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/snippets/snippetprunerserialization/SnippetPrunerSerialization.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. // **************************************************************************** // This snippet illustrates the usage of PxPruningStructure. // // It creates a box stack, then prepares a pruning structure. This structure // together with the actors is serialized into a collection. When the collection // is added to the scene, the actor's scene query shape AABBs are directly merged // into the current scene query AABB tree through the precomputed pruning structure. // This may unbalance the AABB tree but should provide significant speedup in // case of large world scenarios where parts get streamed in on the fly. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "extensions/PxCollectionExt.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #define MAX_MEMBLOCKS 10 PxU8* gMemBlocks[MAX_MEMBLOCKS]; PxU32 gMemBlockCount = 0; PxReal stackZ = 10.0f; /** Allocates 128 byte aligned memory block for binary serialized data Stores pointer to memory in gMemBlocks for later deallocation */ void* createAlignedBlock(PxU32 size) { PX_ASSERT(gMemBlockCount < MAX_MEMBLOCKS); PxU8* baseAddr = static_cast<PxU8*>(malloc(size + PX_SERIAL_FILE_ALIGN - 1)); gMemBlocks[gMemBlockCount++] = baseAddr; void* alignedBlock = reinterpret_cast<void*>((size_t(baseAddr) + PX_SERIAL_FILE_ALIGN - 1)&~(PX_SERIAL_FILE_ALIGN - 1)); return alignedBlock; } // Create a regular stack, with actors added directly into a scene. void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } // Create a stack where pruning structure is build in runtime and used to merge // the query shapes into the AABB tree. void createStackWithRuntimePrunerStructure(const PxTransform& t, PxU32 size, PxReal halfExtent) { std::vector<PxRigidActor*> actors; PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); // store the actors, will be added later actors.push_back(body); } } shape->release(); // Create pruning structure from given actors. PxPruningStructure* ps = gPhysics->createPruningStructure(&actors[0], PxU32(actors.size())); // Add actors into a scene together with the precomputed pruning structure. gScene->addActors(*ps); ps->release(); } // Create a stack where pruning structure is build in runtime and then stored into a collection. // The collection is stored into a stream and loaded into another stream. The loaded collection // is added to a scene. While the collection is added to the scene the pruning structure is used. void createStackWithSerializedPrunerStructure(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxCollection* collection = PxCreateCollection(); // collection for all the objects PxSerializationRegistry* sr = PxSerialization::createSerializationRegistry(*gPhysics); std::vector<PxRigidActor*> actors; PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i < size; i++) { for (PxU32 j = 0; j < size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); // store the actors, will be added later actors.push_back(body); } } collection->add(*shape); // Create pruner structure from given actors. PxPruningStructure* ps = gPhysics->createPruningStructure(&actors[0], PxU32(actors.size())); // Add the pruning structure into the collection. Adding the pruning structure will automatically // add the actors from which the collection was build. collection->add(*ps); PxSerialization::complete(*collection, *sr); // Store the collection into a stream. PxDefaultMemoryOutputStream outStream; PxSerialization::serializeCollectionToBinary(outStream, *collection, *sr); collection->release(); // Release the used items added to the collection. ps->release(); for (size_t i = 0; i < actors.size(); i++) { actors[i]->release(); } shape->release(); // Load collection from the stream into and input stream. PxDefaultMemoryInputData inputStream(outStream.getData(), outStream.getSize()); void* alignedBlock = createAlignedBlock(inputStream.getLength()); inputStream.read(alignedBlock, inputStream.getLength()); PxCollection* collection1 = PxSerialization::createCollectionFromBinary(alignedBlock, *sr); // Add collection to the scene. gScene->addCollection(*collection1); // Release objects in collection, the pruning structure must be released before its actors // otherwise actors will still be part of pruning structure PxCollectionExt::releaseObjects(*collection1); collection1->release(); } void initPhysics(bool ) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); // Create a regular stack. createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 3, 2.0f); // Create a stack using the runtime pruner structure usage. createStackWithRuntimePrunerStructure(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 3, 2.0f); // Create a stack using the serialized pruner structure usage. createStackWithSerializedPrunerStructure(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 3, 2.0f); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } // Now that the objects have been released, it's safe to release the space they occupy. for (PxU32 i = 0; i < gMemBlockCount; i++) free(gMemBlocks[i]); gMemBlockCount = 0; PX_RELEASE(gFoundation); printf("SnippetPrunerSerialization done.\n"); } int snippetMain(int, const char*const*) { static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); return 0; }
10,169
C++
38.115384
121
0.736847
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomprofiler/SnippetCustomProfilerRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet CustomProfiler", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,007
C++
34.388235
136
0.759894
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomprofiler/SnippetCustomProfiler.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. // **************************************************************************** // This snippet illustrates how to setup a custom profiler, and potentially // re-route it to PVD's profiling functions. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxReal stackZ = 10.0f; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } static const bool gCallPVDProfilingFunctions = false; class CustomProfilerCallback : public PxProfilerCallback { public: virtual ~CustomProfilerCallback() {} virtual void* zoneStart(const char* eventName, bool detached, uint64_t contextId) { // Option 1: add your own profiling code here (before calling the PVD function). // If you call the PVD profiling function below, adding your own profiling code here // means it will capture the cost of the PVD zoneStart function. // NB: we don't have an actual profiler implementation in the snippet so we just call printf instead printf("start: %s\n", eventName); // Optional: call the PVD function if you want to see the profiling results in PVD. void* profilerData = gCallPVDProfilingFunctions ? gPvd->zoneStart(eventName, detached, contextId) : NULL; // Option 2: add your own profiling code here (after calling the PVD function). // If you call the PVD profiling function above, adding your own profiling code here // means its cost will be captured by the PVD profiler. return profilerData; } virtual void zoneEnd(void* profilerData, const char* eventName, bool detached, uint64_t contextId) { // Option 2: add your own profiling code here (before calling the PVD function). // If you call the PVD profiling function below, adding your own profiling code here // means its cost will be captured by the PVD profiler. // Optional: call the PVD function if you want to see the profiling results in PVD. if(gCallPVDProfilingFunctions) gPvd->zoneEnd(profilerData, eventName, detached, contextId); // Option 1: add your own profiling code here (after calling the PVD function). // If you call the PVD profiling function above, adding your own profiling code here // means it will capture the cost of the PVD zoneEnd function. // NB: we don't have an actual profiler implementation in the snippet so we just call printf instead printf("end: %s\n", eventName); } }gCustomProfilerCallback; void initPhysics(bool interactive) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); // During the "connect" call, PVD sets itself up as the profiler if PxPvdInstrumentationFlag::ePROFILE is used. // That is, it internally calls PxSetProfilerCallback() to setup its own profiling callback. Any calls to // PxSetProfilerCallback() prior to calling "connect" is thus lost. gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); // This call should be performed after PVD is initialized, otherwise it will have no effect. PxSetProfilerCallback(&gCustomProfilerCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<5;i++) createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); if(!interactive) createDynamic(PxTransform(PxVec3(0,40,100)), PxSphereGeometry(10), PxVec3(0,-50,-100)); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); #if (PX_DEBUG || PX_CHECKED || PX_PROFILE) printf("SnippetCustomProfiler done.\n"); #else printf("Warning: SnippetCustomProfiler does not capture the profiler timings in release build.\n"); #endif } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case 'B': createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); break; case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
8,365
C++
37.376147
120
0.737717
NVIDIA-Omniverse/PhysX/physx/snippets/snippetserialization/SnippetSerialization.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. // **************************************************************************** // This snippet illustrates the use of binary and xml serialization // // Note: RepX/Xml serialization has been DEPRECATED. // // It creates a chain of boxes and serializes them as two collections: // a collection with shared objects and a collection with actors and joints // which can be instantiated multiple times. // // Then physics is setup based on the serialized data. The collection with the // actors and the joints is instantiated multiple times with different // transforms. // // Finally phyics is teared down again, including deallocation of memory // occupied by deserialized objects (in the case of binary serialization). // // **************************************************************************** #include "PxPhysicsAPI.h" #include "foundation/PxMemory.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static bool gUseBinarySerialization = false; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxPvd* gPvd = NULL; #define MAX_MEMBLOCKS 10 static PxU8* gMemBlocks[MAX_MEMBLOCKS]; static PxU32 gMemBlockCount = 0; /** Creates two example collections: - collection with actors and joints that can be instantiated multiple times in the scene - collection with shared objects */ void createCollections(PxCollection*& sharedCollection, PxCollection*& actorCollection, PxSerializationRegistry& sr) { PxMaterial* material = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxReal halfLength = 2.0f, height = 25.0f; PxVec3 offset(halfLength, 0, 0); PxRigidActor* prevActor = PxCreateStatic(*gPhysics, PxTransform(PxVec3(0,height,0)), PxSphereGeometry(halfLength), *material, PxTransform(offset)); PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfLength, 1.0f, 1.0f), *material); for(PxU32 i=1; i<8;i++) { PxTransform tm(PxVec3(PxReal(i*2)* halfLength, height, 0)); PxRigidDynamic* dynamic = gPhysics->createRigidDynamic(tm); dynamic->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*dynamic, 10.0f); PxSphericalJointCreate(*gPhysics, prevActor, PxTransform(offset), dynamic, PxTransform(-offset)); prevActor = dynamic; } sharedCollection = PxCreateCollection(); // collection for all the shared objects actorCollection = PxCreateCollection(); // collection for all the nonshared objects sharedCollection->add(*shape); PxSerialization::complete(*sharedCollection, sr); // chases the pointer from shape to material, and adds it PxSerialization::createSerialObjectIds(*sharedCollection, PxSerialObjectId(77)); // arbitrary choice of base for references to shared objects actorCollection->add(*prevActor); PxSerialization::complete(*actorCollection, sr, sharedCollection, true); // chases all pointers and recursively adds actors and joints } /** Allocates 128 byte aligned memory block for binary serialized data Stores pointer to memory in gMemBlocks for later deallocation */ void* createAlignedBlock(PxU32 size) { PX_ASSERT(gMemBlockCount < MAX_MEMBLOCKS); PxU8* baseAddr = static_cast<PxU8*>(malloc(size+PX_SERIAL_FILE_ALIGN-1)); gMemBlocks[gMemBlockCount++] = baseAddr; void* alignedBlock = reinterpret_cast<void*>((size_t(baseAddr)+PX_SERIAL_FILE_ALIGN-1)&~(PX_SERIAL_FILE_ALIGN-1)); return alignedBlock; } /** Create objects, add them to collections and serialize the collections to the steams gSharedStream and gActorStream This function doesn't setup the gPhysics global as the corresponding physics object is only used locally */ void serializeObjects(PxOutputStream& sharedStream, PxOutputStream& actorStream) { PxSerializationRegistry* sr = PxSerialization::createSerializationRegistry(*gPhysics); PxCollection* sharedCollection = NULL; PxCollection* actorCollection = NULL; createCollections(sharedCollection, actorCollection, *sr); // Alternatively to using PxDefaultMemoryOutputStream it would be possible to serialize to files using // PxDefaultFileOutputStream or a similar implementation of PxOutputStream. if (gUseBinarySerialization) { PxSerialization::serializeCollectionToBinary(sharedStream, *sharedCollection, *sr); PxSerialization::serializeCollectionToBinary(actorStream, *actorCollection, *sr, sharedCollection); } else { PxSerialization::serializeCollectionToXml(sharedStream, *sharedCollection, *sr); PxSerialization::serializeCollectionToXml(actorStream, *actorCollection, *sr, NULL, sharedCollection); } actorCollection->release(); sharedCollection->release(); sr->release(); } /** Deserialize shared data and use resulting collection to deserialize and instance actor collections */ void deserializeObjects(PxInputData& sharedData, PxInputData& actorData, const PxCookingParams& params) { PxSerializationRegistry* sr = PxSerialization::createSerializationRegistry(*gPhysics); PxCollection* sharedCollection = NULL; { if (gUseBinarySerialization) { void* alignedBlock = createAlignedBlock(sharedData.getLength()); sharedData.read(alignedBlock, sharedData.getLength()); sharedCollection = PxSerialization::createCollectionFromBinary(alignedBlock, *sr); } else { sharedCollection = PxSerialization::createCollectionFromXml(sharedData, params, *sr); } } // Deserialize collection and instantiate objects twice, each time with a different transform PxTransform transforms[2] = { PxTransform(PxVec3(-5.0f, 0.0f, 0.0f)), PxTransform(PxVec3(5.0f, 0.0f, 0.0f)) }; for (PxU32 i = 0; i < 2; i++) { PxCollection* collection = NULL; // If the PxInputData actorData would refer to a file, it would be better to avoid reading from it twice. // This could be achieved by reading the file once to memory, and then working with copies. // This is particulary practical when using binary serialization, where the data can be directly // converted to physics objects. actorData.seek(0); if (gUseBinarySerialization) { void* alignedBlock = createAlignedBlock(actorData.getLength()); actorData.read(alignedBlock, actorData.getLength()); collection = PxSerialization::createCollectionFromBinary(alignedBlock, *sr, sharedCollection); } else { collection = PxSerialization::createCollectionFromXml(actorData, params, *sr, sharedCollection); } for (PxU32 o = 0; o < collection->getNbObjects(); o++) { PxRigidActor* rigidActor = collection->getObject(o).is<PxRigidActor>(); if (rigidActor) { PxTransform globalPose = rigidActor->getGlobalPose(); globalPose = globalPose.transform(transforms[i]); rigidActor->setGlobalPose(globalPose); } } gScene->addCollection(*collection); collection->release(); } sharedCollection->release(); PxMaterial* material; gPhysics->getMaterials(&material,1); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *material); gScene->addActor(*groundPlane); sr->release(); } /** Initializes physics and creates a scene */ void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } } void stepPhysics() { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } /** Releases all physics objects, including memory blocks containing deserialized data */ void cleanupPhysics() { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); // releases all objects if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } // Now that the objects have been released, it's safe to release the space they occupy for (PxU32 i = 0; i < gMemBlockCount; i++) free(gMemBlocks[i]); gMemBlockCount = 0; PX_RELEASE(gFoundation); } int snippetMain(int, const char*const*) { initPhysics(); // Alternatively PxDefaultFileOutputStream could be used PxDefaultMemoryOutputStream sharedOutputStream; PxDefaultMemoryOutputStream actorOutputStream; serializeObjects(sharedOutputStream, actorOutputStream); cleanupPhysics(); initPhysics(); // Alternatively PxDefaultFileInputData could be used PxDefaultMemoryInputData sharedInputStream(sharedOutputStream.getData(), sharedOutputStream.getSize()); PxDefaultMemoryInputData actorInputStream(actorOutputStream.getData(), actorOutputStream.getSize()); PxTolerancesScale scale; const PxCookingParams params(scale); deserializeObjects(sharedInputStream, actorInputStream, params); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 250; for(PxU32 i=0; i<frameCount; i++) stepPhysics(); cleanupPhysics(); printf("SnippetSerialization done.\n"); #endif return 0; }
11,630
C++
36.519355
148
0.756148
NVIDIA-Omniverse/PhysX/physx/snippets/snippetserialization/SnippetSerializationRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(); extern void stepPhysics(); extern void cleanupPhysics(); namespace { Snippets::Camera* sCamera; void renderCallback() { Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); stepPhysics(); } void exitCallback(void) { delete sCamera; cleanupPhysics(); printf("SnippetSerialization done.\n"); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet Serialization", sCamera, NULL, renderCallback, exitCallback); glutMainLoop(); } #endif
2,942
C++
33.623529
136
0.754929
NVIDIA-Omniverse/PhysX/physx/snippets/snippetisosurface/SnippetIsosurfaceRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "PxIsosurfaceExtraction.h" #include "foundation/PxArray.h" #define USE_CUDA_INTEROP (!PX_PUBLIC_RELEASE) #define CUDA_SUCCESS 0 #define SHOW_SOLID_SDF_SLICE 0 #define IDX(i, j, k, offset) ((i) + dimX * ((j) + dimY * ((k) + dimZ * (offset)))) using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxPBDParticleSystem* getParticleSystem(); extern PxParticleBuffer* getParticleBuffer(); #if PX_SUPPORT_GPU_PHYSX extern PxArray<PxVec4> gIsosurfaceVertices; extern PxArray<PxU32> gIsosurfaceIndices; extern PxArray<PxVec4> gIsosurfaceNormals; extern PxIsosurfaceExtractor* gIsosurfaceExtractor; extern void* gVerticesGpu; extern void* gNormalsGpu; extern void* gInterleavedVerticesAndNormalsGpu; #endif namespace { Snippets::Camera* sCamera; #if PX_SUPPORT_GPU_PHYSX #if USE_CUDA_INTEROP bool directGpuRendering = true; #else bool directGpuRendering = false; #endif Snippets::SharedGLBuffer sPosBuffer; Snippets::SharedGLBuffer sNormalBuffer; Snippets::SharedGLBuffer sTriangleBuffer; Snippets::SharedGLBuffer sInterleavedPosNormalBuffer; Snippets::SharedGLBuffer sParticlePosBuffer; void onBeforeRenderParticles() { PxPBDParticleSystem* particleSystem = getParticleSystem(); if (particleSystem) { PxParticleBuffer* userBuffer = getParticleBuffer(); PxVec4* positions = userBuffer->getPositionInvMasses(); const PxU32 numParticles = userBuffer->getNbActiveParticles(); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); cudaContextManager->acquireContext(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyDtoH(sParticlePosBuffer.map(), CUdeviceptr(positions), sizeof(PxVec4) * numParticles); cudaContextManager->releaseContext(); } } void renderParticles() { sParticlePosBuffer.unmap(); sPosBuffer.unmap(); sNormalBuffer.unmap(); sTriangleBuffer.unmap(); if (directGpuRendering) { PxVec3 color(0.5f, 0.5f, 1); Snippets::DrawMeshIndexed(sInterleavedPosNormalBuffer.vbo, sTriangleBuffer.vbo, gIsosurfaceExtractor->getNumTriangles(), color); //PxVec3 particleColor(1.0f, 1.0f, 0.0f); //Snippets::DrawPoints(sParticlePosBuffer.vbo, sParticlePosBuffer.size / sizeof(PxVec4), particleColor, 2.f); } else { //Draw a triangle mesh where the data gets copied to the host and back to the device for rendering Snippets::renderMesh(gIsosurfaceExtractor->getNumVertices(), gIsosurfaceVertices.begin(), gIsosurfaceExtractor->getNumTriangles(), gIsosurfaceIndices.begin(), PxVec3(1, 0, 0), gIsosurfaceNormals.begin()); //Check for unused vertices PxVec4 marker(10000000, 0, 0, 0); PxU32 numIndices = 3 * gIsosurfaceExtractor->getNumTriangles(); for (PxU32 i = 0; i < numIndices; ++i) { gIsosurfaceNormals[gIsosurfaceIndices[i]] = marker; } for (PxU32 i = 0; i < gIsosurfaceExtractor->getNumVertices(); ++i) { if (gIsosurfaceNormals[i] != marker) { printf("Isosurface mesh contains unreferenced vertices\n"); } } } Snippets::DrawFrame(PxVec3(0, 0, 0)); } void allocParticleBuffers() { PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); //PxPBDParticleSystem* particleSystem = getParticleSystem(); PxU32 maxVertices = gIsosurfaceExtractor->getMaxVertices(); PxU32 maxIndices = gIsosurfaceExtractor->getMaxTriangles() * 3; sParticlePosBuffer.initialize(cudaContextManager); sParticlePosBuffer.allocate(gIsosurfaceExtractor->getMaxParticles() * sizeof(PxVec4)); sPosBuffer.initialize(cudaContextManager); sPosBuffer.allocate(maxVertices * sizeof(PxVec4)); gVerticesGpu = sPosBuffer.map(); sNormalBuffer.initialize(cudaContextManager); sNormalBuffer.allocate(maxVertices * sizeof(PxVec4)); gNormalsGpu = sNormalBuffer.map(); sTriangleBuffer.initialize(cudaContextManager); sTriangleBuffer.allocate(maxIndices * sizeof(PxU32)); sInterleavedPosNormalBuffer.initialize(cudaContextManager); sInterleavedPosNormalBuffer.allocate(2 * maxVertices * sizeof(PxVec3)); gInterleavedVerticesAndNormalsGpu = sInterleavedPosNormalBuffer.map(); if (directGpuRendering) { gIsosurfaceExtractor->setResultBufferDevice(reinterpret_cast<PxVec4*>(sPosBuffer.map()), reinterpret_cast<PxU32*>(sTriangleBuffer.map()), reinterpret_cast<PxVec4*>(sNormalBuffer.map())); } else { gIsosurfaceExtractor->setResultBufferHost(gIsosurfaceVertices.begin(), gIsosurfaceIndices.begin(), gIsosurfaceNormals.begin()); gInterleavedVerticesAndNormalsGpu = NULL; } } void clearupParticleBuffers() { sParticlePosBuffer.release(); sPosBuffer.release(); sNormalBuffer.release(); sTriangleBuffer.release(); sInterleavedPosNormalBuffer.release(); } #else void onBeforeRenderParticles() { } void renderParticles() { } void allocParticleBuffers() { } void clearupParticleBuffers() { } #endif void renderCallback() { onBeforeRenderParticles(); stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } renderParticles(); Snippets::showFPS(); Snippets::finishRender(); } void cleanup() { gIsosurfaceVertices.reset(); gIsosurfaceIndices.reset(); gIsosurfaceNormals.reset(); delete sCamera; clearupParticleBuffers(); cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(15.0f, 10.0f, 15.0f), PxVec3(-0.6f, -0.2f, -0.6f)); Snippets::setupDefault("PhysX Snippet Isosurface", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); Snippets::initFPS(); allocParticleBuffers(); glutMainLoop(); cleanup(); } #endif
8,307
C++
29.656826
137
0.754183
NVIDIA-Omniverse/PhysX/physx/snippets/snippetisosurface/SnippetIsosurface.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. // **************************************************************************** // This snippet illustrates isosurface extraction from particle-based fluid // simulation. The fluid simulation is performed using position-based dynamics. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxParticleExt.h" #include "PxIsosurfaceExtraction.h" #include "PxAnisotropy.h" #include "PxSmoothing.h" #include "gpu/PxGpu.h" #include "gpu/PxPhysicsGpu.h" #include "PxArrayConverter.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleBuffer* gParticleBuffer = NULL; static bool gIsRunning = true; PxRigidDynamic* movingWall; using namespace ExtGpu; PxArray<PxVec4> gIsosurfaceVertices; PxArray<PxU32> gIsosurfaceIndices; PxArray<PxVec4> gIsosurfaceNormals; PxIsosurfaceExtractor* gIsosurfaceExtractor; void* gVerticesGpu; void* gNormalsGpu; void* gInterleavedVerticesAndNormalsGpu; class IsosurfaceCallback : public PxParticleSystemCallback { public: PxIsosurfaceExtractor* mIsosurfaceExtractor; PxAnisotropyGenerator* mAnisotropyGenerator; PxSmoothedPositionGenerator* mSmoothedPositionGenerator; PxArrayConverter* mArrayConverter; PxVec4* mSmoothedPositionsDeviceBuffer; PxVec4* mAnisotropyDeviceBuffer1; PxVec4* mAnisotropyDeviceBuffer2; PxVec4* mAnisotropyDeviceBuffer3; PxU32 mMaxVertices; PxCudaContextManager* mCudaContextManager; IsosurfaceCallback() : mIsosurfaceExtractor(NULL), mAnisotropyGenerator(NULL) { } void initialize(PxCudaContextManager* cudaContextManager, const PxSparseGridParams& sparseGridParams, PxIsosurfaceParams& p, PxU32 maxNumVertices, PxU32 maxNumTriangles, PxU32 maxNumParticles) { mCudaContextManager = cudaContextManager; mMaxVertices = maxNumVertices; /*ExtGpu::PxIsosurfaceParams p; p.isosurfaceValue =threshold; p.clearFilteringPasses();*/ PxPhysicsGpu* pxGpu = PxGetPhysicsGpu(); mSmoothedPositionGenerator = pxGpu->createSmoothedPositionGenerator(cudaContextManager, maxNumParticles, 0.5f); PX_DEVICE_ALLOC(cudaContextManager, mSmoothedPositionsDeviceBuffer, maxNumParticles); mSmoothedPositionGenerator->setResultBufferDevice(mSmoothedPositionsDeviceBuffer); //Too small minAnisotropy values will shrink particles to ellipsoids that are smaller than a isosurface grid cell which can lead to unpleasant aliasing/flickering PxReal minAnisotropy = 1.0f;// 0.5f; // 0.1f; PxReal anisotropyScale = 5.0f; mAnisotropyGenerator = pxGpu->createAnisotropyGenerator(cudaContextManager, maxNumParticles, anisotropyScale, minAnisotropy, 2.0f); PX_DEVICE_ALLOC(cudaContextManager, mAnisotropyDeviceBuffer1, maxNumParticles); PX_DEVICE_ALLOC(cudaContextManager, mAnisotropyDeviceBuffer2, maxNumParticles); PX_DEVICE_ALLOC(cudaContextManager, mAnisotropyDeviceBuffer3, maxNumParticles); mAnisotropyGenerator->setResultBufferDevice(mAnisotropyDeviceBuffer1, mAnisotropyDeviceBuffer2, mAnisotropyDeviceBuffer3); gIsosurfaceVertices.resize(maxNumVertices); gIsosurfaceNormals.resize(maxNumVertices); gIsosurfaceIndices.resize(3 * maxNumTriangles); mIsosurfaceExtractor = pxGpu->createSparseGridIsosurfaceExtractor(cudaContextManager, sparseGridParams, p, maxNumParticles, maxNumVertices, maxNumTriangles); gIsosurfaceExtractor = mIsosurfaceExtractor; mArrayConverter = pxGpu->createArrayConverter(cudaContextManager); } virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) { #if RENDER_SNIPPET PxGpuParticleSystem& p = *gpuParticleSystem.mHostPtr; if (mAnisotropyGenerator) { mAnisotropyGenerator->generateAnisotropy(gpuParticleSystem.mDevicePtr, p.mCommonData.mMaxParticles, stream); } mSmoothedPositionGenerator->generateSmoothedPositions(gpuParticleSystem.mDevicePtr, p.mCommonData.mMaxParticles, stream); mIsosurfaceExtractor->extractIsosurface(mSmoothedPositionsDeviceBuffer/*reinterpret_cast<PxVec4*>(p.mUnsortedPositions_InvMass)*/, p.mCommonData.mNumParticles, stream, p.mUnsortedPhaseArray, PxParticlePhaseFlag::eParticlePhaseFluid, NULL, mAnisotropyDeviceBuffer1, mAnisotropyDeviceBuffer2, mAnisotropyDeviceBuffer3, p.mCommonData.mParticleContactDistance); if (gInterleavedVerticesAndNormalsGpu) { //Bring the data into a form that is better suited for rendering mArrayConverter->interleaveGpuBuffers(static_cast<PxVec4*>(gVerticesGpu), static_cast<PxVec4*>(gNormalsGpu), mMaxVertices, static_cast<PxVec3*>(gInterleavedVerticesAndNormalsGpu), stream); } #else PX_UNUSED(gpuParticleSystem); PX_UNUSED(stream); #endif } virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { } virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { } virtual ~IsosurfaceCallback() { } void release() { gIsosurfaceVertices.reset(); gIsosurfaceIndices.reset(); gIsosurfaceNormals.reset(); mIsosurfaceExtractor->release(); PX_DELETE(mIsosurfaceExtractor); PX_DELETE(mArrayConverter); if (mAnisotropyGenerator) { mAnisotropyGenerator->release(); mCudaContextManager->freeDeviceBuffer(mAnisotropyDeviceBuffer1); mCudaContextManager->freeDeviceBuffer(mAnisotropyDeviceBuffer2); mCudaContextManager->freeDeviceBuffer(mAnisotropyDeviceBuffer3); } if (mSmoothedPositionGenerator) { mSmoothedPositionGenerator->release(); mCudaContextManager->freeDeviceBuffer(mSmoothedPositionsDeviceBuffer); } } }; static IsosurfaceCallback gIsosuraceCallback; // ----------------------------------------------------------------------------------------------------------------- static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); } // ----------------------------------------------------------------------------------------------------------------- static PxReal initParticles(const PxU32 numX, const PxU32 numY, const PxU32 numZ, const PxVec3& position = PxVec3(0, 0, 0), const PxReal particleSpacing = 0.2f, const PxReal fluidDensity = 1000.f) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return -1; const PxU32 maxParticles = numX * numY * numZ; const PxReal fluidRestOffset = 0.5f * particleSpacing; // Material setup PxPBDMaterial* defaultMat = gPhysics->createPBDMaterial(0.05f, 0.05f, 0.f, 0.001f, 0.5f, 0.005f, 0.01f, 0.f, 0.f); PxPBDParticleSystem *particleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager, 96); gParticleSystem = particleSystem; bool highCohesion = false; if (highCohesion) { defaultMat->setViscosity(50.0f); defaultMat->setSurfaceTension(0.f); defaultMat->setCohesion(100.0f); particleSystem->setSolverIterationCounts(20, 0); } else { defaultMat->setViscosity(0.001f); defaultMat->setSurfaceTension(0.00704f); defaultMat->setCohesion(0.704f); defaultMat->setVorticityConfinement(10.f); } // General particle system setting const PxReal restOffset = fluidRestOffset / 0.6f; const PxReal solidRestOffset = restOffset; const PxReal particleMass = fluidDensity * 1.333f * 3.14159f * particleSpacing * particleSpacing * particleSpacing; particleSystem->setRestOffset(restOffset); particleSystem->setContactOffset(restOffset + 0.01f); particleSystem->setParticleContactOffset(fluidRestOffset / 0.6f); particleSystem->setSolidRestOffset(solidRestOffset); particleSystem->setFluidRestOffset(fluidRestOffset); particleSystem->enableCCD(false); particleSystem->setMaxVelocity(100.f); gScene->addActor(*particleSystem); // Create particles and add them to the particle system const PxU32 particlePhase = particleSystem->createPhase(defaultMat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseFluid | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); PxU32* phase = cudaContextManager->allocPinnedHostBuffer<PxU32>(maxParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxReal x = position.x; PxReal y = position.y; PxReal z = position.z; for (PxU32 i = 0; i < numX; ++i) { for (PxU32 j = 0; j < numY; ++j) { for (PxU32 k = 0; k < numZ; ++k) { const PxU32 index = i * (numY * numZ) + j * numZ + k; PxVec4 pos(x, y, z, 1.0f / particleMass); phase[index] = particlePhase; positionInvMass[index] = pos; velocity[index] = PxVec4(0.0f); z += particleSpacing; } z = position.z; y += particleSpacing; } y = position.y; x += particleSpacing; } ExtGpu::PxParticleBufferDesc bufferDesc; bufferDesc.maxParticles = maxParticles; bufferDesc.numActiveParticles = maxParticles; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phase; gParticleBuffer = physx::ExtGpu::PxCreateAndPopulateParticleBuffer(bufferDesc, cudaContextManager); gParticleSystem->addParticleBuffer(gParticleBuffer); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phase); return particleSpacing; } PxPBDParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleBuffer* getParticleBuffer() { return gParticleBuffer; } void addKinematicBox(PxVec3 boxSize, PxVec3 boxCenter) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(boxSize.x, boxSize.y, boxSize.z), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(boxCenter)); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); } // ----------------------------------------------------------------------------------------------------------------- void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup PBF bool useMovingWall = true; const PxReal fluidDensity = 1000.0f; PxU32 numX = 50; PxU32 numY = 200; PxU32 numZ = 100; PxReal particleSpacing = initParticles(numX, numY, numZ, PxVec3(1.5f, /*3.f*/8, -4.f), 0.1f, fluidDensity); addKinematicBox(PxVec3(7.5f,0.25f,7.5f), PxVec3(3,7.5f,0)); addKinematicBox(PxVec3(0.25f, 7.5f, 7.5f), PxVec3(-2.f, 7.5f+ 7.5f+0.5f, 0)); // Setup container gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.0f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(-1.f, 0.f, 0.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, 1.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, -1.f, 7.5f), *gMaterial)); if (!useMovingWall) { gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(1.f, 0.f, 0.f, 7.5f), *gMaterial)); movingWall = NULL; } else { PxTransform trans = PxTransformFromPlaneEquation(PxPlane(1.f, 0.f, 0.f, 20.f)); movingWall = gPhysics->createRigidDynamic(trans); movingWall->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); PxRigidActorExt::createExclusiveShape(*movingWall, PxPlaneGeometry(), *gMaterial); gScene->addActor(*movingWall); } const PxReal fluidRestOffset = 0.5f * particleSpacing; PxSparseGridParams sgIsosurfaceParams; sgIsosurfaceParams.subgridSizeX = 16; sgIsosurfaceParams.subgridSizeY = 16; sgIsosurfaceParams.subgridSizeZ = 16; sgIsosurfaceParams.haloSize = 0; sgIsosurfaceParams.maxNumSubgrids = 4096; sgIsosurfaceParams.gridSpacing = 1.5f*fluidRestOffset; PxIsosurfaceParams p; p.particleCenterToIsosurfaceDistance = 1.6f*fluidRestOffset; p.clearFilteringPasses(); p.numMeshSmoothingPasses = 4; p.numMeshNormalSmoothingPasses = 4; gIsosuraceCallback.initialize(gScene->getCudaContextManager(), sgIsosurfaceParams, p, 2*1024 * 1024, 4*1024 * 1024, numX * numY * numZ); gParticleSystem->setParticleSystemCallback(&gIsosuraceCallback); // Setup rigid bodies const PxReal dynamicsDensity = fluidDensity * 0.5f; const PxReal boxSize = 1.0f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 8.0f, 10, 7.5f))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } // --------------------------------------------------- PxI32 stepCounter = 0; void stepPhysics(bool /*interactive*/) { if (gIsRunning) { const PxReal dt = 1.0f / 60.0f; if (movingWall) { static bool moveOut = false; const PxReal speed = stepCounter > 1200 ? 2.0f : 0.0f; PxTransform pose = movingWall->getGlobalPose(); if (moveOut) { pose.p.x += dt * speed; if (pose.p.x > -7.f) moveOut = false; } else { pose.p.x -= dt * speed; if (pose.p.x < -11.5f) moveOut = true; } movingWall->setKinematicTarget(pose); } gScene->simulate(dt); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); ++stepCounter; } } void cleanupPhysics(bool /*interactive*/) { gParticleSystem->setParticleSystemCallback(NULL); gIsosuraceCallback.release(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetIsosurface done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
18,083
C++
34.389432
234
0.744069
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonebvh/SnippetStandaloneBVH.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. // **************************************************************************** // This snippet illustrates how to use a standalone PxBVH. // It creates a small custom scene (no PxScene) and creates a PxBVH for the // scene objects. The BVH is then used to raytrace the scene. The snippet // also shows how to update the BVH after the objects have moved. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; // Change this to use either refit the full BVH or just a subset of nodes static const bool gUsePartialRefit = false; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; namespace { class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void createBVH(); void render(); bool raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxGeomRaycastHit& hit) const; void updateObjects(); struct Object { PxGeometryHolder mGeom; PxTransform mPose; }; PxArray<Object> mObjects; PxBVH* mBVH; }; CustomScene::CustomScene() : mBVH(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mBVH); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { Object obj; obj.mGeom.storeAny(geom); obj.mPose = pose; mObjects.pushBack(obj); } void CustomScene::updateObjects() { static float time = 0.0f; time += 0.01f; if(gUsePartialRefit) { // This version is more efficient if you have to update a small subset of nodes const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i+=3) // Don't update all objects { // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); Object& obj = mObjects[i]; obj.mPose.p.x = sinf(time)*cosf(time+coeff)*10.0f; obj.mPose.p.y = sinf(time*1.17f)*cosf(time*1.17f+coeff)*2.0f; obj.mPose.p.z = sinf(time*0.33f)*cosf(time*0.33f+coeff)*10.0f; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; obj.mPose.q = PxQuat(rot); obj.mPose.q.normalize(); PxBounds3 newBounds; PxGeometryQuery::computeGeomBounds(newBounds, obj.mGeom.any(), obj.mPose); mBVH->updateBounds(i, newBounds); } mBVH->partialRefit(); } else { // This version is more efficient if you have to update all nodes PxBounds3* bounds = mBVH->getBoundsForModification(); const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); Object& obj = mObjects[i]; obj.mPose.p.x = sinf(time)*cosf(time+coeff)*10.0f; obj.mPose.p.y = sinf(time*1.17f)*cosf(time*1.17f+coeff)*2.0f; obj.mPose.p.z = sinf(time*0.33f)*cosf(time*0.33f+coeff)*10.0f; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; obj.mPose.q = PxQuat(rot); obj.mPose.q.normalize(); PxGeometryQuery::computeGeomBounds(bounds[i], obj.mGeom.any(), obj.mPose); } mBVH->refit(); } } void CustomScene::createBVH() { const PxU32 nbObjects = mObjects.size(); PxBounds3* bounds = new PxBounds3[nbObjects]; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PxGeometryQuery::computeGeomBounds(bounds[i], obj.mGeom.any(), obj.mPose); } PxBVHDesc bvhDesc; bvhDesc.bounds.count = nbObjects; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); bvhDesc.numPrimsPerLeaf = 1; mBVH = PxCreateBVH(bvhDesc); delete [] bounds; } struct LocalCB : PxBVH::RaycastCallback { LocalCB(const CustomScene& scene, const PxVec3& origin, const PxVec3& dir, PxGeomRaycastHit& hit) : mScene (scene), mHit (hit), mOrigin (origin), mDir (dir), mStatus (false) { } virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) { const CustomScene::Object& obj = mScene.mObjects[boundsIndex]; if(PxGeometryQuery::raycast(mOrigin, mDir, obj.mGeom.any(), obj.mPose, distance, PxHitFlag::eDEFAULT, 1, &mLocalHit, sizeof(PxGeomRaycastHit))) { if(mLocalHit.distance<distance) { distance = mLocalHit.distance; mHit = mLocalHit; mStatus = true; } } return true; } const CustomScene& mScene; PxGeomRaycastHit& mHit; PxGeomRaycastHit mLocalHit; const PxVec3& mOrigin; const PxVec3& mDir; bool mStatus; PX_NOCOPY(LocalCB) }; bool CustomScene::raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxGeomRaycastHit& hit) const { if(!mBVH) return false; LocalCB CB(*this, origin, unitDir, hit); mBVH->raycast(origin, unitDir, maxDist, CB); return CB.mStatus; } void CustomScene::render() { updateObjects(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } struct DrawBounds : PxBVH::TraversalCallback { virtual bool visitNode(const PxBounds3& bounds) { Snippets::DrawBounds(bounds); return true; } virtual bool reportLeaf(PxU32, const PxU32*) { return true; } }drawBounds; mBVH->traverse(drawBounds); const PxU32 screenWidth = Snippets::getScreenWidth(); const PxU32 screenHeight = Snippets::getScreenHeight(); Snippets::Camera* sCamera = Snippets::getCamera(); const PxVec3 camPos = sCamera->getEye(); const PxVec3 camDir = sCamera->getDir(); #if PX_DEBUG const PxU32 RAYTRACING_RENDER_WIDTH = 64; const PxU32 RAYTRACING_RENDER_HEIGHT = 64; #else const PxU32 RAYTRACING_RENDER_WIDTH = 256; const PxU32 RAYTRACING_RENDER_HEIGHT = 256; #endif const PxU32 textureWidth = RAYTRACING_RENDER_WIDTH; const PxU32 textureHeight = RAYTRACING_RENDER_HEIGHT; GLubyte* pixels = new GLubyte[textureWidth*textureHeight*4]; const float fScreenWidth = float(screenWidth)/float(RAYTRACING_RENDER_WIDTH); const float fScreenHeight = float(screenHeight)/float(RAYTRACING_RENDER_HEIGHT); GLubyte* buffer = pixels; for(PxU32 j=0;j<RAYTRACING_RENDER_HEIGHT;j++) { const PxU32 yi = PxU32(fScreenHeight*float(j)); for(PxU32 i=0;i<RAYTRACING_RENDER_WIDTH;i++) { const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = Snippets::computeWorldRay(xi, yi, camDir); PxGeomRaycastHit hit; if(raycast(camPos, dir, 5000.0f, hit)) { buffer[0] = 128+GLubyte(hit.normal.x*127.0f); buffer[1] = 128+GLubyte(hit.normal.y*127.0f); buffer[2] = 128+GLubyte(hit.normal.z*127.0f); buffer[3] = 255; } else { buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 255; } buffer+=4; } } const GLuint texID = Snippets::CreateTexture(textureWidth, textureHeight, pixels, false); #if PX_DEBUG Snippets::DisplayTexture(texID, 256, 10); #else Snippets::DisplayTexture(texID, RAYTRACING_RENDER_WIDTH, 10); #endif delete [] pixels; Snippets::ReleaseTexture(texID); #endif } } static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static CustomScene* gScene = NULL; void renderScene() { if(gScene) gScene->render(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } gScene = new CustomScene; gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f))); gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f))); gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f))); gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f))); gScene->createBVH(); initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetStandaloneBVH done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { /* if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); }*/ } int snippetMain(int, const char*const*) { printf("Standalone BVH snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,680
C++
26.329741
146
0.706546
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonebvh/SnippetStandaloneBVHRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet StandaloneBVH", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,901
C++
33.547619
117
0.749741
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcontactmodification/SnippetContactModificationRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern std::vector<PxVec3> gContactPositions; extern std::vector<PxVec3> gContactImpulses; std::vector<PxVec3> gContactVertices; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } if(gContactPositions.size()) { gContactVertices.clear(); for(PxU32 i=0;i<gContactPositions.size();i++) { gContactVertices.push_back(gContactPositions[i]); gContactVertices.push_back(gContactPositions[i]+gContactImpulses[i]*0.1f); } glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(gContactVertices.size())); glDisableClientState(GL_VERTEX_ARRAY); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet ContactReport", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,551
C++
33.823529
136
0.755843
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcontactmodification/SnippetContactModification.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. // **************************************************************************** // This snippet illustrates the use of simple contact reports and contact modification. // // It defines a filter shader function that requests contact modification and // touch reports for all pairs, and a contact callback function that saves // the contact points. It configures the scene to use this filter and callback, // and prints the number of contact reports each frame. If rendering, it renders // each contact as a line whose length and direction are defined by the contact // impulse. // This test sets up a situation that would be unstable without contact modification // due to very large mass ratios. This test uses local mass modification to make // the configuration stable. It also demonstrates how to interpret contact impulses // when local mass modification is used. // Local mass modification can be disabled with the MODIFY_MASS_PROPERTIES #define // to demonstrate the instability if it was not used. // // **************************************************************************** #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; #define MODIFY_MASS_PROPERTIES 1 static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<PxVec3> gContactPositions; std::vector<PxVec3> gContactImpulses; std::vector<PxVec3> gContactLinearImpulses[2]; std::vector<PxVec3> gContactAngularImpulses[2]; static PxFilterFlags contactReportFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(filterData0); PX_UNUSED(filterData1); PX_UNUSED(constantBlockSize); PX_UNUSED(constantBlock); // all initial and persisting reports for everything, with per-point data pairFlags = PxPairFlag::eSOLVE_CONTACT | PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::eMODIFY_CONTACTS; return PxFilterFlag::eDEFAULT; } class ContactModifyCallback: public PxContactModifyCallback { void onContactModify(PxContactModifyPair* const pairs, PxU32 count) { #if MODIFY_MASS_PROPERTIES //We define a maximum mass ratio that we will accept in this test, which is a ratio of 2 const PxReal maxMassRatio = 2.f; for(PxU32 i = 0; i < count; i++) { const PxRigidDynamic* dynamic0 = pairs[i].actor[0]->is<PxRigidDynamic>(); const PxRigidDynamic* dynamic1 = pairs[i].actor[1]->is<PxRigidDynamic>(); if(dynamic0 != NULL && dynamic1 != NULL) { //We only want to perform local mass modification between 2 dynamic bodies because we intend on //normalizing the mass ratios between the pair within a tolerable range PxReal mass0 = dynamic0->getMass(); PxReal mass1 = dynamic1->getMass(); if(mass0 > mass1) { //dynamic0 is heavier than dynamic1 so we will locally increase the mass of dynamic1 //to be half the mass of dynamic0. PxReal ratio = mass0/mass1; if(ratio > maxMassRatio) { PxReal invMassScale = maxMassRatio/ratio; pairs[i].contacts.setInvMassScale1(invMassScale); pairs[i].contacts.setInvInertiaScale1(invMassScale); } } else { //dynamic1 is heavier than dynamic0 so we will locally increase the mass of dynamic0 //to be half the mass of dynamic1. PxReal ratio = mass1/mass0; if(ratio > maxMassRatio) { PxReal invMassScale = maxMassRatio/ratio; pairs[i].contacts.setInvMassScale0(invMassScale); pairs[i].contacts.setInvInertiaScale0(invMassScale); } } } } #endif } }; ContactModifyCallback gContactModifyCallback; static PxU32 extractContactsWithMassScale(const PxContactPair& pair, PxContactPairPoint* userBuffer, PxU32 bufferSize, PxReal& invMassScale0, PxReal& invMassScale1) { const PxU8* contactStream = pair.contactPoints; const PxU8* patchStream = pair.contactPatches; const PxU32* faceIndices = pair.getInternalFaceIndices(); PxU32 nbContacts = 0; if(pair.contactCount && bufferSize) { PxContactStreamIterator iter(patchStream, contactStream, faceIndices, pair.patchCount, pair.contactCount); const PxReal* impulses = reinterpret_cast<const PxReal*>(pair.contactImpulses); PxU32 flippedContacts = (pair.flags & PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED); PxU32 hasImpulses = (pair.flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES); invMassScale0 = iter.getInvMassScale0(); invMassScale1 = iter.getInvMassScale1(); while(iter.hasNextPatch()) { iter.nextPatch(); while(iter.hasNextContact()) { iter.nextContact(); PxContactPairPoint& dst = userBuffer[nbContacts]; dst.position = iter.getContactPoint(); dst.separation = iter.getSeparation(); dst.normal = iter.getContactNormal(); if (!flippedContacts) { dst.internalFaceIndex0 = iter.getFaceIndex0(); dst.internalFaceIndex1 = iter.getFaceIndex1(); } else { dst.internalFaceIndex0 = iter.getFaceIndex1(); dst.internalFaceIndex1 = iter.getFaceIndex0(); } if (hasImpulses) { PxReal impulse = impulses[nbContacts]; dst.impulse = dst.normal * impulse; } else dst.impulse = PxVec3(0.0f); ++nbContacts; if(nbContacts == bufferSize) return nbContacts; } } } return nbContacts; } class ContactReportCallback: public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) { PX_UNUSED(constraints); PX_UNUSED(count); } void onWake(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onSleep(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onTrigger(PxTriggerPair* pairs, PxU32 count) { PX_UNUSED(pairs); PX_UNUSED(count); } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) {} void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) { PX_UNUSED((pairHeader)); std::vector<PxContactPairPoint> contactPoints; for(PxU32 i=0;i<nbPairs;i++) { PxU32 contactCount = pairs[i].contactCount; if(contactCount) { contactPoints.resize(contactCount); PxReal invMassScale[2]; extractContactsWithMassScale(pairs[i], &contactPoints[0], contactCount, invMassScale[0], invMassScale[1]); for(PxU32 j=0;j<contactCount;j++) { gContactPositions.push_back(contactPoints[j].position); //Push back reported contact impulses gContactImpulses.push_back(contactPoints[j].impulse); //Compute the effective linear/angular impulses for each body. //Note that the local mass scaling permits separate scales for invMass and invInertia. for(PxU32 k = 0; k < 2; ++k) { const PxRigidDynamic* dynamic = pairHeader.actors[k]->is<PxRigidDynamic>(); PxVec3 linImpulse(0.f), angImpulse(0.f); if(dynamic != NULL) { PxRigidBodyExt::computeLinearAngularImpulse(*dynamic, dynamic->getGlobalPose(), contactPoints[j].position, k == 0 ? contactPoints[j].impulse : -contactPoints[j].impulse, invMassScale[k], invMassScale[k], linImpulse, angImpulse); } gContactLinearImpulses[k].push_back(linImpulse); gContactAngularImpulses[k].push_back(angImpulse); } } } } } }; static ContactReportCallback gContactReportCallback; static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { PxTransform localTm(PxVec3(0, PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, (i+1)*(i+1)*(i+1)*10.0f); gScene->addActor(*body); } shape->release(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.filterShader = contactReportFilterShader; sceneDesc.simulationEventCallback = &gContactReportCallback; sceneDesc.contactModifyCallback = &gContactModifyCallback; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createStack(PxTransform(PxVec3(0,0.0f,10.0f)), 5, 2.0f); } void stepPhysics(bool /*interactive*/) { gContactPositions.clear(); gContactImpulses.clear(); gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); printf("%d contact reports\n", PxU32(gContactPositions.size())); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetContactModification done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); for(PxU32 i=0; i<250; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,299
C++
35.17647
164
0.72697
NVIDIA-Omniverse/PhysX/physx/snippets/snippetomnipvd/SnippetOmniPvd.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 <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "omnipvd/PxOmniPvd.h" #if PX_SUPPORT_OMNI_PVD #include "../pvdruntime/include/OmniPvdWriter.h" #include "../pvdruntime/include/OmniPvdFileWriteStream.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxOmniPvd* gOmniPvd = NULL; const char* gOmniPvdPath = NULL; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void initPhysXScene() { PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); createDynamic(PxTransform(PxVec3(0, 40, 100)), PxSphereGeometry(10), PxVec3(0, -50, -100)); } void initPhysicsWithOmniPvd() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); if (!gFoundation) { printf("Error : could not create PxFoundation!"); return; } gOmniPvd = PxCreateOmniPvd(*gFoundation); if (!gOmniPvd) { printf("Error : could not create PxOmniPvd!"); return; } OmniPvdWriter* omniWriter = gOmniPvd->getWriter(); if (!omniWriter) { printf("Error : could not get an instance of PxOmniPvdWriter!"); return; } OmniPvdFileWriteStream* fStream = gOmniPvd->getFileWriteStream(); if (!fStream) { printf("Error : could not get an instance of PxOmniPvdFileWriteStream!"); return; } fStream->setFileName(gOmniPvdPath); omniWriter->setWriteStream(static_cast<OmniPvdWriteStream&>(*fStream)); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, NULL, gOmniPvd); if (!gPhysics) { printf("Error : could not create a PhysX instance!"); return; } if (gPhysics->getOmniPvd()) { gPhysics->getOmniPvd()->startSampling(); } else { printf("Error : could not start OmniPvd sampling!"); return; } initPhysXScene(); } void cleanupPhysics() { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PX_RELEASE(gOmniPvd); PX_RELEASE(gFoundation); } bool parseOmniPvdOutputFile(int argc, const char *const* argv) { if (argc != 2 || 0 != strncmp(argv[1], "--omnipvdfile", strlen("--omnipvdfile"))) { printf("SnippetOmniPvd usage:\n" "SnippetOmniPvd " "[--omnipvdfile=<full path and fileName of the output OmniPvd file> ] \n"); return false; } gOmniPvdPath = argv[1] + strlen("--omnipvdfile="); return true; } void stepPhysics() { gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200); break; } } #endif // PX_SUPPORT_OMNI_PVD int snippetMain(int argc, const char *const* argv) { #if PX_SUPPORT_OMNI_PVD if (!parseOmniPvdOutputFile(argc, argv)) { return 1; } #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysicsWithOmniPvd(); static const PxU32 frameCount = 100; for (PxU32 i = 0; i < frameCount; i++) stepPhysics(); cleanupPhysics(); #endif #else PX_UNUSED(argc); PX_UNUSED(argv); printf("PVD is not supported in release build configuration. Please use any of the other build configurations to run this snippet.\n"); #endif // PX_SUPPORT_OMNI_PVD return 0; }
5,835
C++
29.878307
136
0.737789
NVIDIA-Omniverse/PhysX/physx/snippets/snippetomnipvd/SnippetOmniPvdRender.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. #ifdef RENDER_SNIPPET #if PX_SUPPORT_OMNI_PVD #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysicsWithOmniPvd(); extern void stepPhysics(); extern void cleanupPhysics(); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet OmniPvd", sCamera, keyPress, renderCallback, exitCallback); initPhysicsWithOmniPvd(); glutMainLoop(); } #endif // PX_SUPPORT_OMNI_PVD #endif
3,018
C++
33.306818
136
0.75613
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpathtracing/SnippetPathTracing.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. // **************************************************************************** // This snippet illustrates how to use a standalone PxBVH for path-tracing. // // This is an advanced snippet that demonstrates how to use PxBVH in a more // realistic/complex case than SnippetStandaloneBVH. It also reuses some // multithreading code from SnippetMultiThreading, so you should get familiar // with these two snippets first. // // This snippet also illustrates some micro-optimizations (see defines below) // that don't make much difference in a regular game/setup, but can save // milliseconds when running a lot of raycasts. // // The path-tracing code itself is a mashup of various implementations found // online, most notably: // http://aras-p.info/blog/2018/03/28/Daily-Pathtracer-Part-0-Intro/ // https://blog.demofox.org/2020/05/25/casual-shadertoy-path-tracing-1-basic-camera-diffuse-emissive/ // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "foundation/PxMathUtils.h" #include "foundation/PxFPU.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; //#define PRINT_TIMINGS //#define STATS // PT: flags controlling micro optimizations #define OPTIM_SKIP_INTERNAL_SIMD_GUARD 1 // Take care of SSE control register directly in the snippet, skip internal version #define OPTIM_BAKE_MESH_SCALE 1 // Bake scale in mesh vertices (queries against scaled meshes are a bit slower) #define OPTIM_SHADOW_RAY_CODEPATH 1 // Use dedicated codepath for shadow rays (early exit + skip pos/normal hit computations) static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static int gFrameIndex = 0; #if OPTIM_SKIP_INTERNAL_SIMD_GUARD static const PxGeometryQueryFlags gQueryFlags = PxGeometryQueryFlag::Enum(0); #else static const PxGeometryQueryFlags gQueryFlags = PxGeometryQueryFlag::eDEFAULT; #endif namespace { enum MaterialType { Lambert, Metal, Dielectric, }; struct CustomMaterial { MaterialType mType; PxVec3 mAlbedo; PxVec3 mEmissive; float mRoughness; float mRI; }; struct CustomObject { PxGeometryHolder mGeom; PxTransform mPose; CustomMaterial mMaterial; }; struct CustomHit : PxGeomRaycastHit { protected: const CustomObject* mObject; public: PX_FORCE_INLINE void setObject(const CustomObject* obj) { mObject = obj; } PX_FORCE_INLINE const CustomObject* getObject() const { return mObject; } PX_FORCE_INLINE MaterialType getType() const { return mObject->mMaterial.mType; } PX_FORCE_INLINE PxVec3 getAlbedo() const { return mObject->mMaterial.mAlbedo; } PX_FORCE_INLINE PxVec3 getEmissive() const { return mObject->mMaterial.mEmissive; } PX_FORCE_INLINE float getRoughness() const { return mObject->mMaterial.mRoughness; } PX_FORCE_INLINE float getRI() const { return mObject->mMaterial.mRI; } }; struct Ray { PxVec3 mPos; PxVec3 mDir; }; // PT: helper to avoid recomputing the same things for each ray class RayProvider { public: RayProvider(float screenWidth, float screenHeight, float fov, const PxVec3& camDir); PX_FORCE_INLINE PxVec3 computeWorldRayF(float xs, float ys) const; PxMat33 mInvView; const PxVec3 mCamDir; float mWidth; float mHeight; float mOneOverWidth; float mOneOverHeight; float mHTan; float mVTan; PX_NOCOPY(RayProvider) }; RayProvider::RayProvider(float screenWidth, float screenHeight, float fov, const PxVec3& camDir) : mCamDir (camDir), mWidth (screenWidth*0.5f), mHeight (screenHeight*0.5f), mOneOverWidth (2.0f/screenWidth), mOneOverHeight (2.0f/screenHeight) { const float HTan = tanf(0.25f * fabsf(PxDegToRad(fov * 2.0f))); mHTan = HTan; mVTan = HTan*(screenWidth/screenHeight); PxVec3 right, up; PxComputeBasisVectors(camDir, right, up); mInvView = PxMat33(-right, up, mCamDir); } PX_FORCE_INLINE PxVec3 RayProvider::computeWorldRayF(float xs, float ys) const { const float u = (xs - mWidth)*mOneOverWidth; const float v = -(ys - mHeight)*mOneOverHeight; const PxVec3 CamRay(mVTan*u, mHTan*v, 1.0f); return mInvView.transform(CamRay).getNormalized(); } class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose, const PxVec3& albedo, const PxVec3& emissive, MaterialType type=Lambert, float roughness=0.0f, float ri=0.0f); void createBVH(); void render() const; PxVec3 trace(const PxVec3& camPos, const PxVec3& dir, PxU32& rngState) const; PxVec3 trace2(const Ray& ray, PxU32& rngState, PxU32 depth, bool doMaterialE = true) const; bool raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomHit& hit) const; #if OPTIM_SHADOW_RAY_CODEPATH bool shadowRay(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const CustomObject* filtered) const; #endif bool scatter(const Ray& r, const CustomHit& hit, PxVec3& attenuation, Ray& scattered, PxVec3& outLightE, PxU32& state) const; PxU32 traceKernel(PxVec3* dest, const PxVec3& camPos, const RayProvider& rp, float fScreenWidth, float fScreenHeight, PxU32 seed, PxU32 offseti, PxU32 offsetj) const; PxArray<CustomObject> mObjects; PxArray<PxU32> mEmissiveObjects; // Indices of emissive objects PxBVH* mBVH; }; CustomScene::CustomScene() : mBVH(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mBVH); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose, const PxVec3& albedo, const PxVec3& emissive, MaterialType type, float roughness, float ri) { const PxU32 id = mObjects.size(); CustomObject obj; obj.mGeom.storeAny(geom); obj.mPose = pose; obj.mMaterial.mType = type; obj.mMaterial.mAlbedo = albedo; obj.mMaterial.mEmissive = emissive; obj.mMaterial.mRoughness = roughness; obj.mMaterial.mRI = ri; mObjects.pushBack(obj); if(!emissive.isZero()) mEmissiveObjects.pushBack(id); } void CustomScene::createBVH() { const PxU32 nbObjects = mObjects.size(); PxBounds3* bounds = new PxBounds3[nbObjects]; for(PxU32 i=0;i<nbObjects;i++) { const CustomObject& obj = mObjects[i]; PxGeometryQuery::computeGeomBounds(bounds[i], obj.mGeom.any(), obj.mPose); } PxBVHDesc bvhDesc; bvhDesc.bounds.count = nbObjects; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); mBVH = PxCreateBVH(bvhDesc); delete [] bounds; } #ifdef STATS static PxU32 gTotalNbRays = 0; #endif bool CustomScene::raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomHit& hit) const { #ifdef STATS gTotalNbRays++; #endif if(!mBVH) return false; struct LocalCB : PxBVH::RaycastCallback { LocalCB(const CustomScene& scene, const PxVec3& origin_, const PxVec3& dir, CustomHit& hit_) : mScene (scene), mHit (hit_), mOrigin (origin_), mDir (dir), mStatus (false) { } virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) { const CustomObject& obj = mScene.mObjects[boundsIndex]; if(PxGeometryQuery::raycast(mOrigin, mDir, obj.mGeom.any(), obj.mPose, distance, PxHitFlag::eDEFAULT, 1, &mLocalHit, sizeof(PxGeomRaycastHit), gQueryFlags)) { // We need to discard internal hits for refracted rays if(mLocalHit.distance==0.0f) return true; if(mLocalHit.distance<distance) { distance = mLocalHit.distance; static_cast<PxGeomRaycastHit&>(mHit) = mLocalHit; mHit.setObject(&obj); mStatus = true; } } return true; } const CustomScene& mScene; CustomHit& mHit; PxGeomRaycastHit mLocalHit; const PxVec3& mOrigin; const PxVec3& mDir; bool mStatus; LocalCB& operator=(const LocalCB&) { PX_ASSERT(0); return *this; } }; LocalCB CB(*this, origin, unitDir, hit); mBVH->raycast(origin, unitDir, maxDist, CB, gQueryFlags); return CB.mStatus; } #if OPTIM_SHADOW_RAY_CODEPATH bool CustomScene::shadowRay(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const CustomObject* filtered) const { #ifdef STATS gTotalNbRays++; #endif if(!mBVH) return false; struct LocalCB : PxBVH::RaycastCallback { LocalCB(const CustomScene& scene, const PxVec3& origin_, const PxVec3& dir, const CustomObject* filtered_) : mScene (scene), mFiltered (filtered_), mOrigin (origin_), mDir (dir), mStatus (false) { } virtual bool reportHit(PxU32 boundsIndex, PxReal& distance) { const CustomObject& obj = mScene.mObjects[boundsIndex]; if(&obj==mFiltered) return true; // PT: we don't need the hit position/normal for shadow rays, so we tell PhysX it can skip computing them. // We also use eMESH_ANY to tell the system not to look for the closest hit on triangle meshes. if(PxGeometryQuery::raycast(mOrigin, mDir, obj.mGeom.any(), obj.mPose, distance, PxHitFlag::eMESH_ANY, 1, &mLocalHit, sizeof(PxGeomRaycastHit), gQueryFlags)) { mStatus = true; return false; } return true; } const CustomScene& mScene; const CustomObject* mFiltered; PxGeomRaycastHit mLocalHit; const PxVec3& mOrigin; const PxVec3& mDir; bool mStatus; LocalCB& operator=(const LocalCB&) { PX_ASSERT(0); return *this; } }; LocalCB CB(*this, origin, unitDir, filtered); mBVH->raycast(origin, unitDir, maxDist, CB, gQueryFlags); return CB.mStatus; } #endif struct TracerThread { TracerThread() : mScene(NULL), mRndState(42), mActive(true) { } SnippetUtils::Sync* mWorkReadySyncHandle; SnippetUtils::Thread* mThreadHandle; SnippetUtils::Sync* mWorkDoneSyncHandle; const CustomScene* mScene; const RayProvider* mRayProvider; PxVec3* mDest; PxVec3 mCamPos; float mScreenWidth; float mScreenHeight; PxU32 mOffsetX; PxU32 mOffsetY; PxU32 mRndState; bool mActive; void Setup(const CustomScene* scene, const RayProvider* rp, PxVec3* dest, const PxVec3& camPos, float width, float height, PxU32 offsetX, PxU32 offsetY) { mScene = scene; mRayProvider = rp; mDest = dest; mCamPos = camPos; mScreenWidth = width; mScreenHeight = height; mOffsetX = offsetX; mOffsetY = offsetY; } void Run() { if(mActive) mRndState = mScene->traceKernel(mDest, mCamPos, *mRayProvider, mScreenWidth, mScreenHeight, mRndState, mOffsetX, mOffsetY); } }; const PxU32 gNumThreads = 16; TracerThread gThreads[gNumThreads]; static PX_FORCE_INLINE PxU32 wang_hash(PxU32& seed) { seed = PxU32(seed ^ PxU32(61)) ^ PxU32(seed >> PxU32(16)); seed *= PxU32(9); seed = seed ^ (seed >> 4); seed *= PxU32(0x27d4eb2d); seed = seed ^ (seed >> 15); return seed; } /*static PX_FORCE_INLINE PxU32 XorShift32(PxU32& state) { PxU32 x = state; x ^= x << 13; x ^= x >> 17; x ^= x << 15; state = x; return x; }*/ static const float gInvValue = float(1.0 / 4294967296.0); //static const float gInvValue2 = float(1.0 / 16777216.0); static PX_FORCE_INLINE float RandomFloat01(PxU32& state) { // return float(wang_hash(state)) / 4294967296.0; return float(wang_hash(state)) * gInvValue; // return (XorShift32(state) & 0xFFFFFF) / 16777216.0f; // return (XorShift32(state) & 0xFFFFFF) * gInvValue2; } /*static PxVec3 RandomInUnitDisk(PxU32& state) { PxVec3 p; do { p = 2.0f * PxVec3(RandomFloat01(state), RandomFloat01(state), 0.0f) - PxVec3(1.0f, 1.0f, 0.0f); } while (p.dot(p) >= 1.0f); return p; }*/ static PxVec3 RandomInUnitSphere(PxU32& state) { PxVec3 p; do { p = 2.0f * PxVec3(RandomFloat01(state), RandomFloat01(state), RandomFloat01(state)) - PxVec3(1.0f); } while (p.dot(p) >= 1.0f); return p; } static PX_FORCE_INLINE PxVec3 RandomUnitVector(PxU32& state) { const float z = RandomFloat01(state) * 2.0f - 1.0f; const float a = RandomFloat01(state) * PxTwoPi; const float r = sqrtf(1.0f - z * z); const float x = r * cosf(a); const float y = r * sinf(a); return PxVec3(x, y, z); } static PX_FORCE_INLINE PxVec3 sky(const PxVec3& dir) { const float t = 0.5f * (dir.y + 1.0f); const PxVec3 white(1.0f); const PxVec3 blue(0.5f, 0.7f, 1.0f); return white*(1.0f-t) + blue*t; } static PX_FORCE_INLINE PxVec3 mul(const PxVec3& v0, const PxVec3& v1) { return PxVec3(v0.x*v1.x, v0.y*v1.y, v0.z*v1.z); } #ifdef RENDER_SNIPPET static PX_FORCE_INLINE PxVec3 div(const PxVec3& v0, const PxVec3& v1) { const float x = v1.x!=0.0f ? v0.x/v1.x : 0.0f; const float y = v1.y!=0.0f ? v0.y/v1.y : 0.0f; const float z = v1.z!=0.0f ? v0.z/v1.z : 0.0f; return PxVec3(x, y, z); // return PxVec3(v0.x/v1.x, v0.y/v1.y, v0.z/v1.z); } /*static PX_FORCE_INLINE float saturate(float a) { return (a < 0.0f) ? 0.0f : (a > 1.0f) ? 1.0f : a; }*/ static PX_FORCE_INLINE PxVec3 ACESTonemap(const PxVec3& inColor) { const float a = 2.51f; const float b = 0.03f; const float c = 2.43f; const float d = 0.59f; const float e = 0.14f; const PxVec3 col = div((mul(inColor, (PxVec3(b) + inColor * a))) , (mul(inColor, (inColor * c + PxVec3(d)) + PxVec3(e)))); // return PxVec3(saturate(col.x), saturate(col.y), saturate(col.z)); return col; } #endif /*static PX_FORCE_INLINE PxVec3 LessThan(const PxVec3& f, float value) { return PxVec3( (f.x < value) ? 1.0f : 0.0f, (f.y < value) ? 1.0f : 0.0f, (f.z < value) ? 1.0f : 0.0f); }*/ /*PX_FORCE_INLINE float sqLength(const PxVec3& v) { return v.dot(v); }*/ #ifdef RENDER_SNIPPET static PX_FORCE_INLINE PxVec3 max3(const PxVec3& v, float e) { return PxVec3(PxMax(v.x, e), PxMax(v.y, e), PxMax(v.z, e)); } static PX_FORCE_INLINE PxVec3 pow(const PxVec3& v, float e) { return PxVec3(powf(v.x, e), powf(v.y, e), powf(v.z, e)); } #endif /*static PX_FORCE_INLINE PxVec3 pow(const PxVec3& v, const PxVec3& e) { return PxVec3(powf(v.x, e.x), powf(v.y, e.y), powf(v.z, e.z)); } static PX_FORCE_INLINE PxVec3 mix(const PxVec3& x, const PxVec3& y, const PxVec3& a) { const PxVec3 b = PxVec3(1.0f) - a; return mul(x,b) + mul(y,a); }*/ /*static PX_FORCE_INLINE PxVec3 mix(const PxVec3& x, const PxVec3& y, float a) { const float b = 1.0f - a; return (x*b) + (y*a); }*/ static PX_FORCE_INLINE PxVec3 reflect(const PxVec3& I, const PxVec3& N) { return I - 2.0f * N.dot(I) * N; } /*static PX_FORCE_INLINE PxVec3 LinearToSRGB(const PxVec3& rgb) { return mix( pow(rgb, PxVec3(1.0f / 2.4f)) * 1.055f - PxVec3(0.055f), rgb * 12.92f, LessThan(rgb, 0.0031308f) ); }*/ #ifdef RENDER_SNIPPET static PX_FORCE_INLINE PxVec3 LinearToSRGB2(const PxVec3 rgb) { // rgb = max(rgb, float3(0, 0, 0)); return max3(1.055f * pow(rgb, 0.416666667f) - PxVec3(0.055f), 0.0f); } #endif /*static PX_FORCE_INLINE PxVec3 SRGBToLinear(const PxVec3& rgb2) { // rgb = clamp(rgb, 0.0f, 1.0f); PxVec3 rgb = rgb2; if(rgb.x>255.0f) rgb.x = 255.0f; if(rgb.y>255.0f) rgb.y = 255.0f; if(rgb.z>255.0f) rgb.z = 255.0f; return mix( pow(((rgb + PxVec3(0.055f)) / 1.055f), PxVec3(2.4f)), rgb / 12.92f, LessThan(rgb, 0.04045f) ); }*/ static PxVec3* gAccumPixels = NULL; static PxVec3* gCurrentPixels = NULL; #ifdef RENDER_SNIPPET static GLubyte* gCurrentTexture = NULL; static GLuint gTexID = 0; #endif static const PxU32 RAYTRACING_RENDER_WIDTH = 512; static const PxU32 RAYTRACING_RENDER_HEIGHT = 512; static bool gUseMultipleThreads = true; static bool gShowAllThreadRenders = false; static bool gToneMapping = true; static bool gLinearToSRGB = false; static float gSkyCoeff = 0.4f; static float gExposure = 0.5f; static const float gRayPosNormalNudge = 0.01f; static const PxU32 gMaxNbBounces = 8; static const PxU32 gNbSamplesPerPixel = 1; static const float gOneOverNbSamples = 1.0f / float(gNbSamplesPerPixel); #define DO_LIGHT_SAMPLING 1 #define ANTIALIASING static void resetRender() { gFrameIndex = 0; if(gAccumPixels) PxMemZero(gAccumPixels, RAYTRACING_RENDER_WIDTH*RAYTRACING_RENDER_HEIGHT*sizeof(PxVec3)); } static PX_FORCE_INLINE bool refract(PxVec3 v, PxVec3 n, float nint, PxVec3& outRefracted) { const float dt = v.dot(n); const float discr = 1.0f - nint*nint*(1.0f-dt*dt); if(discr > 0.0f) { outRefracted = nint * (v - n*dt) - n*sqrtf(discr); return true; } return false; } static PX_FORCE_INLINE float schlick(float cosine, float ri) { float r0 = (1.0f-ri) / (1.0f+ri); r0 = r0*r0; return r0 + (1.0f-r0)*powf(1.0f-cosine, 5.0f); } bool CustomScene::scatter(const Ray& r, const CustomHit& hit, PxVec3& attenuation, Ray& scattered, PxVec3& outLightE, PxU32& state) const { outLightE = PxVec3(0.0f); const MaterialType type = hit.getType(); if(type == Lambert) { // random point on unit sphere that is tangent to the hit point attenuation = hit.getAlbedo(); scattered.mPos = hit.position + hit.normal * gRayPosNormalNudge; scattered.mDir = (hit.normal + RandomUnitVector(state)).getNormalized(); #if DO_LIGHT_SAMPLING const PxU32 nbLights = mEmissiveObjects.size(); // sample lights for(PxU32 j=0; j<nbLights; j++) { const int i = mEmissiveObjects[j]; const CustomObject& smat = mObjects[i]; if(hit.getObject() == &smat) continue; // skip self PX_ASSERT(smat.mGeom.getType()==PxGeometryType::eSPHERE); const PxSphereGeometry& sphereGeom = smat.mGeom.sphere(); const PxVec3& sphereCenter = smat.mPose.p; // create a random direction towards sphere // coord system for sampling: sw, su, sv PxVec3 delta = sphereCenter - hit.position; const float maxDist2 = delta.magnitudeSquared(); const float maxDist = PxSqrt(maxDist2); PxVec3 sw = delta/maxDist; PxVec3 su; if(fabsf(sw.x)>0.01f) su = PxVec3(0,1,0).cross(sw); else su = PxVec3(1,0,0).cross(sw); su.normalize(); PxVec3 sv = sw.cross(su); // sample sphere by solid angle const float tmp = 1.0f - sphereGeom.radius*sphereGeom.radius / maxDist2; const float cosAMax = tmp>0.0f ? sqrtf(tmp) : 0.0f; const float eps1 = RandomFloat01(state), eps2 = RandomFloat01(state); const float cosA = 1.0f - eps1 + eps1 * cosAMax; const float sinA = sqrtf(1.0f - cosA*cosA); const float phi = PxTwoPi * eps2; const PxVec3 l = su * (cosf(phi) * sinA) + sv * (sinf(phi) * sinA) + sw * cosA; //l = normalize(l); // NOTE(fg): This is already normalized, by construction. // shoot shadow ray #if OPTIM_SHADOW_RAY_CODEPATH if(!shadowRay(scattered.mPos, l, maxDist, &smat)) #else CustomHit lightHit; if(raycast(scattered.mPos, l, 5000.0f, lightHit) && lightHit.getObject()==&smat) #endif { const float omega = PxTwoPi * (1.0f - cosAMax); const PxVec3 nl = hit.normal.dot(r.mDir) < 0.0f ? hit.normal : -hit.normal; outLightE += (mul(hit.getAlbedo(), smat.mMaterial.mEmissive)) * (PxMax(0.0f, l.dot(nl)) * omega / PxPi); } } #endif return true; } else if(type == Metal) { const PxVec3 refl = reflect(r.mDir, hit.normal); // reflected ray, and random inside of sphere based on roughness const float roughness = hit.getRoughness(); scattered.mPos = hit.position + hit.normal * gRayPosNormalNudge; scattered.mDir = (refl + roughness*RandomInUnitSphere(state)).getNormalized(); attenuation = hit.getAlbedo(); return scattered.mDir.dot(hit.normal) > 0.0f; } else if(type == Dielectric) { attenuation = PxVec3(1.0f); const PxVec3& rdir = r.mDir; const float matri = hit.getRI(); PxVec3 outwardN; float nint; float cosine; if(rdir.dot(hit.normal) > 0) { outwardN = -hit.normal; nint = matri; cosine = matri * rdir.dot(hit.normal); } else { outwardN = hit.normal; nint = 1.0f / matri; cosine = -rdir.dot(hit.normal); } float reflProb; PxVec3 refr(1.0f); if(refract(rdir, outwardN, nint, refr)) reflProb = schlick(cosine, matri); else reflProb = 1.0f; if(RandomFloat01(state) < reflProb) { const PxVec3 refl = reflect(rdir, hit.normal); scattered.mPos = hit.position + hit.normal * gRayPosNormalNudge; scattered.mDir = refl.getNormalized(); } else { scattered.mPos = hit.position - hit.normal * gRayPosNormalNudge; scattered.mDir = refr.getNormalized(); } } else { attenuation = PxVec3(1.0f, 0.0f, 1.0f); return false; } return true; } PxVec3 CustomScene::trace2(const Ray& ray, PxU32& rngState, PxU32 depth, bool doMaterialE) const { CustomHit hit; if(raycast(ray.mPos, ray.mDir, 5000.0f, hit)) { Ray scattered; PxVec3 attenuation; PxVec3 lightE; PxVec3 matE = hit.getEmissive(); if(depth < gMaxNbBounces && scatter(ray, hit, attenuation, scattered, lightE, rngState)) { #if DO_LIGHT_SAMPLING if(!doMaterialE) matE = PxVec3(0.0f); // don't add material emission if told so // for Lambert materials, we just did explicit light (emissive) sampling and already // for their contribution, so if next ray bounce hits the light again, don't add // emission doMaterialE = hit.getType() != Lambert; #endif return matE + lightE + mul(attenuation, trace2(scattered, rngState, depth+1, doMaterialE)); } else return matE; } else return sky(ray.mDir)*gSkyCoeff; } PxU32 CustomScene::traceKernel(PxVec3* dest, const PxVec3& camPos, const RayProvider& rp, float fScreenWidth, float fScreenHeight, PxU32 seed, PxU32 offseti, PxU32 offsetj) const { #if OPTIM_SKIP_INTERNAL_SIMD_GUARD PX_SIMD_GUARD #endif PxU32 rngState = seed; for(PxU32 jj=0;jj<RAYTRACING_RENDER_HEIGHT;jj+=4) { const PxU32 j = jj + offsetj; #ifndef ANTIALIASING const PxU32 yi = PxU32(fScreenHeight*float(j)); #endif for(PxU32 ii=0;ii<RAYTRACING_RENDER_WIDTH;ii+=4) { const PxU32 i = ii + offseti; PxVec3 color(0.0f); for(PxU32 k=0;k<gNbSamplesPerPixel;k++) { #ifdef ANTIALIASING const float radius = 1.0f; const float jitterX = radius*(RandomFloat01(rngState) - 0.5f); const float jitterY = radius*(RandomFloat01(rngState) - 0.5f); const float xf = fScreenWidth*(float(i)+jitterX); const float yf = fScreenHeight*(float(j)+jitterY); const PxVec3 dir = rp.computeWorldRayF(xf, yf); #else const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = rp.computeWorldRayF(float(xi), float(yi)); #endif Ray r; r.mPos = camPos; r.mDir = dir; color += trace2(r, rngState, 0); } *dest++ = color * gOneOverNbSamples; } dest += (RAYTRACING_RENDER_HEIGHT/4)*3; } return rngState; } void CustomScene::render() const { #if OPTIM_SKIP_INTERNAL_SIMD_GUARD PX_SIMD_GUARD #endif #ifdef RENDER_SNIPPET if(0) { const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const CustomObject& obj = mObjects[i]; Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } } const PxU32 screenWidth = Snippets::getScreenWidth(); const PxU32 screenHeight = Snippets::getScreenHeight(); Snippets::Camera* sCamera = Snippets::getCamera(); const PxVec3 camPos = sCamera->getEye(); const PxVec3 camDir = sCamera->getDir(); static PxVec3 cachedPos(0.0f); static PxVec3 cachedDir(0.0f); if(cachedPos!=camPos || cachedDir!=camDir) { cachedPos=camPos; cachedDir=camDir; resetRender(); } const PxU32 textureWidth = RAYTRACING_RENDER_WIDTH; const PxU32 textureHeight = RAYTRACING_RENDER_HEIGHT; if(!gAccumPixels) { gAccumPixels = new PxVec3[textureWidth*textureHeight]; PxMemZero(gAccumPixels, textureWidth*textureHeight*sizeof(PxVec3)); } const float fScreenWidth = float(screenWidth)/float(RAYTRACING_RENDER_WIDTH); const float fScreenHeight = float(screenHeight)/float(RAYTRACING_RENDER_HEIGHT); static PxU32 rngState = 42; if(!gCurrentPixels) { gCurrentPixels = new PxVec3[textureWidth*textureHeight]; PxMemZero(gCurrentPixels, textureWidth*textureHeight*sizeof(PxVec3)); } #ifdef PRINT_TIMINGS const DWORD tgt = timeGetTime(); const DWORD64 time0 = __rdtsc(); #endif const RayProvider rp(float(screenWidth), float(screenHeight), 60.0f, camDir); PxVec3* buffer = gCurrentPixels; if(gUseMultipleThreads) { PxU32 index = 0; for(PxU32 j=0;j<4;j++) { for(PxU32 i=0;i<4;i++) { PxU32 offset = (RAYTRACING_RENDER_WIDTH/4)*i; offset += (RAYTRACING_RENDER_HEIGHT/4)*j*RAYTRACING_RENDER_WIDTH; gThreads[index++].Setup(this, &rp, buffer + offset, camPos, fScreenWidth, fScreenHeight, i, j); } } { for (PxU32 i=0; i<gNumThreads; i++) SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); for (PxU32 i=0; i<gNumThreads; i++) { SnippetUtils::syncWait(gThreads[i].mWorkDoneSyncHandle); SnippetUtils::syncReset(gThreads[i].mWorkDoneSyncHandle); } } } else { for(PxU32 j=0;j<RAYTRACING_RENDER_HEIGHT;j++) { #ifndef ANTIALIASING const PxU32 yi = PxU32(fScreenHeight*float(j)); #endif for(PxU32 i=0;i<RAYTRACING_RENDER_WIDTH;i++) { PxVec3 color(0.0f); for(PxU32 k=0;k<gNbSamplesPerPixel;k++) { #ifdef ANTIALIASING const float radius = 1.0f; const float jitterX = radius*(RandomFloat01(rngState) - 0.5f); const float jitterY = radius*(RandomFloat01(rngState) - 0.5f); const float xf = fScreenWidth*(float(i)+jitterX); const float yf = fScreenHeight*(float(j)+jitterY); const PxVec3 dir = rp.computeWorldRayF(xf, yf); #else const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = rp.computeWorldRayF(float(xi), float(yi)); #endif Ray r; r.mPos = camPos; r.mDir = dir; color += trace2(r, rngState, 0); } *buffer++ = color * gOneOverNbSamples; } } } #ifdef PRINT_TIMINGS const DWORD64 time1 = __rdtsc(); #endif gFrameIndex++; const float coeff = 1.0f/float(gFrameIndex); const float coeff2 = 1.0f-coeff; if(gUseMultipleThreads && !gShowAllThreadRenders) { for(PxU32 j=0;j<4;j++) { for(PxU32 i=0;i<4;i++) { PxU32 offset = (RAYTRACING_RENDER_WIDTH/4)*i; offset += (RAYTRACING_RENDER_HEIGHT/4)*j*RAYTRACING_RENDER_WIDTH; const PxVec3* src = gCurrentPixels + offset; PxVec3* dst = gAccumPixels + i + j*RAYTRACING_RENDER_WIDTH; for(PxU32 jj=0;jj<RAYTRACING_RENDER_HEIGHT/4;jj++) { for(PxU32 ii=0;ii<RAYTRACING_RENDER_WIDTH/4;ii++) { dst[ii*4] = dst[ii*4]*coeff2 + src[ii]*coeff; } src += RAYTRACING_RENDER_WIDTH; dst += RAYTRACING_RENDER_WIDTH*4; } } } } else { for(PxU32 i=0;i<textureWidth*textureHeight;i++) { gAccumPixels[i] = gAccumPixels[i]*coeff2 + gCurrentPixels[i]*coeff; } } if(!gCurrentTexture) gCurrentTexture = new GLubyte[textureWidth*textureHeight*4]; if(1) { for(PxU32 i=0;i<textureWidth*textureHeight;i++) { PxVec3 col = gAccumPixels[i]; // apply exposure (how long the shutter is open) col *= gExposure; if(gToneMapping) { // convert unbounded HDR color range to SDR color range col = ACESTonemap(col); } if(gLinearToSRGB) col = LinearToSRGB2(col); col *= 255.99f; if(col.x>255.0f) col.x = 255.0f; if(col.y>255.0f) col.y = 255.0f; if(col.z>255.0f) col.z = 255.0f; gCurrentTexture[i*4+0] = GLubyte(col.x); gCurrentTexture[i*4+1] = GLubyte(col.y); gCurrentTexture[i*4+2] = GLubyte(col.z); gCurrentTexture[i*4+3] = 255; } } if(1) { if(!gTexID) gTexID = Snippets::CreateTexture(textureWidth, textureHeight, gCurrentTexture, false); else Snippets::UpdateTexture(gTexID, textureWidth, textureHeight, gCurrentTexture, false); // Snippets::DisplayTexture(gTexID, RAYTRACING_RENDER_WIDTH, 10); Snippets::DisplayTexture(gTexID, 0, 0); } #ifdef PRINT_TIMINGS const DWORD64 time2 = __rdtsc(); const DWORD tgt2 = timeGetTime(); if(1) { printf("Render: %d\n", int(time1-time0)/1024); printf("End : %d\n", int(time2-time1)/1024); printf("Total : %d\n", int(time2-time0)/1024); printf("Total : %d ms\n\n", tgt2 - tgt); } #endif #ifdef STATS printf("Total #rays: %d\n", gTotalNbRays); gTotalNbRays = 0; #endif #endif } } static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static CustomScene* gScene = NULL; static const float gMeshScaleValue = 1.5f; enum SceneIndex { SCENE_FIRST = 0, SCENE_ARAS = 0, SCENE_BUNNY = 1, SCENE_SPHERES = 2, SCENE_COUNT }; static PxU32 gSceneIndex = SCENE_BUNNY; static void initScene() { const PxVec3 red(1.0f, 0.25f, 0.2f); const PxVec3 green(0.5f, 1.0f, 0.4f); const PxVec3 blue(0.1f, 0.5f, 1.0f); const PxVec3 grey(0.5f); const PxVec3 noEmissive(0.0f); const PxVec3 smallEmissive(0.0f); // const PxVec3 bigEmissive(0.7f); const PxVec3 bigEmissive(70.0f); const PxVec3 color(1.0f, 0.5f, 0.25f); #if OPTIM_BAKE_MESH_SCALE // PT: queries against scaled meshes are slightly slower, so we pre-scale the vertices const PxMeshScale meshScale(1.0f); #else const PxMeshScale meshScale(gMeshScaleValue); #endif gScene = new CustomScene; gSkyCoeff = 0.4f; gExposure = 0.5f; if(gSceneIndex==SCENE_ARAS) { gScene->addGeom(PxSphereGeometry(100.0f), PxTransform(PxVec3(0,-100.5,-1)), PxVec3(0.8f, 0.8f, 0.8f), noEmissive); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(2,0,-1)), PxVec3(0.8f, 0.4f, 0.4f), noEmissive); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(0,0,-1)), PxVec3(0.4f, 0.8f, 0.4f), noEmissive); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(-2,0,-1)), PxVec3(0.4f, 0.4f, 0.8f), noEmissive, Metal); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(2,0,1)), PxVec3(0.4f, 0.8f, 0.4f), noEmissive, Metal); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(0,0,1)), PxVec3(0.4f, 0.8f, 0.4f), noEmissive, Metal, 0.2f); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(-2,0,1)), PxVec3(0.4f, 0.8f, 0.4f), noEmissive, Metal, 0.6f); gScene->addGeom(PxSphereGeometry(0.5f), PxTransform(PxVec3(0.5f,1,0.5f)), PxVec3(0.4f, 0.4f, 0.4f), noEmissive, Dielectric, 0.0f, 1.5f); gScene->addGeom(PxSphereGeometry(0.3f), PxTransform(PxVec3(-1.5f,1.5f,0.f)), PxVec3(0.8f, 0.6f, 0.2f), PxVec3(30,25,15)); } else if(gSceneIndex==SCENE_BUNNY) { gScene->addGeom(PxSphereGeometry(1.0f), PxTransform(PxVec3(0.0f, 8.0f, 0.0f)), grey, PxVec3(70,65,55)); // gScene->addGeom(PxSphereGeometry(1.0f), PxTransform(PxVec3(0.0f, 8.0f, 0.0f)), grey, PxVec3(7.0f,6.5f,5.5f)); // gScene->addGeom(PxSphereGeometry(1.0f), PxTransform(PxVec3(4.0f, 4.5f, 4.0f)), grey, bigEmissive); // gScene->addGeom(PxSphereGeometry(0.1f), PxTransform(PxVec3(4.0f, 4.5f, 4.0f)), grey, bigEmissive); gScene->addGeom(PxBoxGeometry(PxVec3(15.0f, 0.01f, 15.0f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), grey, smallEmissive); gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 2.0f, -4.0f)), color, smallEmissive); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 1.55f, -4.0f)), grey, smallEmissive, Metal, 0.0f); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 1.55f, 0.0f)), grey, smallEmissive, Metal, 0.1f); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 1.55f, 4.0f)), grey, smallEmissive, Metal, 0.2f); // gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 1.05f, 0.0f)), blue, smallEmissive, Dielectric, 0.0f, 1.2f); gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 1.05f, 0.0f)), blue, smallEmissive); gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 1.05f, 4.0f)), green, smallEmissive); gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh, meshScale), PxTransform(PxVec3(0.0f, 0.70f*gMeshScaleValue, 0.0f)), red, smallEmissive); // gScene->addGeom(PxBoxGeometry(PxVec3(1.0f)), PxTransform(PxVec3(0.0f, 1.0f, 0.0f)), color, smallEmissive); } else if(gSceneIndex==SCENE_SPHERES) { gScene->addGeom(PxBoxGeometry(PxVec3(150.0f, 0.0001f, 150.0f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), grey, smallEmissive); gScene->addGeom(PxSphereGeometry(10.0f), PxTransform(PxVec3(0.0f, 40.0f, 0.0f)), grey, PxVec3(100.0f)); const PxU32 nb = 16; PxU32 state = 42; // const PxVec3 base(1.0f, 0.5f, 0.25f); const PxVec3 base(1.0f, 0.5f, 0.2f); for(PxU32 i=0;i<nb;i++) { const float CoeffX = float(i) - float(nb/2); for(PxU32 j=0;j<nb;j++) { const float CoeffZ = float(j) - float(nb/2); const float x = CoeffX * 4.0f; const float z = CoeffZ * 4.0f; PxVec3 rndColor(RandomFloat01(state), RandomFloat01(state), RandomFloat01(state)); rndColor += base; rndColor *= 0.5f; // gScene->addGeom(PxSphereGeometry(1.0f), PxTransform(PxVec3(x, 1.0f, z)), rndColor, smallEmissive, Metal, 0.25f); gScene->addGeom(PxSphereGeometry(1.0f), PxTransform(PxVec3(x, 1.0f, z)), rndColor, smallEmissive, Metal, 0.0f); // gScene->addGeom(PxBoxGeometry(PxVec3(1.0f)), PxTransform(PxVec3(x, 1.0f, z)), rndColor, smallEmissive, Metal, 0.0f); // gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh, meshScale), PxTransform(PxVec3(x, 0.75f*gMeshScaleValue, z)), rndColor, smallEmissive); } } } gScene->createBVH(); } static void releaseScene() { PX_RELEASE(gScene); } void renderScene() { if(gScene) gScene->render(); } static void threadExecute(void* data) { TracerThread* tracerThread = static_cast<TracerThread*>(data); for(;;) { SnippetUtils::syncWait(tracerThread->mWorkReadySyncHandle); SnippetUtils::syncReset(tracerThread->mWorkReadySyncHandle); if (SnippetUtils::threadQuitIsSignalled(tracerThread->mThreadHandle)) break; tracerThread->Run(); SnippetUtils::syncSet(tracerThread->mWorkDoneSyncHandle); } SnippetUtils::threadQuit(tracerThread->mThreadHandle); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; // We don't need the extra data structures for just doing raycasts vs the mesh params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); #if OPTIM_BAKE_MESH_SCALE PxVec3* verts = const_cast<PxVec3*>(SnippetUtils::Bunny_getVerts()); for(PxU32 i=0;i<meshDesc.points.count;i++) verts[i] *= gMeshScaleValue; #endif gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } initScene(); #ifdef RENDER_SNIPPET Snippets::enableVSync(false); #endif for (PxU32 i=0; i<gNumThreads; i++) { gThreads[i].mWorkReadySyncHandle = SnippetUtils::syncCreate(); gThreads[i].mWorkDoneSyncHandle = SnippetUtils::syncCreate(); gThreads[i].mThreadHandle = SnippetUtils::threadCreate(threadExecute, &gThreads[i]); } } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i=0; i<gNumThreads; i++) { SnippetUtils::threadSignalQuit(gThreads[i].mThreadHandle); SnippetUtils::syncSet(gThreads[i].mWorkReadySyncHandle); } for (PxU32 i=0; i<gNumThreads; i++) { SnippetUtils::threadWaitForQuit(gThreads[i].mThreadHandle); SnippetUtils::threadRelease(gThreads[i].mThreadHandle); SnippetUtils::syncRelease(gThreads[i].mWorkReadySyncHandle); } for (PxU32 i=0; i<gNumThreads; i++) SnippetUtils::syncRelease(gThreads[i].mWorkDoneSyncHandle); releaseScene(); #ifdef RENDER_SNIPPET Snippets::ReleaseTexture(gTexID); #endif PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); #ifdef RENDER_SNIPPET if(gCurrentTexture) { delete [] gCurrentTexture; gCurrentTexture = NULL; } #endif if(gCurrentPixels) { delete [] gCurrentPixels; gCurrentPixels = NULL; } if(gAccumPixels) { delete [] gAccumPixels; gAccumPixels = NULL; } printf("SnippetPathTracing done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key == 1) { gSceneIndex++; if(gSceneIndex==SCENE_COUNT) gSceneIndex = SCENE_FIRST; releaseScene(); initScene(); resetRender(); } else if(key == 2) { if(gSceneIndex) gSceneIndex--; else gSceneIndex = SCENE_COUNT-1; releaseScene(); initScene(); resetRender(); } else if(key == 3) { gSkyCoeff += 0.1f; printf("Sky coeff: %f\n", double(gSkyCoeff)); resetRender(); } else if(key == 4) { gSkyCoeff -= 0.1f; if(gSkyCoeff<0.0f) gSkyCoeff=0.0f; printf("Sky coeff: %f\n", double(gSkyCoeff)); resetRender(); } else if(key == 5) { gExposure += 0.1f; printf("Exposure: %f\n", double(gExposure)); resetRender(); } else if(key == 6) { gExposure -= 0.1f; if(gExposure<0.0f) gExposure=0.0f; printf("Exposure: %f\n", double(gExposure)); resetRender(); } else if(key == 'r' || key == 'R') { resetRender(); } else if(key == 'g' || key == 'G') { gShowAllThreadRenders = !gShowAllThreadRenders; printf("Debug multithread: %d\n", gShowAllThreadRenders); } else if(key == 'm' || key == 'M') { gUseMultipleThreads = !gUseMultipleThreads; printf("Multithreading: %d\n", gUseMultipleThreads); } else if(key == 't' || key == 'T') { gToneMapping = !gToneMapping; printf("Tone mapping: %d\n", gToneMapping); } else if(key == 'l' || key == 'L') { gLinearToSRGB = !gLinearToSRGB; printf("Linear-to-SRGB: %d\n", gLinearToSRGB); } } int snippetMain(int, const char*const*) { printf("PxBVH PathTracing snippet. Use these keys:\n"); printf(" F1/F2 - change scene\n"); printf(" F3/F4 - change sky color intensity\n"); printf(" F5/F6 - change exposure value\n"); printf(" m - multithreading on/off\n"); printf(" t - tone mapping on/off\n"); printf(" l - linear to SRGB/off\n"); printf(" r - reset scene\n"); printf(" g - debug multithreading on/off\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
41,336
C++
27.906993
178
0.686786
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpathtracing/SnippetPathTracingRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { // sCamera = new Snippets::Camera(PxVec3(5.330070f, 5.598980f, -7.194576f), PxVec3(-0.436862f, -0.552957f, 0.709500f)); // sCamera = new Snippets::Camera(PxVec3(-2.840040f, 2.347654f, -6.658016f), PxVec3(0.361939f, -0.232584f, 0.902721f)); sCamera = new Snippets::Camera(PxVec3(-6.085999f, 4.210001f, 4.160744f), PxVec3(0.694034f, -0.479131f, -0.537355f)); Snippets::setupDefault("PhysX Snippet PathTracing", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,139
C++
35.511627
119
0.745779
NVIDIA-Omniverse/PhysX/physx/snippets/snippetjointdrive/SnippetJointDriveRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } { const PxRenderBuffer& renderBuffer = scene->getRenderBuffer(); const PxDebugLine* lines = renderBuffer.getLines(); const PxU32 nbLines = renderBuffer.getNbLines(); for(PxU32 i=0;i<nbLines;i++) { const float b = float((lines[i].color0 & 0xff))/255.0f; const float g = float(((lines[i].color0>>8) & 0xff))/255.0f; const float r = float(((lines[i].color0>>16) & 0xff))/255.0f; Snippets::DrawLine(lines[i].pos0, lines[i].pos1, PxVec3(r, g, b)); } } renderText(); Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(1.847750f, 2.8f, -15.241850f), PxVec3(-0.219386f, -0.289038f, -0.931841f)); Snippets::setupDefault("PhysX Snippet Joint Drive", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); cleanup(); } #endif
3,635
C++
32.054545
136
0.742228
NVIDIA-Omniverse/PhysX/physx/snippets/snippetjointdrive/SnippetJointDrive.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. // **************************************************************************** // This snippet illustrates simple use of joint drives in physx // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #if PX_SUPPORT_GPU_PHYSX static PxCudaContextManager* gCudaContextManager = NULL; #endif static bool gPause = false; static bool gOneFrame = false; static bool gChangeObjectAType = false; static bool gChangeObjectBRotation = false; static bool gChangeJointFrameARotation = false; static bool gChangeJointFrameBRotation = false; #if PX_SUPPORT_GPU_PHYSX static bool gUseGPU = false; #endif static PxU32 gSceneIndex = 0; static const PxU32 gMaxSceneIndex = 4; static void setupActor(PxRigidActor* actor) { actor->setActorFlag(PxActorFlag::eVISUALIZATION, true); gScene->addActor(*actor); } static void createScene() { PX_RELEASE(gScene); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); // Disable gravity so that the motion is only produced by the drive sceneDesc.gravity = PxVec3(0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; #if PX_SUPPORT_GPU_PHYSX if(gUseGPU) { sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; } #endif gScene = gPhysics->createScene(sceneDesc); // Visualize joint local frames gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eJOINT_LOCAL_FRAMES, 1.0f); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); if(gSceneIndex<gMaxSceneIndex) { const PxQuat rotZ = PxGetRotZQuat(-PxPi/4.0f); const PxBoxGeometry boxGeom(0.5f, 0.5f, 0.5f); PxTransform tr(PxVec3(0.0f, 2.0f, -20.0f)); PxRigidActor* actor0; if(gChangeObjectAType) { PxRigidDynamic* actor = PxCreateDynamic(*gPhysics, tr, boxGeom, *gMaterial, 1.0f); actor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); actor0 = actor; } else { actor0 = PxCreateStatic(*gPhysics, tr, boxGeom, *gMaterial); } setupActor(actor0); tr.p.x += boxGeom.halfExtents.x * 2.0f; if(gChangeObjectBRotation) tr.q = rotZ; PxRigidDynamic* actor1 = PxCreateDynamic(*gPhysics, tr, boxGeom, *gMaterial, 1.0f); setupActor(actor1); PxTransform jointFrame0(PxIdentity); PxTransform jointFrame1(PxIdentity); // We're going to setup a linear drive along "X" = actor0's joint frame's X axis. // That axis will be either aligned with the actors' X axis or tilted 45 degrees. if(gChangeJointFrameARotation) jointFrame0.q = rotZ; else jointFrame0.q = PxQuat(PxIdentity); if(gChangeJointFrameBRotation) jointFrame1.q = rotZ; else jointFrame1.q = PxQuat(PxIdentity); PxD6Joint* j = PxD6JointCreate(*gPhysics, actor0, jointFrame0, actor1, jointFrame1); j->setConstraintFlag(PxConstraintFlag::eVISUALIZATION, true); // Locked axes would move the joint frames & snap them together. In this test we explicitly want them disjoint, // to check in which direction the drives operates. So we set all DOFs free to make sure none of that interferes // with the drive. j->setMotion(PxD6Axis::eX, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eY, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eZ, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); j->setMotion(PxD6Axis::eTWIST, PxD6Motion::eFREE); if(gSceneIndex==0) { // Linear drive along "X" = actor0's joint frame's X axis j->setDrive(PxD6Drive::eX, PxD6JointDrive(0, 1000, FLT_MAX, true)); j->setDriveVelocity(PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f), true); } else if(gSceneIndex==1) { j->setDrive(PxD6Drive::eTWIST, PxD6JointDrive(0, 1000, FLT_MAX, true)); j->setDriveVelocity(PxVec3(0.0f), PxVec3(1.0f, 0.0f, 0.0f), true); } else if(gSceneIndex==2) { j->setDrive(PxD6Drive::eSWING, PxD6JointDrive(0, 1000, FLT_MAX, true)); j->setDriveVelocity(PxVec3(0.0f), PxVec3(0.0f, 1.0f, 0.0f), true); } else if(gSceneIndex==3) { j->setDrive(PxD6Drive::eSLERP, PxD6JointDrive(0, 1000, FLT_MAX, true)); j->setDriveVelocity(PxVec3(0.0f), PxVec3(0.0f, 1.0f, 0.0f), true); } } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); #if PX_SUPPORT_GPU_PHYSX PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if(gCudaContextManager) { if(!gCudaContextManager->contextIsValid()) PX_RELEASE(gCudaContextManager); } #endif gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); createScene(); } void stepPhysics(bool /*interactive*/) { if(gPause && !gOneFrame) return; gOneFrame = false; gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } #if PX_SUPPORT_GPU_PHYSX PX_RELEASE(gCudaContextManager); #endif PX_RELEASE(gFoundation); printf("SnippetJointDrive done.\n"); } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to change body0's joint frame orientation"); Snippets::print("Press F2 to change body0's type (static/kinematic)"); Snippets::print("Press F3 to change body1's joint frame orientation"); Snippets::print("Press F4 to change body1's orientation"); #if PX_SUPPORT_GPU_PHYSX Snippets::print("Press F5 to use CPU or GPU"); #endif Snippets::print("Press F6 to select the next drive"); switch(gSceneIndex) { case 0: Snippets::print("Current drive: linear X"); break; case 1: Snippets::print("Current drive: angular twist (around X)"); break; case 2: Snippets::print("Current drive: angular swing (around Y)"); break; case 3: Snippets::print("Current drive: angular slerp (around Y)"); break; } #if PX_SUPPORT_GPU_PHYSX if(gUseGPU) Snippets::print("Current mode: GPU"); else Snippets::print("Current mode: CPU"); #endif Snippets::print("body1's translation or rotation (drive) axis should only depend on body0's joint axes."); #endif } void keyPress(unsigned char key, const PxTransform&) { if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } if(key==1) { gChangeJointFrameARotation = !gChangeJointFrameARotation; createScene(); } else if(key==2) { gChangeObjectAType = !gChangeObjectAType; createScene(); } else if(key==3) { gChangeJointFrameBRotation = !gChangeJointFrameBRotation; createScene(); } else if(key==4) { gChangeObjectBRotation = !gChangeObjectBRotation; createScene(); } #if PX_SUPPORT_GPU_PHYSX else if(key==5) { gUseGPU = !gUseGPU; createScene(); } #endif else if(key==6) { gSceneIndex = gSceneIndex + 1; if(gSceneIndex==gMaxSceneIndex) gSceneIndex = 0; createScene(); } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,585
C++
30.135294
114
0.72017
NVIDIA-Omniverse/PhysX/physx/snippets/snippetconvexmeshcreate/SnippetConvexMeshCreate.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. // **************************************************************************** // This snippet creates convex meshes with different cooking settings // and shows how these settings affect the convex mesh creation performance and // the size of the resulting cooked meshes. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static float rand(float loVal, float hiVal) { return loVal + (float(rand())/float(RAND_MAX))*(hiVal - loVal); } template<PxConvexMeshCookingType::Enum convexMeshCookingType, bool directInsertion, PxU32 gaussMapLimit> static void createRandomConvex(PxU32 numVerts, const PxVec3* verts) { PxTolerancesScale tolerances; PxCookingParams params(tolerances); // Use the new (default) PxConvexMeshCookingType::eQUICKHULL params.convexMeshCookingType = convexMeshCookingType; // If the gaussMapLimit is chosen higher than the number of output vertices, no gauss map is added to the convex mesh data (here 256). // If the gaussMapLimit is chosen lower than the number of output vertices, a gauss map is added to the convex mesh data (here 16). params.gaussMapLimit = gaussMapLimit; // Setup the convex mesh descriptor PxConvexMeshDesc desc; // We provide points only, therefore the PxConvexFlag::eCOMPUTE_CONVEX flag must be specified desc.points.data = verts; desc.points.count = numVerts; desc.points.stride = sizeof(PxVec3); desc.flags = PxConvexFlag::eCOMPUTE_CONVEX; PxU32 meshSize = 0; PxConvexMesh* convex = NULL; PxU64 startTime = SnippetUtils::getCurrentTimeCounterValue(); if(directInsertion) { // Directly insert mesh into PhysX convex = PxCreateConvexMesh(params, desc, gPhysics->getPhysicsInsertionCallback()); PX_ASSERT(convex); } else { // Serialize the cooked mesh into a stream. PxDefaultMemoryOutputStream outStream; bool res = PxCookConvexMesh(params, desc, outStream); PX_UNUSED(res); PX_ASSERT(res); meshSize = outStream.getSize(); // Create the mesh from a stream. PxDefaultMemoryInputData inStream(outStream.getData(), outStream.getSize()); convex = gPhysics->createConvexMesh(inStream); PX_ASSERT(convex); } // Print the elapsed time for comparison PxU64 stopTime = SnippetUtils::getCurrentTimeCounterValue(); float elapsedTime = SnippetUtils::getElapsedTimeInMilliseconds(stopTime - startTime); printf("\t -----------------------------------------------\n"); printf("\t Create convex mesh with %d triangles: \n", numVerts); directInsertion ? printf("\t\t Direct mesh insertion enabled\n") : printf("\t\t Direct mesh insertion disabled\n"); printf("\t\t Gauss map limit: %d \n", gaussMapLimit); printf("\t\t Created hull number of vertices: %d \n", convex->getNbVertices()); printf("\t\t Created hull number of polygons: %d \n", convex->getNbPolygons()); printf("\t Elapsed time in ms: %f \n", double(elapsedTime)); if (!directInsertion) { printf("\t Mesh size: %d \n", meshSize); } convex->release(); } static void createConvexMeshes() { const PxU32 numVerts = 64; PxVec3* vertices = new PxVec3[numVerts]; // Prepare random verts for(PxU32 i = 0; i < numVerts; i++) { vertices[i] = PxVec3(rand(-20.0f, 20.0f), rand(-20.0f, 20.0f), rand(-20.0f, 20.0f)); } // Create convex mesh using the quickhull algorithm with different settings printf("-----------------------------------------------\n"); printf("Create convex mesh using the quickhull algorithm: \n\n"); // The default convex mesh creation serializing to a stream, useful for offline cooking. createRandomConvex<PxConvexMeshCookingType::eQUICKHULL, false, 16>(numVerts, vertices); // The default convex mesh creation without the additional gauss map data. createRandomConvex<PxConvexMeshCookingType::eQUICKHULL, false, 256>(numVerts, vertices); // Convex mesh creation inserting the mesh directly into PhysX. // Useful for runtime cooking. createRandomConvex<PxConvexMeshCookingType::eQUICKHULL, true, 16>(numVerts, vertices); // Convex mesh creation inserting the mesh directly into PhysX, without gauss map data. // Useful for runtime cooking. createRandomConvex<PxConvexMeshCookingType::eQUICKHULL, true, 256>(numVerts, vertices); delete [] vertices; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true); } void cleanupPhysics() { PX_RELEASE(gPhysics); PX_RELEASE(gFoundation); printf("SnippetConvexMeshCreate done.\n"); } int snippetMain(int, const char*const*) { initPhysics(); createConvexMeshes(); cleanupPhysics(); return 0; }
6,604
C++
37.401163
135
0.727135
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomjoint/PulleyJoint.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PULLEY_JOINT_H #define PULLEY_JOINT_H #include "PxPhysicsAPI.h" // a pulley joint constrains two actors such that the sum of their distances from their respective anchor points at their attachment points // is a fixed value (the parameter 'distance'). Only dynamic actors are supported. // // The constraint equation is as follows: // // |anchor0 - attachment0| + |anchor1 - attachment1| * ratio = distance // // where 'ratio' provides mechanical advantage. // // The above equation results in a singularity when the anchor point is coincident with the attachment point; for simplicity // the constraint does not attempt to handle this case robustly. class PulleyJoint : public physx::PxConstraintConnector { public: static const physx::PxU32 TYPE_ID = physx::PxConcreteType::eFIRST_USER_EXTENSION; PulleyJoint(physx::PxPhysics& physics, physx::PxRigidBody& body0, const physx::PxTransform& localFrame0, const physx::PxVec3& attachment0, physx::PxRigidBody& body1, const physx::PxTransform& localFrame1, const physx::PxVec3& attachment1); void release(); // attribute accessor and mutators void setAttachment0(const physx::PxVec3& pos); physx::PxVec3 getAttachment0() const; void setAttachment1(const physx::PxVec3& pos); physx::PxVec3 getAttachment1() const; void setDistance(physx::PxReal totalDistance); physx::PxReal getDistance() const; void setRatio(physx::PxReal ratio); physx::PxReal getRatio() const; // PxConstraintConnector boilerplate void* prepareData(); void onConstraintRelease(); void onComShift(physx::PxU32 actor); void onOriginShift(const physx::PxVec3& shift); void* getExternalReference(physx::PxU32& typeID); bool updatePvdProperties(physx::pvdsdk::PvdDataStream&, const physx::PxConstraint*, physx::PxPvdUpdateType::Enum) const { return true; } void updateOmniPvdProperties() const { } physx::PxBase* getSerializable() { return NULL; } virtual physx::PxConstraintSolverPrep getPrep() const; virtual const void* getConstantBlock() const { return &mData; } struct PulleyJointData { physx::PxTransform c2b[2]; physx::PxVec3 attachment0; physx::PxVec3 attachment1; physx::PxReal distance; physx::PxReal ratio; physx::PxReal tolerance; }; physx::PxRigidBody* mBody[2]; physx::PxTransform mLocalPose[2]; physx::PxConstraint* mConstraint; PulleyJointData mData; ~PulleyJoint() {} }; #endif
4,140
C
35.973214
140
0.750483
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomjoint/SnippetCustomJoint.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. // **************************************************************************** // This snippet illustrates the implementation and use of a pulley joint // using physx' custom constraint framework. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "PulleyJoint.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); // two boxes connected by the pulley, one twice the density of the other PxBoxGeometry boxGeom(1.0f, 1.0f, 1.0f); PxRigidDynamic* box0 = PxCreateDynamic(*gPhysics, PxTransform(PxVec3(5,5,0)), boxGeom, *gMaterial, 1.0f); PxRigidDynamic* box1 = PxCreateDynamic(*gPhysics, PxTransform(PxVec3(0,5,0)), boxGeom, *gMaterial, 2.0f); PulleyJoint* joint = new PulleyJoint(*gPhysics, *box0, PxTransform(PxVec3(0.0f,1.0f,0.0f)), PxVec3(5.0f,10.0f,0.0f), *box1, PxTransform(PxVec3(0.0f,1.0f,0.0f)), PxVec3(0.0f,10.0f,0.0f)); joint->setDistance(8.0f); gScene->addActor(*box0); gScene->addActor(*box1); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCustomJoint done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
5,021
C++
36.477612
117
0.727943
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomjoint/PulleyJoint.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 "PulleyJoint.h" #include <assert.h> #include "PxConstraint.h" using namespace physx; //TAG:solverprepshader static PxU32 solverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 maxConstraints, PxConstraintInvMassScale&, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { PX_UNUSED(maxConstraints); const PulleyJoint::PulleyJointData& data = *reinterpret_cast<const PulleyJoint::PulleyJointData*>(constantBlock); PxTransform cA2w = bA2w.transform(data.c2b[0]); PxTransform cB2w = bB2w.transform(data.c2b[1]); cA2wOut = cA2w.p; cB2wOut = cB2w.p; body0WorldOffset = cB2w.p - bA2w.p; PxVec3 directionA = data.attachment0 - cA2w.p; PxReal distanceA = directionA.normalize(); PxVec3 directionB = data.attachment1 - cB2w.p; PxReal distanceB = directionB.normalize(); directionB *= data.ratio; PxReal totalDistance = distanceA + distanceB; // compute geometric error: PxReal geometricError = (data.distance - totalDistance); Px1DConstraint *c = constraints; // constraint is breakable, so we need to output forces c->flags = Px1DConstraintFlag::eOUTPUT_FORCE; if (geometricError < 0.0f) { c->maxImpulse = PX_MAX_F32; c->minImpulse = 0; c->geometricError = geometricError; } else if(geometricError > 0.0f) { c->maxImpulse = 0; c->minImpulse = -PX_MAX_F32; c->geometricError = geometricError; } c->linear0 = directionA; c->angular0 = (cA2w.p - bA2w.p).cross(c->linear0); c->linear1 = -directionB; c->angular1 = (cB2w.p - bB2w.p).cross(c->linear1); return 1; } static void visualize( PxConstraintVisualizer& viz, const void* constantBlock, const PxTransform& body0Transform, const PxTransform& body1Transform, PxU32 flags) { PX_UNUSED(flags); const PulleyJoint::PulleyJointData& data = *reinterpret_cast<const PulleyJoint::PulleyJointData*>(constantBlock); PxTransform cA2w = body0Transform * data.c2b[0]; PxTransform cB2w = body1Transform * data.c2b[1]; viz.visualizeJointFrames(cA2w, cB2w); viz.visualizeJointFrames(PxTransform(data.attachment0), PxTransform(data.attachment1)); } static PxConstraintShaderTable sShaderTable = { solverPrep, visualize, PxConstraintFlag::Enum(0) }; PxConstraintSolverPrep PulleyJoint::getPrep() const { return solverPrep; } PulleyJoint::PulleyJoint(PxPhysics& physics, PxRigidBody& body0, const PxTransform& localFrame0, const PxVec3& attachment0, PxRigidBody& body1, const PxTransform& localFrame1, const PxVec3& attachment1) { mConstraint = physics.createConstraint(&body0, &body1, *this, sShaderTable, sizeof(PulleyJointData)); mBody[0] = &body0; mBody[1] = &body1; // keep these around in case the CoM gets relocated mLocalPose[0] = localFrame0.getNormalized(); mLocalPose[1] = localFrame1.getNormalized(); // the data which will be fed to the joint solver and projection shaders mData.attachment0 = attachment0; mData.attachment1 = attachment1; mData.distance = 1.0f; mData.ratio = 1.0f; mData.c2b[0] = body0.getCMassLocalPose().transformInv(mLocalPose[0]); mData.c2b[1] = body1.getCMassLocalPose().transformInv(mLocalPose[1]); } void PulleyJoint::release() { mConstraint->release(); } ///////////////////////////////////////////// attribute accessors and mutators void PulleyJoint::setAttachment0(const PxVec3& pos) { mData.attachment0 = pos; mConstraint->markDirty(); } PxVec3 PulleyJoint::getAttachment0() const { return mData.attachment0; } void PulleyJoint::setAttachment1(const PxVec3& pos) { mData.attachment1 = pos; mConstraint->markDirty(); } PxVec3 PulleyJoint::getAttachment1() const { return mData.attachment1; } void PulleyJoint::setDistance(float totalDistance) { mData.distance = totalDistance; mConstraint->markDirty(); } float PulleyJoint::getDistance() const { return mData.distance; } void PulleyJoint::setRatio(float ratio) { mData.ratio = ratio; mConstraint->markDirty(); } float PulleyJoint::getRatio() const { return mData.ratio; } ///////////////////////////////////////////// PxConstraintConnector methods void* PulleyJoint::prepareData() { return &mData; } void PulleyJoint::onConstraintRelease() { delete this; } void PulleyJoint::onComShift(PxU32 actor) { mData.c2b[actor] = mBody[actor]->getCMassLocalPose().transformInv(mLocalPose[actor]); mConstraint->markDirty(); } void PulleyJoint::onOriginShift(const PxVec3& shift) { mData.attachment0 -= shift; mData.attachment1 -= shift; } void* PulleyJoint::getExternalReference(PxU32& typeID) { typeID = TYPE_ID; return this; }
6,369
C++
28.627907
123
0.733396
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomjoint/SnippetCustomJointRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet HelloWorld", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,931
C++
33.904762
136
0.758103
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonequerysystem/SnippetStandaloneQuerySystemRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet StandaloneQuerySystem", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,909
C++
33.642857
117
0.75043
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonequerysystem/SnippetStandaloneQuerySystem.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. // **************************************************************************** // This snippet illustrates how to use a custom query system and the low-level // cooking functions. // // This is similar to SnippetStandaloneBVH, but this time using a more // advanced query system instead of a single PxBVH. // // This snippet illustrates a basic setup and a single type of query // (raycast closest hit). For more queries see SnippetQuerySystemAllQueries. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "GuQuerySystem.h" #include "GuFactory.h" #include "GuCooking.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace Gu; // The query system can compute the bounds for you, or you can do it manually. Manual bounds // computation can be useful for specific effects (like using temporal bounds) or if there is // an external system that already computed the bounds and recomputing them would be a waste. // Automatic bounds computation is easier to use and less error-prone. static const bool gManualBoundsComputation = false; // The query system can delay internal transform/bounds updates or use the data immediately. // Delaying updates can be faster due to batching, but it uses more memory to store the data until // the actual update happens. Delaying the update can also serve as a double-buffering mechanism, // allowing one to query the old state of the system until a later user-controlled point in time. static const bool gUseDelayedUpdates = true; // Bounds in the query system can be inflated a bit to fight numerical inaccuracy errors that can happen // when a ray or a query-volume just touches the bounds. Users can manually inflate bounds or let the // system do it. Because the system can compute the bounds automatically, it is necessary to let it know // about the inflation value. static const float gBoundsInflation = 0.001f; #define MAX_NB_OBJECTS 32 namespace { class CustomScene : public Adapter { public: CustomScene(); ~CustomScene() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void render(); bool raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxGeomRaycastHit& hit) const; void updateObjects(); struct Object { PxGeometryHolder mGeom; ActorShapeData mData; }; PxU32 mNbObjects; Object mObjects[MAX_NB_OBJECTS]; QuerySystem* mQuerySystem; PxU32 mPrunerIndex; }; static const PxGeometry& getGeometryFromPayload(const PrunerPayload& payload) { const CustomScene* cs = reinterpret_cast<const CustomScene*>(payload.data[1]); return cs->mObjects[PxU32(payload.data[0])].mGeom.any(); } const PxGeometry& CustomScene::getGeometry(const PrunerPayload& payload) const { // This function is called by the system to compute bounds. It will never be // called if 'gManualBoundsComputation' is true. PX_ASSERT(!gManualBoundsComputation); return getGeometryFromPayload(payload); } void CustomScene::release() { PX_DELETE(mQuerySystem); PX_DELETE_THIS; } CustomScene::CustomScene() : mNbObjects(0) { // The contextID is a parameter sent to the profiler to identify the owner of a profile event. // In PhysX this is usually the PxScene pointer, and it is used by PVD to group together all profile events of a given scene. // We do not have a PxScene object here so we can put an arbitrary value there. The value will only be used by // PVD to display profiling results. const PxU64 contextID = PxU64(this); // First we create a query system and give it an adapter. The adapter is used to retrieve the geometry // of objects in the system. This is needed when the system automatically computes bounds for users. // The geometry is not stored directly in the system to avoid duplication, and make it easy to reuse // the system with PxShape-based objects. In this snippet the system will call the // 'CustomScene::getGeometry' function above to fetch an object's geometry. mQuerySystem = PX_NEW(QuerySystem)(contextID, gBoundsInflation, *this); // PhysX uses a hardcoded number of pruners (one for static objects, one for dynamic objects, // and an optional one for compound). The query system here is more flexible and supports an // arbitrary number of pruners, which have to be created by users and added to the system // explicitly. In this snippet we just use a single pruner of a chosen type: Pruner* pruner = createAABBPruner(contextID, true, COMPANION_PRUNER_INCREMENTAL, BVH_SPLATTER_POINTS, 4); // Then we add it to the query system, which takes ownership of the object (it will delete // the pruner when the query system is released). Each pruner is given an index by the // system, used in 'addPrunerShape' to identify which pruner each object is added to. mPrunerIndex = mQuerySystem->addPruner(pruner, 0); } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { PX_ASSERT(mQuerySystem); // The query system operates on anonymous 'payloads', which are basically glorified user-data. // We put here what we need to implement 'CustomScene::getGeometry'. PrunerPayload payload; payload.data[0] = mNbObjects; // This will be the index of our new object, see below. payload.data[1] = size_t(this); // We store the geometry first, because in automatic mode the 'CustomScene::getGeometry' function // will be called by 'addPrunerShape' below, so we need the geometry to be properly setup first. Object& obj = mObjects[mNbObjects]; obj.mGeom.storeAny(geom); // The query system manages a built-in timestamp for static objects, which is used by external // sub-systems like character controllers to invalidate their caches. This is not needed in // this snippet so any value works here. const bool isDynamic = true; // In automatic mode the system will compute the bounds for us. // In manual mode we compute the bounds first and pass them to the system. // // Note that contrary to bounds, the transforms are duplicated and stored within the query // system. In this snippet we take advantage of this by not storing the poses anywhere // else - we will retrieve them from the query system when we need them. In a more complex // example this could create a duplication of the transforms, but this 'double-buffering' is // actually done on purpose to make sure the query system can run in parallel to the app's // code when/if it modifies the objects' poses. The poses are double-buffered but the geometries // are not, because poses of dynamic objects change each frame while geometries do not. if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom, pose, 0.0f, 1.0f + gBoundsInflation); obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, &bounds); } else { obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, NULL); } mNbObjects++; } void CustomScene::updateObjects() { if(!mQuerySystem) return; static float time = 0.0f; time += 0.01f; const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); // Compute an arbitrary new pose for this object PxTransform pose; { pose.p.x = sinf(time)*cosf(time+coeff)*10.0f; pose.p.y = sinf(time*1.17f)*cosf(time*1.17f+coeff)*2.0f; pose.p.z = sinf(time*0.33f)*cosf(time*0.33f+coeff)*10.0f; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; pose.q = PxQuat(rot); pose.q.normalize(); } // Now we're going to tell the query system about it. It is important to // understand that updating the query system is a multiple-steps process: // a) we need to store the new transform and/or bounds in the system. // b) the internal data-structures have to be updated to take a) into account. // // For example if the internal data-structure is an AABB-tree (but it doesn't // have to be, this is pruner-dependent) then (a) would be writing the new bounds // value in a leaf node, while (b) would be refitting the tree accordingly. Or // in a different implementation (a) could be storing the bounds in a linear // array and (b) could be rebuilding the tree from scratch. // // The important point is that there is a per-object update (a), and a global // per-pruner update (b). It would be very inefficient to do (a) and (b) // sequentially for each object (we don't want to rebuild the tree more than // once for example) so the update process is separated into two clearly // distinct phases. The phase we're dealing with here is (a), via the // 'updatePrunerShape' function. const Object& obj = mObjects[i]; if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj.mGeom.any(), pose, 0.0f, 1.0f + gBoundsInflation); mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, &bounds); } else { // Note: in this codepath the system will compute the bounds automatically: // - if 'immediately' is true, the system will call back 'CustomScene::getGeometry' // during the 'updatePrunerShape' call. // - otherwise it will call 'CustomScene::getGeometry' later during the // 'mQuerySystem->update' call (below). mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, NULL); } } // This is the per-pruner update (b) we mentioned just above. It commits the // updates we just made and reflects them into the internal data-structures. // // Note that this function must also be called after adding & removing objects. // // Finally, this function also manages the incremental rebuild of internal structures // if the 'buildStep' parameter is true. This is a convenience function that does // everything needed in a single call. If all the updates to the system happen in // a single place, like in this snippet, then this is everything you need. mQuerySystem->update(true, true); } namespace { struct CustomPrunerFilterCallback : public PrunerFilterCallback { virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& /*hitFlags*/) { return &getGeometryFromPayload(payload); } }; } static CustomPrunerFilterCallback gFilterCallback; static CachedFuncs gCachedFuncs; bool CustomScene::raycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxGeomRaycastHit& hit) const { if(!mQuerySystem) return false; // In this snippet our update loop is simple: // // - update all objects ('mQuerySystem->updatePrunerShape') // - call 'mQuerySystem->update' // - then perform raycasts // // Because we call 'mQuerySystem->update' just before performing the raycasts, // we guarantee that the internal data-structures are up-to-date and we can // immediately call 'mQuerySystem->raycast'. // // However things can become more complicated: // - sometimes 'mQuerySystem->updatePrunerShape' is immediately followed by a // raycast (ex: spawning an object, using a raycast to locate it on the map, repeat) // - sometimes raycasts happen from multiple threads in no clear order // // In these cases the following call to 'commitUpdates' is needed to commit the // minimal amount of updates to the system, so that correct raycast results are // guaranteed. In particular this call omits the 'build step' performed in the // main 'mQuerySystem->update' function (users should have one build step per // frame). This function is also thread-safe, i.e. you can call commitUpdates // and raycasts from multiple threads (contrary to 'mQuerySystem->update'). // // Note that in PxScene::raycast() this call is always executed. But this custom // query system lets users control when & where it happens. The system becomes // more flexible, but puts more burden on users. if(0) mQuerySystem->commitUpdates(); // After that the raycast code itself is rather simple. DefaultPrunerRaycastClosestCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist, PxHitFlag::eDEFAULT); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); if(CB.mFoundHit) hit = CB.mClosestHit; return CB.mFoundHit; } void CustomScene::render() { updateObjects(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PrunerPayloadData ppd; mQuerySystem->getPayloadData(obj.mData, &ppd); Snippets::DrawBounds(*ppd.mBounds); Snippets::renderGeoms(1, &obj.mGeom, ppd.mTransform, false, color); } //mQuerySystem->visualize(true, true, PxRenderOutput) const PxU32 screenWidth = Snippets::getScreenWidth(); const PxU32 screenHeight = Snippets::getScreenHeight(); Snippets::Camera* sCamera = Snippets::getCamera(); const PxVec3 camPos = sCamera->getEye(); const PxVec3 camDir = sCamera->getDir(); #if PX_DEBUG const PxU32 RAYTRACING_RENDER_WIDTH = 64; const PxU32 RAYTRACING_RENDER_HEIGHT = 64; #else const PxU32 RAYTRACING_RENDER_WIDTH = 256; const PxU32 RAYTRACING_RENDER_HEIGHT = 256; #endif const PxU32 textureWidth = RAYTRACING_RENDER_WIDTH; const PxU32 textureHeight = RAYTRACING_RENDER_HEIGHT; GLubyte* pixels = new GLubyte[textureWidth*textureHeight*4]; const float fScreenWidth = float(screenWidth)/float(RAYTRACING_RENDER_WIDTH); const float fScreenHeight = float(screenHeight)/float(RAYTRACING_RENDER_HEIGHT); { // Contrary to PxBVH, the Gu-level query system does not contain any built-in "SIMD guard". // It is up to users to make sure the SIMD control word is properly setup before calling // these low-level functions. See also OPTIM_SKIP_INTERNAL_SIMD_GUARD in SnippetPathTracing. PX_SIMD_GUARD GLubyte* buffer = pixels; for(PxU32 j=0;j<RAYTRACING_RENDER_HEIGHT;j++) { const PxU32 yi = PxU32(fScreenHeight*float(j)); for(PxU32 i=0;i<RAYTRACING_RENDER_WIDTH;i++) { const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = Snippets::computeWorldRay(xi, yi, camDir); PxGeomRaycastHit hit; if(raycast(camPos, dir, 5000.0f, hit)) { buffer[0] = 128+GLubyte(hit.normal.x*127.0f); buffer[1] = 128+GLubyte(hit.normal.y*127.0f); buffer[2] = 128+GLubyte(hit.normal.z*127.0f); buffer[3] = 255; } else { buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 255; } buffer+=4; } } } const GLuint texID = Snippets::CreateTexture(textureWidth, textureHeight, pixels, false); #if PX_DEBUG Snippets::DisplayTexture(texID, 256, 10); #else Snippets::DisplayTexture(texID, RAYTRACING_RENDER_WIDTH, 10); #endif delete [] pixels; Snippets::ReleaseTexture(texID); #endif } } static CustomScene* gScene = NULL; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; void initPhysics(bool /*interactive*/) { // We first initialize the PhysX libs we need to create PxGeometry-based objects. // That is only Foundation, since we'll use the low-level cooking functions here. // (We don't need to initialize the cooking library). // Also note how we are not going to use a PxScene in this snippet, and in fact // we're not going to need anything from the main PhysX_xx.dll, we only use // PhysXCommon_xx.dll. gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); // Cook one convex mesh and one triangle mesh used in this snippet { // Some cooking parameters will have an impact on the performance of our queries, // some will not. Generally speaking midphase-related parameters are still important // here, while anything related to contact-generation can be disabled. const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; // The convex mesh { const PxF32 width = 3.0f; const PxF32 radius = 1.0f; PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } PxConvexMeshDesc convexDesc; convexDesc.points.count = 32; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = points; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; gConvexMesh = immediateCooking::createConvexMesh(params, convexDesc); } // The triangle mesh { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = immediateCooking::createTriangleMesh(params, meshDesc); } } // Create our custom scene and populate it with some custom PxGeometry-based objects { gScene = new CustomScene; gScene->addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f))); gScene->addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f))); gScene->addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f))); gScene->addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f))); } } void renderScene() { if(gScene) gScene->render(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gTriangleMesh); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetStandaloneQuerySystem done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { } int snippetMain(int, const char*const*) { printf("Standalone Query System snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
20,908
C++
36.606115
138
0.733069
NVIDIA-Omniverse/PhysX/physx/snippets/snippetbvhstructure/SnippetBVHStructure.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. // **************************************************************************** // This snippet illustrates the usage of PxBVH for PxScene's addActor function. // // It creates a large number of small sphere shapes forming a large sphere. Large sphere // represents an actor and the actor is inserted into the scene with a BVH // that is precomputed from all the small spheres. When an actor is inserted this // way the scene queries against this object behave actor centric rather than shape // centric. // Each actor that is added with a BVH does not update any of its shape bounds // within a pruning structure. It does update just the actor bounds and the query then // goes into actors bounds pruner, then a local query is done against the shapes in the // actor. // For a dynamic actor consisting of a large amound of shapes there can be a significant // performance benefits. During fetch results, there is no need to synchronize all // shape bounds into scene query system. Also when a new AABB tree is build inside // scene query system these actors shapes are not contained there. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static void createLargeSphere(const PxTransform& t, PxU32 density, PxReal largeRadius, PxReal radius, bool useAggregate) { PxRigidDynamic* body = gPhysics->createRigidDynamic(t); // generate the sphere shapes const float gStep = PxPi/float(density); const float tStep = 2.0f*PxPi/float(density); for(PxU32 i=0; i<density;i++) { for(PxU32 j=0;j<density;j++) { const float sinG = PxSin(gStep * i); const float cosG = PxCos(gStep * i); const float sinT = PxSin(tStep * j); const float cosT = PxCos(tStep * j); PxTransform localTm(PxVec3(largeRadius*sinG*cosT, largeRadius*sinG*sinT, largeRadius*cosG)); PxShape* shape = gPhysics->createShape(PxSphereGeometry(radius), *gMaterial); shape->setLocalPose(localTm); body->attachShape(*shape); shape->release(); } } PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); // get the bounds from the actor, this can be done through a helper function in PhysX extensions PxU32 numBounds = 0; PxBounds3* bounds = PxRigidActorExt::getRigidActorShapeLocalBoundsList(*body, numBounds); printf("Creating BVH structure for large compound actor...\n"); // setup the PxBVHDesc, it does contain only the PxBounds3 data PxBVHDesc bvhDesc; bvhDesc.bounds.count = numBounds; bvhDesc.bounds.data = bounds; bvhDesc.bounds.stride = sizeof(PxBounds3); // cook the bvh PxBVH* bvh = PxCreateBVH(bvhDesc, gPhysics->getPhysicsInsertionCallback()); // release the memory allocated within extensions, the bounds are not required anymore gAllocator.deallocate(bounds); if(useAggregate) printf("Adding actor + BVH structure to aggregate...\n"); else printf("Adding actor + BVH structure to scene...\n"); // add the actor to the scene and provide the bvh structure (regular path without aggregate usage) if(!useAggregate) gScene->addActor(*body, bvh); // Note that when objects with large amound of shapes are created it is also // recommended to create an aggregate from them, see the code below that would replace // the gScene->addActor(*body, bvh) if(useAggregate) { PxAggregate* aggregate = gPhysics->createAggregate(1, body->getNbShapes(), false); aggregate->addActor(*body, bvh); gScene->addAggregate(*aggregate); } // bvh can be released at this point, the precomputed BVH structure was copied to the SDK pruners. bvh->release(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i = 0; i < 10; i++) createLargeSphere(PxTransform(PxVec3(200.0f*i, .0f, 100.0f)), 50, 30.0f, 1.0f, false); } void stepPhysics(bool /*interactive*/) { printf("Simulating...\n"); gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetBVH done.\n"); } void keyPress(unsigned char , const PxTransform& ) { } int snippetMain(int, const char*const*) { static const PxU32 frameCount = 50; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); return 0; }
7,719
C++
37.79397
120
0.736235
NVIDIA-Omniverse/PhysX/physx/snippets/snippetconvert/SnippetConvert.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. // *********************************************************************************************** // This snippet illustrates how to convert PhysX serialized binary files from one platform to // another. The conversion requires three input files: // // Note: Binary conversion has been DEPRECATED // // 1. A metadata file that was created on the source platform. This file specifies the // source platform as well as the layout of PhysX data structures on the source platform. // 2. A metadata file that was created on the target platform. This file specifies the target // (destination) platform as well as the layout of PhysX data structures on the target platform. // 3. A source file containing a binary serialized collection. The platform this file was created // on needs to match with the platform the source metadata file has been created on. // // Optionally this snippet allows to create a example file with binary serialized data for the // platform the snippet runs on. // // The conversion snippet only compiles and runs on authoring platforms (windows, osx and linux). // // SnippetConvert is a simple command-line tool supporting the following options:: // // --srcMetadata=<filename> Specify the source metadata (and the source platform) // --dstMetadata=<filename> Specify the target metadata (and the target platform) // --srcBinFile=<filename> Source binary file to convert (serialized on target platform) // --dstBinFile=<filename> Outputs target binary file // --generateExampleFile=<filename> Generates an example file // --dumpBinaryMetaData=<filename> Dump binary meta data for current runtime platform // --verbose Enables verbose mode // // *********************************************************************************************** #include "PxPhysicsAPI.h" #include <iostream> #include "../snippetcommon/SnippetPrint.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxSerializationRegistry* gSerializationRegistry = NULL; struct CmdLineParameters { bool verbose; const char* srcMetadata; const char* dstMetadata; const char* srcBinFile; const char* dstBinFile; const char* exampleFile; const char* dumpMetaDataFile; CmdLineParameters() : verbose(false) , srcMetadata(NULL) , dstMetadata(NULL) , srcBinFile(NULL) , dstBinFile(NULL) , exampleFile(NULL) , dumpMetaDataFile(NULL) { } }; static bool match(const char* opt, const char* ref) { std::string s1(opt); std::string s2(ref); return !s1.compare(0, s2.length(), s2); } static void printHelpMsg() { printf("SnippetConvert usage:\n" "SnippetConvert " "--srcMetadata=<filename> " "--dstMetadata=<filename> " "--srcBinFile=<filename> " "--dstBinFile=<filename> " "--generateExampleFile=<filename> " "--dumpBinaryMetaData=<filename> " "--verbose \n"); printf("--srcMetadata=<filename>\n"); printf(" Defines source metadata file\n"); printf("--dstMetadata=<filename>\n"); printf(" Defines target metadata file\n"); printf("--srcBinFile=<filename>\n"); printf(" Source binary file to convert\n"); printf("--dstBinFile=<filename>\n"); printf(" Outputs target binary file\n"); printf("--generateExampleFile=<filename>\n"); printf(" Generates an example file\n"); printf("--dumpBinaryMetaData=<filename>\n"); printf(" Dump binary meta data for current runtime platform\n"); printf("--verbose\n"); printf(" Enables verbose mode\n"); } static bool parseCommandLine(CmdLineParameters& result, int argc, const char *const*argv) { if( argc <= 1 ) { printHelpMsg(); return false; } #define GET_PARAMETER(v, s) \ { \ v = argv[i] + strlen(s); \ if( v == NULL ) \ { \ printf("[ERROR] \"%s\" should have extra parameter\n", argv[i]);\ printHelpMsg(); \ return false; \ } \ } for(int i = 0; i < argc; ++i) { if(argv[i][0] != '-' || argv[i][1] != '-') { if( i > 0 ) { printf( "[ERROR] Unknown command line parameter \"%s\"\n", argv[i] ); printHelpMsg(); return false; } continue; } if(match(argv[i], "--verbose")) { result.verbose = true; } else if(match(argv[i], "--srcMetadata=")) { GET_PARAMETER(result.srcMetadata, "--srcMetadata="); } else if(match(argv[i], "--dstMetadata=")) { GET_PARAMETER(result.dstMetadata, "--dstMetadata="); } else if(match(argv[i], "--srcBinFile=")) { GET_PARAMETER(result.srcBinFile, "--srcBinFile="); } else if(match(argv[i], "--dstBinFile=")) { GET_PARAMETER(result.dstBinFile, "--dstBinFile="); } else if(match(argv[i], "--generateExampleFile=")) { GET_PARAMETER(result.exampleFile, "--generateExampleFile="); break; } else if (match(argv[i], "--dumpBinaryMetaData=")) { GET_PARAMETER(result.dumpMetaDataFile, "--dumpBinaryMetaData="); break; } else { printf( "[ERROR] Unknown command line parameter \"%s\"\n", argv[i] ); printHelpMsg(); return false; } } if( result.exampleFile || result.dumpMetaDataFile) return true; if( !result.srcMetadata || !result.dstMetadata || !result.srcBinFile || !result.dstBinFile) { printf("[ERROR] Missed args!! \n"); printHelpMsg(); return false; } return true; } static bool generateExampleFile(const char* filename) { PxCollection* collection = PxCreateCollection(); PX_ASSERT( collection ); PxMaterial *material = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PX_ASSERT( material ); PxShape* shape = gPhysics->createShape(PxBoxGeometry(2.f, 2.f, 2.f), *material); PxRigidStatic* theStatic = PxCreateStatic(*gPhysics, PxTransform(PxIdentity), *shape); collection->add(*material); collection->add(*shape); collection->add(*theStatic); PxDefaultFileOutputStream s(filename); bool bret = PxSerialization::serializeCollectionToBinary(s, *collection, *gSerializationRegistry); collection->release(); return bret; } static bool dumpBinaryMetaData(const char* filename) { PxDefaultFileOutputStream s(filename); PxSerialization::dumpBinaryMetaData(s, *gSerializationRegistry); return true; } static void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true); gSerializationRegistry = PxSerialization::createSerializationRegistry(*gPhysics); PxInitVehicleSDK(*gPhysics, gSerializationRegistry); } static void cleanupPhysics() { PxCloseVehicleSDK(gSerializationRegistry); gSerializationRegistry->release(); PX_RELEASE(gPhysics); PX_RELEASE(gFoundation); printf("SnippetConvert done.\n"); } int snippetMain(int argc, const char *const*argv) { CmdLineParameters result; if(!parseCommandLine(result, argc, argv)) return 1; bool bret = false; initPhysics(); if(result.exampleFile || result.dumpMetaDataFile) { if (result.exampleFile) { bret = generateExampleFile(result.exampleFile); } if (result.dumpMetaDataFile) { bret &= dumpBinaryMetaData(result.dumpMetaDataFile); } } else { PxBinaryConverter* binaryConverter = PxSerialization::createBinaryConverter(); if(result.verbose) binaryConverter->setReportMode(PxConverterReportMode::eVERBOSE); else binaryConverter->setReportMode(PxConverterReportMode::eNORMAL); PxDefaultFileInputData srcMetaDataStream(result.srcMetadata); PxDefaultFileInputData dstMetaDataStream(result.dstMetadata); bret = binaryConverter->setMetaData(srcMetaDataStream, dstMetaDataStream); if(!bret) { printf("setMetaData failed\n"); } else { PxDefaultFileInputData srcBinaryDataStream(result.srcBinFile); PxDefaultFileOutputStream dstBinaryDataStream(result.dstBinFile); binaryConverter->convert(srcBinaryDataStream, srcBinaryDataStream.getLength(), dstBinaryDataStream); } binaryConverter->release(); } cleanupPhysics(); return !bret; }
10,060
C++
30.638365
103
0.684195
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2tankdrive/SnippetVehicleTankDrive.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. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a tank with a fully featured drivetrain comprising engine, // clutch, tank differential and gears. The snippet uses only parameters, states and // components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a drivetrain model that forwards input controls to wheel torques via a drivetrain model // that includes engine, clutch, differential and gears. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/EngineDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with engine drivetrain EngineDriveVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "engineDrive"; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake0; //Tanks have two brake controllers: PxF32 brake1; // one brake controller for the left track and one for the right track. PxF32 thrust0; //Tanks have two thrust controllers that divert engine torque to the left and right tracks: PxF32 thrust1; // one thrust controller for the left track and one for the right track. PxF32 throttle; //Tanks are driven by an engine that requires a throttle to generate engine drive torque. PxU32 gear; //Tanks are geared and may use automatic gearing. PxF32 duration; }; const PxU32 gTargetGearCommand = 2; Command gCommands[] = { {0.5f, 0.5f, 0.0f, 0.0f, 1.0f, gTargetGearCommand, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.0f, 0.5f, 0.5f, 1.0f, gTargetGearCommand, 5.0f}, //drive forwards: symmetric forward thrust for 5 seconds {1.0f, 0.0f, 0.0f, 1.0f, 1.0f, gTargetGearCommand, 5.0f}, //sharp turn: brake on track 0, forward thrust on track 1 for 5 seconds {0.0f, 0.0f, 1.0f, -1.0f,1.0f, gTargetGearCommand, 5.0f}, //turn on spot: forward thrust on track 0, reverse thrust on track track 1 for 5 seconds {0.0f, 0.0f, 1.0f, 0.25f,1.0f, gTargetGearCommand, 5.0f}, //gentle steer: asymmetric forward thrust for 5 seconds {0.0f, 0.0f, -1.0f,-1.0f, 1.0f, gTargetGearCommand, 5.0f} //drive backwards: symmetric negative thrust for 5 seconds }; const PxReal gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", gVehicle.mEngineDriveParams); //Set the states to default. if (!gVehicle.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, EngineDriveVehicle::eDIFFTYPE_TANKDRIVE)) { return false; } //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(0.000000000f, -0.0500000119f, -1.59399998f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Set the vehicle in 1st gear. gVehicle.mEngineDriveState.gearboxState.currentGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; gVehicle.mEngineDriveState.gearboxState.targetGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; //Set the vehicle to use automatic gears. gVehicle.mTankDriveTransmissionCommandState.targetGear = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; const PxReal timestep = 1.0f/60.0f; //Apply the brake, throttle and thrusts to the command state of the tank. const Command& command = gCommands[gCommandProgress]; gVehicle.mCommandState.brakes[0] = command.brake0; gVehicle.mCommandState.brakes[1] = command.brake1; gVehicle.mCommandState.nbBrakes = 2; gVehicle.mCommandState.throttle = command.throttle; gVehicle.mCommandState.steer = 0.0f; gVehicle.mTankDriveTransmissionCommandState.thrusts[0] = command.thrust0; gVehicle.mTankDriveTransmissionCommandState.thrusts[1] = command.thrust1; gVehicle.mTankDriveTransmissionCommandState.targetGear = command.gear; //Forward integrate the vehicle by a single timestep. //Apply substepping at low forward speed to improve simulation fidelity. const PxVec3 linVel = gVehicle.mPhysXState.physxActor.rigidBody->getLinearVelocity(); const PxVec3 forwardDir = gVehicle.mPhysXState.physxActor.rigidBody->getGlobalPose().q.getBasisVector2(); const PxReal forwardSpeed = linVel.dot(forwardDir); const PxU8 nbSubsteps = (forwardSpeed < 5.0f ? 3 : 1); gVehicle.mComponentSequence.setSubsteps(gVehicle.mComponentSequenceSubstepGroupHandle, nbSubsteps); gVehicle.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2TankDrive", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. EngineDrivetrainParams engineDrivetrainParams; if (!readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", engineDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { while (gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
15,721
C++
40.702918
147
0.767445
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customsuspension/SnippetVehicleCustomSuspension.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. // **************************************************************************** // This snippet illustrates how to implement and apply custom vehicle components. // // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. // This snippet demonstrates how to modify the vehicle component pipeline to include a custom suspension model. // The vehicle is then a mixture of custom components and components maintained by the PhysX Vehicle SDK. // In this instance, the custom component computes an additional sinusoidal suspension force that is applied // to the vehicle and complements the suspension force of a linear spring model. The combination of sinusoidal // suspension forces entices the vehicle to perform a kind of mechanical dance. //This snippet organises the components into four distinct groups. //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a direct drive drivetrain model that forwards input controls to wheel torques and steer angles. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. //4) a custom suspension model // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" #include "CustomSuspension.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with the custom suspension component CustomSuspensionVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The timestep of the simulation const PxReal gTimestep = 0.016667f; //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "customsuspension"; //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", gVehicle.mBaseParams.axleDescription, gVehicle.mDirectDriveParams); //Set the states to default. if (!gVehicle.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial)) { return false; } gVehicle.mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL; //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(-5.0f, 0.5f, 0.0f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { //Forward integrate the vehicle by a single timestep. gVehicle.step(gTimestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(gTimestep); gScene->fetchResults(true); } int snippetMain(int argc, const char *const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2CustomSuspension", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. DirectDrivetrainParams directDrivetrainParams; if (!readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { PxReal accumulatedTime = 0.0f; while (accumulatedTime < 15.0f) { stepPhysics(); accumulatedTime += gTimestep; } cleanupPhysics(); } #endif return 0; }
12,773
C++
38.304615
127
0.769905
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customsuspension/CustomSuspension.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct CustomSuspensionParams { PxReal phase; PxReal frequency; PxReal amplitude; }; struct CustomSuspensionState { PxReal theta; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(CustomSuspensionState)); } }; void addCustomSuspensionForce (const PxReal dt, const PxVehicleSuspensionParams& suspParams, const CustomSuspensionParams& customParams, const PxVec3& groundNormal, bool isWheelOnGround, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState, PxVehicleSuspensionForce& suspForce, CustomSuspensionState& customState); class CustomSuspensionComponent : public PxVehicleComponent { public: CustomSuspensionComponent() : PxVehicleComponent() {} virtual void getDataForCustomSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, const PxReal*& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleWheelParams*& wheelParams, const PxVehicleSuspensionParams*& suspensionParams, const CustomSuspensionParams*& customSuspensionParams, const PxVehicleSuspensionComplianceParams*& suspensionComplianceParams, const PxVehicleSuspensionForceParams*& suspensionForceParams, const PxVehicleRoadGeometryState*& wheelRoadGeomStates, PxVehicleSuspensionState*& suspensionStates, CustomSuspensionState*& customSuspensionStates, PxVehicleSuspensionComplianceState*& suspensionComplianceStates, PxVehicleSuspensionForce*& suspensionForces) = 0; virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) { const PxVehicleAxleDescription* axleDescription; const PxVehicleRigidBodyParams* rigidBodyParams; const PxVehicleSuspensionStateCalculationParams* suspensionStateCalculationParams; const PxReal* steerResponseStates; const PxVehicleRigidBodyState* rigidBodyState; const PxVehicleWheelParams* wheelParams; const PxVehicleSuspensionParams* suspensionParams; const CustomSuspensionParams* customSuspensionParams; const PxVehicleSuspensionComplianceParams* suspensionComplianceParams; const PxVehicleSuspensionForceParams* suspensionForceParams; const PxVehicleRoadGeometryState* wheelRoadGeomStates; PxVehicleSuspensionState* suspensionStates; CustomSuspensionState* customSuspensionStates; PxVehicleSuspensionComplianceState* suspensionComplianceStates; PxVehicleSuspensionForce* suspensionForces; getDataForCustomSuspensionComponent(axleDescription, rigidBodyParams, suspensionStateCalculationParams, steerResponseStates, rigidBodyState, wheelParams, suspensionParams, customSuspensionParams, suspensionComplianceParams, suspensionForceParams, wheelRoadGeomStates, suspensionStates, customSuspensionStates, suspensionComplianceStates, suspensionForces); for (PxU32 i = 0; i < axleDescription->nbWheels; i++) { const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; //Update the suspension state (jounce, jounce speed) PxVehicleSuspensionStateUpdate( wheelParams[wheelId], suspensionParams[wheelId], *suspensionStateCalculationParams, suspensionForceParams[wheelId].stiffness, suspensionForceParams[wheelId].damping, steerResponseStates[wheelId], wheelRoadGeomStates[wheelId], *rigidBodyState, dt, context.frame, context.gravity, suspensionStates[wheelId]); //Update the compliance from the suspension state. PxVehicleSuspensionComplianceUpdate( suspensionParams[wheelId], suspensionComplianceParams[wheelId], suspensionStates[wheelId], suspensionComplianceStates[wheelId]); //Compute the suspension force from the suspension and compliance states. PxVehicleSuspensionForceUpdate( suspensionParams[wheelId], suspensionForceParams[wheelId], wheelRoadGeomStates[wheelId], suspensionStates[wheelId], suspensionComplianceStates[wheelId], *rigidBodyState, context.gravity, rigidBodyParams->mass, suspensionForces[wheelId]); addCustomSuspensionForce(dt, suspensionParams[wheelId], customSuspensionParams[wheelId], wheelRoadGeomStates[wheelId].plane.n, PxVehicleIsWheelOnGround(suspensionStates[wheelId]), suspensionComplianceStates[wheelId], *rigidBodyState, suspensionForces[wheelId], customSuspensionStates[wheelId]); } return true; } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a custom component for the suspension logic. // //See BaseVehicle for more details on the snippet code design. // class CustomSuspensionVehicle : public DirectDriveVehicle , public CustomSuspensionComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForCustomSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, const PxReal*& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleWheelParams*& wheelParams, const PxVehicleSuspensionParams*& suspensionParams, const CustomSuspensionParams*& customSuspensionParams, const PxVehicleSuspensionComplianceParams*& suspensionComplianceParams, const PxVehicleSuspensionForceParams*& suspensionForceParams, const PxVehicleRoadGeometryState*& wheelRoadGeomStates, PxVehicleSuspensionState*& suspensionStates, CustomSuspensionState*& customSuspensionStates, PxVehicleSuspensionComplianceState*& suspensionComplianceStates, PxVehicleSuspensionForce*& suspensionForces) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionStateCalculationParams = &mBaseParams.suspensionStateCalculationParams; steerResponseStates = mBaseState.steerCommandResponseStates; rigidBodyState = &mBaseState.rigidBodyState; wheelParams = mBaseParams.wheelParams; suspensionParams = mBaseParams.suspensionParams; customSuspensionParams = mCustomSuspensionParams; suspensionComplianceParams = mBaseParams.suspensionComplianceParams; suspensionForceParams = mBaseParams.suspensionForceParams; wheelRoadGeomStates = mBaseState.roadGeomStates; suspensionStates = mBaseState.suspensionStates; customSuspensionStates = mCustomSuspensionStates; suspensionComplianceStates = mBaseState.suspensionComplianceStates; suspensionForces = mBaseState.suspensionForces; } //Parameters and states of the vehicle's custom suspension. CustomSuspensionParams mCustomSuspensionParams[4]; CustomSuspensionState mCustomSuspensionStates[4]; }; }//namespace snippetvehicle2
8,809
C
41.15311
137
0.820184
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customsuspension/CustomSuspension.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 "CustomSuspension.h" namespace snippetvehicle2 { void addCustomSuspensionForce (const PxReal dt, const PxVehicleSuspensionParams& suspParams, const CustomSuspensionParams& customParams, const PxVec3& groundNormal, bool isWheelOnGround, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState, PxVehicleSuspensionForce& suspForce, CustomSuspensionState& customState) { //Work out the oscillating force magnitude at time t. const PxF32 magnitude = (1.0f + PxCos(customParams.phase + customState.theta))*0.5f*customParams.amplitude; //Compute the custom force and torque. const PxVec3 suspDir = isWheelOnGround ? groundNormal : PxVec3(PxZero); const PxVec3 customForce = suspDir * magnitude; const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(suspComplianceState.suspForceAppPoint)); const PxVec3 customTorque = r.cross(customForce); //Increment the phase of the oscillator and clamp it in range (-Pi,Pi) PxReal theta = customState.theta + 2.0f*PxPi*customParams.frequency*dt; if (theta > PxPi) { theta -= 2.0f*PxPi; } else if (theta < -PxPi) { theta += 2.0f*PxPi; } customState.theta = theta; //Add the custom force to the standard suspension force. suspForce.force += customForce; suspForce.torque += customTorque; } bool CustomSuspensionVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { if (!DirectDriveVehicle::initialize(physics, params, defaultMaterial, addPhysXBeginEndComponents)) return false; //Set the custom suspension params for all 4 wheels of the vehicle. { CustomSuspensionParams frontLeft; frontLeft.amplitude = 6000.0f*1.25f; frontLeft.frequency = 2.0f; frontLeft.phase = 0.0f; mCustomSuspensionParams[0] = frontLeft; CustomSuspensionParams frontRight; frontRight.amplitude = 6000.0f*1.25f; frontRight.frequency = 2.0f; frontRight.phase = 0.0f; mCustomSuspensionParams[1] = frontRight; CustomSuspensionParams rearLeft; rearLeft.amplitude = 6000.0f*1.25f; rearLeft.frequency = 2.0f; rearLeft.phase = PxPi * 0.5f; mCustomSuspensionParams[2] = rearLeft; CustomSuspensionParams rearRight; rearRight.amplitude = 6000.0f*1.25f; rearRight.frequency = 2.0f; rearRight.phase = PxPi * 0.5f; mCustomSuspensionParams[3] = rearRight; } //Initialise the custom suspension state. mCustomSuspensionStates[0].setToDefault(); mCustomSuspensionStates[1].setToDefault(); mCustomSuspensionStates[2].setToDefault(); mCustomSuspensionStates[3].setToDefault(); return true; } void CustomSuspensionVehicle::destroy() { DirectDriveVehicle::destroy(); } void CustomSuspensionVehicle::initComponentSequence(const bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we perform 3 updates of the suspensions, tires and wheels without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is //computationally cheaper than simulating the entire sequence. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. //Add an additional sinusoidal suspension force that will entice the vehicle to //perform a kind of mechanical dance. mComponentSequence.add(static_cast<CustomSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
8,228
C++
43.722826
160
0.781842
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/SnippetKinematicSoftBodyRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "SnippetKinematicSoftBody.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern std::vector<SoftBody> gSoftBodies; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 rcaColor(0.6f*0.75f, 0.8f*0.75f, 1.0f*0.75f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; Snippets::renderSoftBody(sb->mSoftBody, sb->mPositionsInvMass, true, rcaColor); } Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(10.0f, 10.0f, 10.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet Partially Kinematic Softbody", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); cleanup(); } #endif
3,349
C++
32.168317
136
0.750075
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/SnippetKinematicSoftBody.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. // **************************************************************************** // This snippet demonstrates how to setup softbodies. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetkinematicsoftbody/SnippetKinematicSoftBody.h" #include "../snippetkinematicsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, const PxFEMMaterial& /*femMaterial*/, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount/*, PxMaterial* tetMeshMaterial*/) { PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); //softBody->setMaterial(femMaterial); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxFEMSoftBodyMaterial* material = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); material->setDamping(0.005f); PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); materialPtr->setMaterialModel(PxFEMSoftBodyMaterialModel::eNEO_HOOKEAN); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, *material, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 0.75f; createCube(triVerts, triIndices, PxVec3(0, 0, 0), PxVec3(2.5f, 10, 2.5f)); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxVec3 position(0, 5.0f, 0); for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3& p = triVerts[i]; PxReal corr = PxSqrt(p.x*p.x + p.z*p.z); if (corr != 0) corr = PxMax(PxAbs(p.x), PxAbs(p.z)) / corr; PxReal scaling = 0.75f + 0.5f * (PxCos(1.5f*p.y) + 1.0f); p.x *= scaling * corr; p.z *= scaling * corr; p += position; } PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBody = createSoftBody(params, triVerts, triIndices, true); SoftBody* sb = &gSoftBodies[0]; sb->copyDeformedVerticesFromGPU(); PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); PxU32 vertexCount = sb->mSoftBody->getSimulationMesh()->getNbVertices(); PxVec4* kinematicTargets = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, vertexCount); PxVec4* positionInvMass = sb->mPositionsInvMass; for (PxU32 i = 0; i < vertexCount; ++i) { PxVec4& p = positionInvMass[i]; bool kinematic = false; if (i < triVerts.size()) { if (p.y > 9.9f) kinematic = true; if (p.y > 5 - 0.1f && p.y < 5 + 0.1f) kinematic = true; if (p.y < 0.1f) kinematic = true; } kinematicTargets[i] = PxConfigureSoftBodyKinematicTarget(p, kinematic); } PxVec4* kinematicTargetsD = PX_DEVICE_ALLOC_T(PxVec4, cudaContextManager, vertexCount); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(softBody->getSimPositionInvMassBufferD()), positionInvMass, vertexCount * sizeof(PxVec4)); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(kinematicTargetsD), kinematicTargets, vertexCount * sizeof(PxVec4)); softBody->setKinematicTargetBufferD(kinematicTargetsD, PxSoftBodyFlag::ePARTIALLY_KINEMATIC); sb->mTargetPositionsH = kinematicTargets; sb->mTargetPositionsD = kinematicTargetsD; sb->mTargetCount = vertexCount; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); // Setup rigid bodies const PxReal dynamicsDensity = 10; const PxReal boxSize = 0.5f; const PxReal spacing = 0.6f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; const PxU32 gridSizeA = 13; const PxU32 gridSizeB = 3; const PxReal initialRadius = 1.65f; const PxReal distanceJointStiffness = 500.0f; const PxReal distanceJointDamping = 0.5f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); shape->setDensityForFluid(dynamicsDensity); PxArray<PxRigidDynamic*> rigids; for (PxU32 i = 0; i < gridSizeA; ++i) for (PxU32 j = 0; j < gridSizeB; ++j) { PxReal x = PxCos((2 * PxPi*i) / gridSizeA); PxReal y = PxSin((2 * PxPi*i) / gridSizeA); PxVec3 pos = PxVec3((x*j)*spacing + x * initialRadius, 8, (y *j)*spacing + y * initialRadius); PxReal d = 0.0f; { PxReal x2 = PxCos((2 * PxPi*(i + 1)) / gridSizeA); PxReal y2 = PxSin((2 * PxPi*(i + 1)) / gridSizeA); PxVec3 pos2 = PxVec3((x2*j)*spacing + x2 * initialRadius, 8, (y2 *j)*spacing + y2 * initialRadius); d = (pos - pos2).magnitude(); } PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(pos)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); rigids.pushBack(body); if (j > 0) { PxDistanceJoint* joint = PxDistanceJointCreate(*gPhysics, rigids[rigids.size() - 2], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint->setMaxDistance(spacing); joint->setMinDistance(spacing*0.5f); joint->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint->setStiffness(distanceJointStiffness); joint->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); } if (i > 0) { PxDistanceJoint* joint = PxDistanceJointCreate(*gPhysics, rigids[rigids.size() - gridSizeB - 1], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint->setMaxDistance(d); joint->setMinDistance(d*0.5f); joint->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint->setStiffness(distanceJointStiffness); joint->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); if (i == gridSizeA - 1) { PxDistanceJoint* joint2 = PxDistanceJointCreate(*gPhysics, rigids[j], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint2->setMaxDistance(d); joint2->setMinDistance(d*0.5f); joint2->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint2->setStiffness(distanceJointStiffness); joint2->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); } } } shape->release(); } PxReal simTime = 0.0f; void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); PxCudaContextManager* cudaContextManager = sb->mCudaContextManager; //Update the kinematic targets to get some motion if (i == 0) { PxReal scaling = PxMin(0.01f, simTime * 0.1f); PxReal velocity = 1.0f; for (PxU32 j = 0; j < sb->mTargetCount; ++j) { PxVec4& target = sb->mTargetPositionsH[j]; if (target.w == 0.0f) { PxReal phase = target.y*2.0f; target.x += scaling * PxSin(velocity * simTime + phase); target.z += scaling * PxCos(velocity * simTime + phase); } } PxScopedCudaLock _lock(*cudaContextManager); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(sb->mTargetPositionsD), sb->mTargetPositionsH, sb->mTargetCount * sizeof(PxVec4)); } } simTime += dt; } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Kinematic Softbody done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
15,897
C++
37.400966
175
0.746619
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/MeshGenerator.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_MESHGENERATOR_H #define PHYSX_MESHGENERATOR_H #include "PxPhysicsAPI.h" #include "extensions/PxRemeshingExt.h" namespace meshgenerator { using namespace physx; void createCube(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& pos, const PxVec3& scaling) { triVerts.clear(); triIndices.clear(); triVerts.pushBack(scaling.multiply(PxVec3(0.5f, -0.5f, -0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(0.5f, -0.5f, 0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(-0.5f, -0.5f, 0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(-0.5f, -0.5f, -0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(0.5f, 0.5f, -0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(0.5f, 0.5f, 0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(-0.5f, 0.5f, 0.5f)) + pos); triVerts.pushBack(scaling.multiply(PxVec3(-0.5f, 0.5f, -0.5f)) + pos); triIndices.pushBack(1); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(6); triIndices.pushBack(5); triIndices.pushBack(4); triIndices.pushBack(5); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(6); triIndices.pushBack(2); triIndices.pushBack(2); triIndices.pushBack(6); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(1); triIndices.pushBack(3); triIndices.pushBack(4); triIndices.pushBack(7); triIndices.pushBack(5); triIndices.pushBack(0); triIndices.pushBack(4); triIndices.pushBack(1); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(2); triIndices.pushBack(7); triIndices.pushBack(4); triIndices.pushBack(0); triIndices.pushBack(7); } void createConeY(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, PxReal height, PxU32 numPointsOnRing = 32) { triVerts.clear(); triIndices.clear(); for (PxU32 i = 0; i < numPointsOnRing; ++i) { PxReal angle = i * 2.0f * 3.1415926535898f / numPointsOnRing; triVerts.pushBack(center + radius * PxVec3(PxSin(angle), 0, PxCos(angle))); } triVerts.pushBack(center); triVerts.pushBack(center + PxVec3(0, height, 0)); for (PxU32 i = 0; i < numPointsOnRing; ++i) { triIndices.pushBack(numPointsOnRing); triIndices.pushBack(i); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(numPointsOnRing + 1); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(i); } } void projectPointsOntoSphere(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); triVerts[i] = center + radius * dir; } } void createSphere(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, const PxReal maxEdgeLength) { triVerts.clear(); triIndices.clear(); createCube(triVerts, triIndices, center, PxVec3(radius)); projectPointsOntoSphere(triVerts, center, radius); while (PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 1)) projectPointsOntoSphere(triVerts, center, radius); } } #endif
4,918
C
44.12844
151
0.748272
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/SnippetKinematicSoftBody.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_KINEMATIC_SOFTBODY_H #define PHYSX_SNIPPET_KINEMATIC_SOFTBODY_H #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #include <vector> class SoftBody { public: SoftBody(physx::PxSoftBody* softBody, physx::PxCudaContextManager* cudaContextManager) : mSoftBody(softBody), mCudaContextManager(cudaContextManager) { mPositionsInvMass = PX_PINNED_HOST_ALLOC_T(physx::PxVec4, cudaContextManager, softBody->getCollisionMesh()->getNbVertices()); } ~SoftBody() { } void release() { if (mSoftBody) mSoftBody->release(); if (mPositionsInvMass) PX_PINNED_HOST_FREE(mCudaContextManager, mPositionsInvMass); if (mTargetPositionsH) PX_PINNED_HOST_FREE(mCudaContextManager, mTargetPositionsH); if (mTargetPositionsD) PX_DEVICE_FREE(mCudaContextManager, mTargetPositionsD); } void copyDeformedVerticesFromGPUAsync(CUstream stream) { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoHAsync(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4), stream); } void copyDeformedVerticesFromGPU() { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoH(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4)); } physx::PxVec4* mPositionsInvMass; physx::PxSoftBody* mSoftBody; physx::PxCudaContextManager* mCudaContextManager; physx::PxVec4* mTargetPositionsH; physx::PxVec4* mTargetPositionsD; physx::PxU32 mTargetCount; }; #endif
3,563
C
38.164835
205
0.774909
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgeometryquery/SnippetGeometryQuery.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. // **************************************************************************** // This snippet illustrates how to use a PxGeometryQuery for raycasts. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; enum Geom { GEOM_BOX, GEOM_SPHERE, GEOM_CAPSULE, GEOM_CONVEX, GEOM_MESH, GEOM_COUNT }; static const PxU32 gScenarioCount = GEOM_COUNT; static PxU32 gScenario = 0; static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static PxBoxGeometry gBoxGeom(PxVec3(1.0f, 2.0f, 0.5f)); static PxSphereGeometry gSphereGeom(1.5f); static PxCapsuleGeometry gCapsuleGeom(1.0f, 1.0f); static PxConvexMeshGeometry gConvexGeom; static PxTriangleMeshGeometry gMeshGeom; const PxGeometry& getTestGeometry() { switch(gScenario) { case GEOM_BOX: return gBoxGeom; case GEOM_SPHERE: return gSphereGeom; case GEOM_CAPSULE: return gCapsuleGeom; case GEOM_CONVEX: gConvexGeom.convexMesh = gConvexMesh; return gConvexGeom; case GEOM_MESH: gMeshGeom.triangleMesh = gTriangleMesh; gMeshGeom.scale.scale = PxVec3(2.0f); return gMeshGeom; } static PxSphereGeometry pt(0.0f); return pt; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetGeometryQuery done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F5 to select a geometry object."); #endif } int snippetMain(int, const char*const*) { printf("GeometryQuery snippet. Use these keys:\n"); printf(" F1 to F5 - select different geom\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
6,102
C++
27.787736
111
0.727466
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgeometryquery/SnippetGeometryQueryRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern const PxGeometry& getTestGeometry(); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); static float time = 0.0f; time += 0.003f; const PxQuat qx = PxGetRotXQuat(time); const PxQuat qy = PxGetRotYQuat(time*1.7f); const PxQuat qz = PxGetRotZQuat(time*1.33f); const PxTransform pose(PxVec3(0.0f), qx*qy*qz); Snippets::startRender(sCamera); const PxGeometry& geom = getTestGeometry(); const PxU32 screenWidth = Snippets::getScreenWidth(); const PxU32 screenHeight = Snippets::getScreenHeight(); const PxVec3 camPos = sCamera->getEye(); const PxVec3 camDir = sCamera->getDir(); const PxU32 RAYTRACING_RENDER_WIDTH = 256; const PxU32 RAYTRACING_RENDER_HEIGHT = 256; const PxU32 textureWidth = RAYTRACING_RENDER_WIDTH; const PxU32 textureHeight = RAYTRACING_RENDER_HEIGHT; GLubyte* pixels = new GLubyte[textureWidth*textureHeight*4]; const float fScreenWidth = float(screenWidth)/float(RAYTRACING_RENDER_WIDTH); const float fScreenHeight = float(screenHeight)/float(RAYTRACING_RENDER_HEIGHT); GLubyte* buffer = pixels; for(PxU32 j=0;j<RAYTRACING_RENDER_HEIGHT;j++) { const PxU32 yi = PxU32(fScreenHeight*float(j)); for(PxU32 i=0;i<RAYTRACING_RENDER_WIDTH;i++) { const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = Snippets::computeWorldRay(xi, yi, camDir); PxGeomRaycastHit hit; if(PxGeometryQuery::raycast(camPos, dir, geom, pose, 5000.0f, PxHitFlag::eDEFAULT, 1, &hit)) { buffer[0] = 128+GLubyte(hit.normal.x*127.0f); buffer[1] = 128+GLubyte(hit.normal.y*127.0f); buffer[2] = 128+GLubyte(hit.normal.z*127.0f); buffer[3] = 255; } else { buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 255; } buffer+=4; } } const GLuint texID = Snippets::CreateTexture(textureWidth, textureHeight, pixels, false); Snippets::DisplayTexture(texID, RAYTRACING_RENDER_WIDTH, 10); delete [] pixels; Snippets::ReleaseTexture(texID); // Snippets::DrawRectangle(0.0f, 1.0f, 0.0f, 1.0f, PxVec3(0.0f), PxVec3(1.0f), 1.0f, 768, 768, false, false); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); const PxVec3 color(1.0f, 0.5f, 0.25f); const PxGeometryHolder gh(geom); Snippets::renderGeoms(1, &gh, &pose, false, color); renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet GeometryQuery", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
5,000
C++
31.686274
117
0.73
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcontactreportccd/SnippetContactReportCCD.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. // **************************************************************************** // This snippet illustrates the use of simple contact reports in combination // with continuous collision detection (CCD). Furthermore, extra contact report // data will be requested. // // The snippet defines a filter shader function that enables CCD and requests // touch reports for all pairs, and a contact callback function that saves the // contact points and the actor positions at time of impact. // It configures the scene to use this filter and callback, enables CCD and // prints the number of contact points found. If rendering, it renders each // contact as a line whose length and direction are defined by the contact // impulse (the line points in the opposite direction of the impulse). In // addition, the path of the fast moving dynamic object is drawn with lines. // // **************************************************************************** #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static PxRigidStatic* gTriangleMeshActor = NULL; static PxRigidDynamic* gSphereActor = NULL; static PxPvd* gPvd = NULL; static PxU32 gSimStepCount = 0; std::vector<PxVec3> gContactPositions; std::vector<PxVec3> gContactImpulses; std::vector<PxVec3> gContactSphereActorPositions; static PxFilterFlags contactReportFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(filterData0); PX_UNUSED(filterData1); PX_UNUSED(constantBlockSize); PX_UNUSED(constantBlock); // // Enable CCD for the pair, request contact reports for initial and CCD contacts. // Additionally, provide information per contact point and provide the actor // pose at the time of contact. // pairFlags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT | PxPairFlag::eNOTIFY_TOUCH_CCD | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::eCONTACT_EVENT_POSE; return PxFilterFlag::eDEFAULT; } class ContactReportCallback: public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) { PX_UNUSED(constraints); PX_UNUSED(count); } void onWake(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onSleep(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onTrigger(PxTriggerPair* pairs, PxU32 count) { PX_UNUSED(pairs); PX_UNUSED(count); } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) {} void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) { std::vector<PxContactPairPoint> contactPoints; PxTransform spherePose(PxIdentity); PxU32 nextPairIndex = 0xffffffff; PxContactPairExtraDataIterator iter(pairHeader.extraDataStream, pairHeader.extraDataStreamSize); bool hasItemSet = iter.nextItemSet(); if (hasItemSet) nextPairIndex = iter.contactPairIndex; for(PxU32 i=0; i < nbPairs; i++) { // // Get the pose of the dynamic object at time of impact. // if (nextPairIndex == i) { if (pairHeader.actors[0]->is<PxRigidDynamic>()) spherePose = iter.eventPose->globalPose[0]; else spherePose = iter.eventPose->globalPose[1]; gContactSphereActorPositions.push_back(spherePose.p); hasItemSet = iter.nextItemSet(); if (hasItemSet) nextPairIndex = iter.contactPairIndex; } // // Get the contact points for the pair. // const PxContactPair& cPair = pairs[i]; if (cPair.events & (PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_CCD)) { PxU32 contactCount = cPair.contactCount; contactPoints.resize(contactCount); cPair.extractContacts(&contactPoints[0], contactCount); for(PxU32 j=0; j < contactCount; j++) { gContactPositions.push_back(contactPoints[j].position); gContactImpulses.push_back(contactPoints[j].impulse); } } } } }; ContactReportCallback gContactReportCallback; static void initScene() { // // Create a static triangle mesh // PxVec3 vertices[] = { PxVec3(-8.0f, 0.0f, -3.0f), PxVec3(-8.0f, 0.0f, 3.0f), PxVec3(0.0f, 0.0f, 3.0f), PxVec3(0.0f, 0.0f, -3.0f), PxVec3(-8.0f, 10.0f, -3.0f), PxVec3(-8.0f, 10.0f, 3.0f), PxVec3(0.0f, 10.0f, 3.0f), PxVec3(0.0f, 10.0f, -3.0f), }; PxU32 vertexCount = sizeof(vertices) / sizeof(vertices[0]); PxU32 triangleIndices[] = { 0, 1, 2, 0, 2, 3, 0, 5, 1, 0, 4, 5, 4, 6, 5, 4, 7, 6 }; PxU32 triangleCount = (sizeof(triangleIndices) / sizeof(triangleIndices[0])) / 3; PxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.points.count = vertexCount; triangleMeshDesc.points.data = vertices; triangleMeshDesc.points.stride = sizeof(PxVec3); triangleMeshDesc.triangles.count = triangleCount; triangleMeshDesc.triangles.data = triangleIndices; triangleMeshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale tolerances; const PxCookingParams params(tolerances); gTriangleMesh = PxCreateTriangleMesh(params, triangleMeshDesc, gPhysics->getPhysicsInsertionCallback()); if (!gTriangleMesh) return; gTriangleMeshActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0.0f, 1.0f, 0.0f), PxQuat(PxHalfPi / 60.0f, PxVec3(0.0f, 1.0f, 0.0f)))); if (!gTriangleMeshActor) return; PxTriangleMeshGeometry triGeom(gTriangleMesh); PxShape* triangleMeshShape = PxRigidActorExt::createExclusiveShape(*gTriangleMeshActor, triGeom, *gMaterial); if (!triangleMeshShape) return; gScene->addActor(*gTriangleMeshActor); // // Create a fast moving sphere that will hit and bounce off the static triangle mesh 3 times // in one simulation step. // PxTransform spherePose(PxVec3(0.0f, 5.0f, 1.0f)); gContactSphereActorPositions.push_back(spherePose.p); gSphereActor = gPhysics->createRigidDynamic(spherePose); gSphereActor->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if (!gSphereActor) return; PxSphereGeometry sphereGeom(1.0f); PxShape* sphereShape = PxRigidActorExt::createExclusiveShape(*gSphereActor, sphereGeom, *gMaterial); if (!sphereShape) return; PxRigidBodyExt::updateMassAndInertia(*gSphereActor, 1.0f); PxReal velMagn = 900.0f; PxVec3 vel = PxVec3(-1.0f, -1.0f, 0.0f); vel.normalize(); vel *= velMagn; gSphereActor->setLinearVelocity(vel); gScene->addActor(*gSphereActor); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, 0, 0); sceneDesc.filterShader = contactReportFilterShader; sceneDesc.simulationEventCallback = &gContactReportCallback; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; sceneDesc.ccdMaxPasses = 4; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 1.0f); initScene(); } void stepPhysics(bool /*interactive*/) { if (!gSimStepCount) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); printf("%d contact points\n", PxU32(gContactPositions.size())); if (gSphereActor) gContactSphereActorPositions.push_back(gSphereActor->getGlobalPose().p); gSimStepCount = 1; } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gSphereActor); PX_RELEASE(gTriangleMeshActor); PX_RELEASE(gTriangleMesh); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetContactReportCCD done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,959
C++
32.723077
141
0.726709
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcontactreportccd/SnippetContactReportCCDRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern std::vector<PxVec3> gContactPositions; extern std::vector<PxVec3> gContactImpulses; extern std::vector<PxVec3> gContactSphereActorPositions; std::vector<PxVec3> gContactVertices; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } if(gContactPositions.size()) { gContactVertices.clear(); for(PxU32 i=0; i < gContactPositions.size(); i++) { gContactVertices.push_back(gContactPositions[i]); gContactVertices.push_back(gContactPositions[i]-gContactImpulses[i]*0.0001f); } glDisable(GL_LIGHTING); glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(gContactVertices.size())); glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_LIGHTING); } if(gContactSphereActorPositions.size()) { gContactVertices.clear(); for(PxU32 i=0; i < gContactSphereActorPositions.size() - 1; i++) { gContactVertices.push_back(gContactSphereActorPositions[i]); gContactVertices.push_back(gContactSphereActorPositions[i+1]); } glDisable(GL_LIGHTING); glColor4f(1.0f, 1.0f, 0.0f, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(gContactVertices.size())); glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_LIGHTING); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.5f, 6.0f, 14.0f), PxVec3(-0.1f,0.0f,-0.7f)); Snippets::setupDefault("PhysX Snippet ContactReport CCD", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
4,236
C++
33.729508
136
0.753069
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgearjoint/SnippetGearJointRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); /* if(0) { PxVec3 camPos = sCamera->getEye(); PxVec3 camDir = sCamera->getDir(); printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); }*/ Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(7.401237f, 11.224086f, 15.145986f), PxVec3(-0.315603f, -0.041489f, -0.947984f)); Snippets::setupDefault("PhysX Snippet GearJoint", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,246
C++
33.542553
136
0.745533
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgearjoint/SnippetGearJoint.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. // **************************************************************************** // This snippet illustrates simple use of gear joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createGearWithBoxes(PxPhysics& sdk, const PxBoxGeometry& boxGeom, const PxTransform& transform, PxMaterial& material, int nbShapes) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); PxMat33 m(PxIdentity); for(int i=0;i<nbShapes;i++) { const float coeff = float(i)/float(nbShapes); const float angle = PxPi * 0.5f * coeff; PxShape* shape = sdk.createShape(boxGeom, material, true); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); shape->setLocalPose(localPose); actor->attachShape(*shape); } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRevoluteJoint* gHinge0 = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); const float velocityTarget = 0.5f; const float radius0 = 5.0f; const float radius1 = 2.0f; const float extent0 = radius0 * sqrtf(2.0f); const float extent1 = radius1 * sqrtf(2.0f); const float teethLength0 = extent0 - radius0; const float teethLength1 = extent1 - radius1; const float extra = (teethLength0 + teethLength1)*0.75f; const PxBoxGeometry boxGeom0(radius0, radius0, 0.5f); const PxBoxGeometry boxGeom1(radius1, radius1, 0.25f); const PxVec3 boxPos0(0.0f, 10.0f, 0.0f); const PxVec3 boxPos1(radius0+radius1+extra, 10.0f, 0.0f); PxRigidDynamic* actor0 = createGearWithBoxes(*gPhysics, boxGeom0, PxTransform(boxPos0), *gMaterial, int(radius0)); gScene->addActor(*actor0); PxRigidDynamic* actor1= createGearWithBoxes(*gPhysics, boxGeom1, PxTransform(boxPos1), *gMaterial, int(radius1)); gScene->addActor(*actor1); const PxQuat x2z = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f)); PxRevoluteJoint* hinge0 = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos0, x2z), actor0, PxTransform(PxVec3(0.0f), x2z)); PxRevoluteJoint* hinge1 = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos1, x2z), actor1, PxTransform(PxVec3(0.0f), x2z)); hinge0->setDriveVelocity(velocityTarget); hinge0->setRevoluteJointFlag(PxRevoluteJointFlag::eDRIVE_ENABLED, true); gHinge0 = hinge0; PxGearJoint* gearJoint = PxGearJointCreate(*gPhysics, actor0, PxTransform(PxVec3(0.0f), x2z), actor1, PxTransform(PxVec3(0.0f), x2z)); gearJoint->setHinges(hinge0, hinge1); const float ratio = radius0/radius1; gearJoint->setGearRatio(ratio); } void stepPhysics(bool /*interactive*/) { if(0) { static float globalTime = 0.0f; globalTime += 1.0f/60.0f; const float velocityTarget = sinf(globalTime)*3.0f; gHinge0->setDriveVelocity(velocityTarget); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGearJoint done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
6,835
C++
33.877551
154
0.732114
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2directdrive/SnippetVehicleDirectDrive.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. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a vehicle with direct drive using parameters, states and // components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a direct drive drivetrain model that forwards input controls to wheel torques and angles. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with direct drivetrain DirectDriveVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "directDrive"; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxF32 duration; }; Command gCommands[] = { {0.5f, 0.0f, 0.0f, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.5f, 0.0f, 5.0f}, //throttle for 5 seconds {0.5f, 0.0f, 0.0f, 5.0f}, //brake for 5 seconds {0.0f, 0.5f, 0.0f, 5.0f}, //throttle for 5 seconds {0.0f, 0.1f, 0.5f, 5.0f} //light throttle and steer for 5 seconds. }; const PxU32 gNbCommands = sizeof(gCommands)/sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", gVehicle.mBaseParams.axleDescription, gVehicle.mDirectDriveParams); //Set the states to default. if (!gVehicle.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial)) { return false; } gVehicle.mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eFORWARD; //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(-5.0f, 0.5f, 0.0f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if(gNbCommands == gCommandProgress) return; const PxF32 timestep = 0.0166667f; //Apply the brake, throttle and steer to the command state of the direct drive vehicle. const Command& command = gCommands[gCommandProgress]; gVehicle.mCommandState.brakes[0] = command.brake; gVehicle.mCommandState.nbBrakes = 1; gVehicle.mCommandState.throttle = command.throttle; gVehicle.mCommandState.steer = command.steer; //Forward integrate the vehicle by a single timestep. gVehicle.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if(gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if(!parseVehicleDataPath(argc, argv, "SnippetVehicle2DirectDrive", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. DirectDrivetrainParams directDrivetrainParams; if (!readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if(initPhysics()) { while(gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
13,571
C++
37.338983
127
0.763466
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbf/SnippetPBFRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #define CUDA_SUCCESS 0 #define SHOW_SOLID_SDF_SLICE 0 #define IDX(i, j, k, offset) ((i) + dimX * ((j) + dimY * ((k) + dimZ * (offset)))) using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxPBDParticleSystem* getParticleSystem(); extern PxParticleAndDiffuseBuffer* getParticleBuffer(); extern int getNumDiffuseParticles(); namespace { Snippets::Camera* sCamera; Snippets::SharedGLBuffer sPosBuffer; Snippets::SharedGLBuffer sDiffusePosLifeBuffer; void onBeforeRenderParticles() { } void renderParticles() { PxPBDParticleSystem* particleSystem = getParticleSystem(); if (particleSystem) { PxParticleAndDiffuseBuffer* userBuffer = getParticleBuffer(); PxVec4* positions = userBuffer->getPositionInvMasses(); PxVec4* diffusePositions = userBuffer->getDiffusePositionLifeTime(); const PxU32 numParticles = userBuffer->getNbActiveParticles(); const PxU32 numDiffuseParticles = userBuffer->getNbActiveDiffuseParticles(); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); cudaContextManager->acquireContext(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyDtoH(sPosBuffer.map(), CUdeviceptr(positions), sizeof(PxVec4) * numParticles); cudaContext->memcpyDtoH(sDiffusePosLifeBuffer.map(), CUdeviceptr(diffusePositions), sizeof(PxVec4) * numDiffuseParticles); cudaContextManager->releaseContext(); #if SHOW_SOLID_SDF_SLICE particleSystem->copySparseGridData(sSparseGridSolidSDFBufferD, PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF); #endif } sPosBuffer.unmap(); sDiffusePosLifeBuffer.unmap(); PxVec3 color(0.5f, 0.5f, 1); Snippets::DrawPoints(sPosBuffer.vbo, sPosBuffer.size / sizeof(PxVec4), color, 2.f); PxParticleAndDiffuseBuffer* userBuffer = getParticleBuffer(); const PxU32 numActiveDiffuseParticles = userBuffer->getNbActiveDiffuseParticles(); //printf("NumActiveDiffuse = %i\n", numActiveDiffuseParticles); if (numActiveDiffuseParticles > 0) { PxVec3 colorDiffuseParticles(1, 1, 1); Snippets::DrawPoints(sDiffusePosLifeBuffer.vbo, numActiveDiffuseParticles, colorDiffuseParticles, 2.f); } Snippets::DrawFrame(PxVec3(0, 0, 0)); } void allocParticleBuffers() { PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); PxParticleAndDiffuseBuffer* userBuffer = getParticleBuffer(); const PxU32 maxParticles = userBuffer->getMaxParticles(); const PxU32 maxDiffuseParticles = userBuffer->getMaxDiffuseParticles(); sDiffusePosLifeBuffer.initialize(cudaContextManager); sDiffusePosLifeBuffer.allocate(maxDiffuseParticles * sizeof(PxVec4)); sPosBuffer.initialize(cudaContextManager); sPosBuffer.allocate(maxParticles * sizeof(PxVec4)); } void clearupParticleBuffers() { sPosBuffer.release(); sDiffusePosLifeBuffer.release(); } void renderCallback() { onBeforeRenderParticles(); stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } renderParticles(); Snippets::showFPS(); Snippets::finishRender(); } void cleanup() { delete sCamera; clearupParticleBuffers(); cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(15.0f, 10.0f, 15.0f), PxVec3(-0.6f,-0.2f,-0.6f)); Snippets::setupDefault("PhysX Snippet PBFFluid", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); Snippets::initFPS(); allocParticleBuffers(); glutMainLoop(); cleanup(); } #endif
6,088
C++
30.549223
136
0.771189
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbf/SnippetPBF.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. // **************************************************************************** // This snippet illustrates fluid simulation using position-based dynamics // particle simulation. It creates a container and drops a body of water. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxParticleExt.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleAndDiffuseBuffer* gParticleBuffer = NULL; static bool gIsRunning = true; static bool gStep = true; PxRigidDynamic* movingWall; static void initObstacles() { PxShape* shape = gPhysics->createShape(PxCapsuleGeometry(1.0f, 2.5f), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(3.5f, 3.5f, 0), PxQuat(PxPi*-0.5f, PxVec3(0, 0, 1)))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); shape = gPhysics->createShape(PxBoxGeometry(1.0f, 1.0f, 5.0f), *gMaterial); body = gPhysics->createRigidDynamic(PxTransform(PxVec3(3.5f, 0.75f, 0))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); } static int gMaxDiffuseParticles = 0; // ----------------------------------------------------------------------------------------------------------------- static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); } int getNumDiffuseParticles() { return gMaxDiffuseParticles; } // ----------------------------------------------------------------------------------------------------------------- static void initParticles(const PxU32 numX, const PxU32 numY, const PxU32 numZ, const PxVec3& position = PxVec3(0, 0, 0), const PxReal particleSpacing = 0.2f, const PxReal fluidDensity = 1000.f, const PxU32 maxDiffuseParticles = 100000) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; const PxU32 maxParticles = numX * numY * numZ; const PxReal restOffset = 0.5f * particleSpacing / 0.6f; // Material setup PxPBDMaterial* defaultMat = gPhysics->createPBDMaterial(0.05f, 0.05f, 0.f, 0.001f, 0.5f, 0.005f, 0.01f, 0.f, 0.f); defaultMat->setViscosity(0.001f); defaultMat->setSurfaceTension(0.00704f); defaultMat->setCohesion(0.0704f); defaultMat->setVorticityConfinement(10.f); PxPBDParticleSystem *particleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager, 96); gParticleSystem = particleSystem; // General particle system setting const PxReal solidRestOffset = restOffset; const PxReal fluidRestOffset = restOffset * 0.6f; const PxReal particleMass = fluidDensity * 1.333f * 3.14159f * particleSpacing * particleSpacing * particleSpacing; particleSystem->setRestOffset(restOffset); particleSystem->setContactOffset(restOffset + 0.01f); particleSystem->setParticleContactOffset(fluidRestOffset / 0.6f); particleSystem->setSolidRestOffset(solidRestOffset); particleSystem->setFluidRestOffset(fluidRestOffset); particleSystem->enableCCD(false); particleSystem->setMaxVelocity(solidRestOffset*100.f); gScene->addActor(*particleSystem); // Diffuse particles setting PxDiffuseParticleParams dpParams; dpParams.threshold = 300.0f; dpParams.bubbleDrag = 0.9f; dpParams.buoyancy = 0.9f; dpParams.airDrag = 0.0f; dpParams.kineticEnergyWeight = 0.01f; dpParams.pressureWeight = 1.0f; dpParams.divergenceWeight = 10.f; dpParams.lifetime = 1.0f; dpParams.useAccurateVelocity = false; gMaxDiffuseParticles = maxDiffuseParticles; // Create particles and add them to the particle system const PxU32 particlePhase = particleSystem->createPhase(defaultMat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseFluid | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); PxU32* phase = cudaContextManager->allocPinnedHostBuffer<PxU32>(maxParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxReal x = position.x; PxReal y = position.y; PxReal z = position.z; for (PxU32 i = 0; i < numX; ++i) { for (PxU32 j = 0; j < numY; ++j) { for (PxU32 k = 0; k < numZ; ++k) { const PxU32 index = i * (numY * numZ) + j * numZ + k; PxVec4 pos(x, y, z, 1.0f / particleMass); phase[index] = particlePhase; positionInvMass[index] = pos; velocity[index] = PxVec4(0.0f); z += particleSpacing; } z = position.z; y += particleSpacing; } y = position.y; x += particleSpacing; } ExtGpu::PxParticleAndDiffuseBufferDesc bufferDesc; bufferDesc.maxParticles = maxParticles; bufferDesc.numActiveParticles = maxParticles; bufferDesc.maxDiffuseParticles = maxDiffuseParticles; bufferDesc.maxActiveDiffuseParticles = maxDiffuseParticles; bufferDesc.diffuseParams = dpParams; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phase; gParticleBuffer = physx::ExtGpu::PxCreateAndPopulateParticleAndDiffuseBuffer(bufferDesc, cudaContextManager); gParticleSystem->addParticleBuffer(gParticleBuffer); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phase); } PxPBDParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleAndDiffuseBuffer* getParticleBuffer() { return gParticleBuffer; } // ----------------------------------------------------------------------------------------------------------------- void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup PBF bool useLargeFluid = true; bool useMovingWall = true; const PxReal fluidDensity = 1000.0f; const PxU32 maxDiffuseParticles = useLargeFluid ? 2000000 : 100000; initParticles(50, 120 * (useLargeFluid ? 5 : 1), 30, PxVec3(-2.5f, 3.f, 0.5f), 0.1f, fluidDensity, maxDiffuseParticles); initObstacles(); // Setup container gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.0f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(-1.f, 0.f, 0.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, 1.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, -1.f, 7.5f), *gMaterial)); if (!useMovingWall) { gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(1.f, 0.f, 0.f, 7.5f), *gMaterial)); movingWall = NULL; } else { PxTransform trans = PxTransformFromPlaneEquation(PxPlane(1.f, 0.f, 0.f, 5.f)); movingWall = gPhysics->createRigidDynamic(trans); movingWall->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); PxRigidActorExt::createExclusiveShape(*movingWall, PxPlaneGeometry(), *gMaterial); gScene->addActor(*movingWall); } // Setup rigid bodies const PxReal dynamicsDensity = fluidDensity * 0.5f; const PxReal boxSize = 1.0f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 3.0f, 10, 7.5f))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } // --------------------------------------------------- void stepPhysics(bool /*interactive*/) { if (gIsRunning || gStep) { gStep = false; const PxReal dt = 1.0f / 60.0f; if (movingWall) { static bool moveOut = false; const PxReal speed = 3.0f; PxTransform pose = movingWall->getGlobalPose(); if (moveOut) { pose.p.x += dt * speed; if (pose.p.x > -7.f) moveOut = false; } else { pose.p.x -= dt * speed; if (pose.p.x < -15.f) moveOut = true; } movingWall->setKinematicTarget(pose); } gScene->simulate(dt); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBFFluid done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; case 'O': gIsRunning = false; gStep = true; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,993
C++
33.466843
236
0.712999
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpointdistancequery/SnippetPointDistanceQueryRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern const PxGeometry& getTestGeometry(); extern PxU32 getNbPoints(); extern PxVec3 getPoint(PxU32 i); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); const PxVec3 color(1.0f, 0.5f, 0.25f); const PxGeometry& geom = getTestGeometry(); const PxGeometryHolder gh(geom); static float time = 0.0f; time += 0.003f; const PxQuat qx = PxGetRotXQuat(time); const PxQuat qy = PxGetRotYQuat(time*1.7f); const PxQuat qz = PxGetRotZQuat(time*1.33f); const PxTransform pose(PxVec3(0.0f), qx*qy*qz); Snippets::renderGeoms(1, &gh, &pose, false, color); const PxVec3 lineColor(1.0f); const PxU32 nbQueries = getNbPoints(); for(PxU32 i=0;i<nbQueries;i++) { const PxVec3 pt = getPoint(i); PxVec3 cp; float d2 = PxGeometryQuery::pointDistance(pt, geom, pose, &cp); (void)d2; Snippets::DrawLine(pt, cp, lineColor); Snippets::DrawFrame(pt, 0.1f); Snippets::DrawFrame(cp, 0.1f); } renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet PointDistanceQuery", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,712
C++
30.735042
117
0.738685
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpointdistancequery/SnippetPointDistanceQuery.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. // **************************************************************************** // This snippet illustrates how to use the point-distance geometry query. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; enum Geom { GEOM_BOX, GEOM_SPHERE, GEOM_CAPSULE, GEOM_CONVEX, GEOM_MESH, GEOM_COUNT }; static const PxU32 gScenarioCount = GEOM_COUNT; static PxU32 gScenario = 0; enum Mode { MODE_SINGLE, MODE_MULTI_2D, MODE_MULTI_3D, MODE_COUNT }; static PxU32 gMode = MODE_SINGLE; PxU32 getNbPoints() { return gMode==MODE_SINGLE ? 1 : 1024; } static SnippetUtils::BasicRandom rnd(42); PxVec3 getPoint(PxU32) { PxVec3 dir = rnd.unitRandomPt(); if(gMode==MODE_MULTI_2D) { dir.z = 0.0f; dir.normalize(); } return dir*3.0f; } static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static PxBoxGeometry gBoxGeom(PxVec3(1.0f, 2.0f, 0.5f)); static PxSphereGeometry gSphereGeom(1.5f); static PxCapsuleGeometry gCapsuleGeom(1.0f, 1.0f); static PxConvexMeshGeometry gConvexGeom; static PxTriangleMeshGeometry gMeshGeom; const PxGeometry& getTestGeometry() { switch(gScenario) { case GEOM_BOX: return gBoxGeom; case GEOM_SPHERE: return gSphereGeom; case GEOM_CAPSULE: return gCapsuleGeom; case GEOM_CONVEX: gConvexGeom.convexMesh = gConvexMesh; return gConvexGeom; case GEOM_MESH: gMeshGeom.triangleMesh = gTriangleMesh; gMeshGeom.scale.scale = PxVec3(2.0f); return gMeshGeom; } static PxSphereGeometry pt(0.0f); return pt; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); { gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } } initScene(); } void stepPhysics(bool /*interactive*/) { rnd.setSeed(42); } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetPointDistanceQuery done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == gScenarioCount+1) { gMode++; if(gMode==MODE_COUNT) gMode = 0; } if(key == 'r' || key == 'R') { releaseScene(); initScene(); } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F5 to select a geometry object."); Snippets::print("Press F6 to select different test queries."); #endif } int snippetMain(int, const char*const*) { printf("Point-distance query snippet. Use these keys:\n"); printf(" F1 to F5 - select different geom\n"); printf(" F6 - select different test queries\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
6,713
C++
25.537549
111
0.720393
NVIDIA-Omniverse/PhysX/physx/snippets/snippethelloworld/SnippetHelloWorld.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. // **************************************************************************** // This snippet illustrates simple use of physx // // It creates a number of box stacks on a plane, and if rendering, allows the // user to create new stacks and fire a ball from the camera position // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxReal stackZ = 10.0f; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool interactive) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<5;i++) createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); if(!interactive) createDynamic(PxTransform(PxVec3(0,40,100)), PxSphereGeometry(10), PxVec3(0,-50,-100)); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetHelloWorld done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case 'B': createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); break; case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
5,851
C++
34.90184
120
0.728764
NVIDIA-Omniverse/PhysX/physx/snippets/snippethelloworld/SnippetHelloWorldRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet HelloWorld", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,003
C++
34.341176
136
0.759574
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsdf/SnippetSDFRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 rcaColor(0.6f*0.75f, 0.8f*0.75f, 1.0f*0.75f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } Snippets::showFPS(); Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(5.0f, 5.0f, 5.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet SDF", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); Snippets::initFPS(); glutMainLoop(); cleanup(); } #endif
3,115
C++
31.458333
136
0.750241
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsdf/MeshGenerator.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_MESHGENERATOR_H #define PHYSX_MESHGENERATOR_H #include "PxPhysicsAPI.h" #include "extensions/PxRemeshingExt.h" namespace meshgenerator { using namespace physx; void createCube(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& pos, PxReal scaling) { triVerts.clear(); triIndices.clear(); triVerts.pushBack(scaling * PxVec3(0.5f, -0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, -0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, -0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, -0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, 0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, 0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, 0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, 0.5f, -0.5f) + pos); triIndices.pushBack(1); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(6); triIndices.pushBack(5); triIndices.pushBack(4); triIndices.pushBack(5); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(6); triIndices.pushBack(2); triIndices.pushBack(2); triIndices.pushBack(6); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(1); triIndices.pushBack(3); triIndices.pushBack(4); triIndices.pushBack(7); triIndices.pushBack(5); triIndices.pushBack(0); triIndices.pushBack(4); triIndices.pushBack(1); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(2); triIndices.pushBack(7); triIndices.pushBack(4); triIndices.pushBack(0); triIndices.pushBack(7); } void createConeY(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, PxReal height, PxU32 numPointsOnRing = 32) { triVerts.clear(); triIndices.clear(); for (PxU32 i = 0; i < numPointsOnRing; ++i) { PxReal angle = i * 2.0f * 3.1415926535898f / numPointsOnRing; triVerts.pushBack(center + radius * PxVec3(PxSin(angle), 0, PxCos(angle))); } triVerts.pushBack(center); triVerts.pushBack(center + PxVec3(0, height, 0)); for (PxU32 i = 0; i < numPointsOnRing; ++i) { triIndices.pushBack(numPointsOnRing); triIndices.pushBack(i); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(numPointsOnRing + 1); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(i); } } void projectPointsOntoSphere(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); triVerts[i] = center + radius * dir; } } void projectPointsOntoBowl(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); if (dir.y > 0.01f) { dir.x *= 0.9f; dir.z *= 0.9f; dir.y = -dir.y; } triVerts[i] = center + radius * dir; } } void createBowl(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, const PxReal maxEdgeLength) { triVerts.clear(); triIndices.clear(); createCube(triVerts, triIndices, center, radius); projectPointsOntoSphere(triVerts, center, radius); while (PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 1)) projectPointsOntoSphere(triVerts, center, radius); projectPointsOntoBowl(triVerts, center, radius); } } #endif
5,222
C
39.176923
151
0.734393
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsdf/SnippetSDF.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. // **************************************************************************** // This snippet demonstrates how to setup triangle meshes with SDFs. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsdf/MeshGenerator.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxTriangleMesh* createMesh(PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, PxReal sdfSpacing, PxU32 sdfSubgridSize = 6, PxSdfBitsPerSubgridPixel::Enum bitsPerSdfSubgridPixel = PxSdfBitsPerSubgridPixel::e16_BIT_PER_PIXEL) { PxTriangleMeshDesc meshDesc; meshDesc.points.count = triVerts.size(); meshDesc.triangles.count = triIndices.size() / 3; meshDesc.points.stride = sizeof(float) * 3; meshDesc.triangles.stride = sizeof(int) * 3; meshDesc.points.data = triVerts.begin(); meshDesc.triangles.data = triIndices.begin(); params.meshPreprocessParams |= PxMeshPreprocessingFlag::eENABLE_INERTIA; params.meshWeldTolerance = 1e-7f; PxSDFDesc sdfDesc; if (sdfSpacing > 0.f) { sdfDesc.spacing = sdfSpacing; sdfDesc.subgridSize = sdfSubgridSize; sdfDesc.bitsPerSubgridPixel = bitsPerSdfSubgridPixel; sdfDesc.numThreadsForSdfConstruction = 16; meshDesc.sdfDesc = &sdfDesc; } bool enableCaching = false; if (enableCaching) { const char* path = "C:\\tmp\\PhysXSDFSnippetData.dat"; bool ok = false; FILE* fp = fopen(path, "rb"); if (fp) { fclose(fp); ok = true; } if (!ok) { PxDefaultFileOutputStream stream(path); ok = PxCookTriangleMesh(params, meshDesc, stream); } if (ok) { PxDefaultFileInputData stream(path); PxTriangleMesh* triangleMesh = gPhysics->createTriangleMesh(stream); return triangleMesh; } return NULL; } else return PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } static void addInstance(const PxTransform& transform, PxTriangleMesh* mesh) { PxRigidDynamic* dyn = gPhysics->createRigidDynamic(transform); dyn->setLinearDamping(0.2f); dyn->setAngularDamping(0.1f); PxTriangleMeshGeometry geom; geom.triangleMesh = mesh; geom.scale = PxVec3(0.1f, 0.1f, 0.1f); dyn->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES, true); dyn->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*dyn, geom, *gMaterial); shape->setContactOffset(0.05f); shape->setRestOffset(0.0f); PxRigidBodyExt::updateMassAndInertia(*dyn, 100.f); gScene->addActor(*dyn); dyn->setWakeCounter(100000000.f); dyn->setSolverIterationCounts(50, 1); dyn->setMaxDepenetrationVelocity(5.f); } static void createBowls(PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createBowl(triVerts, triIndices, PxVec3(0, 4.5, 0), 6.0f, maxEdgeLength); PxTriangleMesh* mesh = createMesh(params, triVerts, triIndices, 0.05f); PxQuat rotate(PxIdentity); const PxU32 numInstances = 200; for (PxU32 i = 0; i < numInstances; ++i) { PxTransform transform(PxVec3(0, 5.f + i * 0.5f, 0), rotate); addInstance(transform, mesh); } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createBowls(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet SDF done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
8,420
C++
31.639535
145
0.745012
NVIDIA-Omniverse/PhysX/physx/snippets/snippettriggers/SnippetTriggers.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. // **************************************************************************** // This snippet illustrates the use of built-in triggers, and how to emulate // them with regular shapes if you need CCD or trigger-trigger notifications. // // **************************************************************************** #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; enum TriggerImpl { // Uses built-in triggers (PxShapeFlag::eTRIGGER_SHAPE). REAL_TRIGGERS, // Emulates triggers using a filter shader. Needs one reserved value in PxFilterData. FILTER_SHADER, // Emulates triggers using a filter callback. Doesn't use PxFilterData but needs user-defined way to mark a shape as a trigger. FILTER_CALLBACK, }; struct ScenarioData { TriggerImpl mImpl; bool mCCD; bool mTriggerTrigger; }; #define SCENARIO_COUNT 9 static ScenarioData gData[SCENARIO_COUNT] = { {REAL_TRIGGERS, false, false}, {FILTER_SHADER, false, false}, {FILTER_CALLBACK, false, false}, {REAL_TRIGGERS, true, false}, {FILTER_SHADER, true, false}, {FILTER_CALLBACK, true, false}, {REAL_TRIGGERS, false, true}, {FILTER_SHADER, false, true}, {FILTER_CALLBACK, false, true}, }; static PxU32 gScenario = 0; static PX_FORCE_INLINE TriggerImpl getImpl() { return gData[gScenario].mImpl; } static PX_FORCE_INLINE bool usesCCD() { return gData[gScenario].mCCD; } static PX_FORCE_INLINE bool usesTriggerTrigger() { return gData[gScenario].mTriggerTrigger; } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static bool gPause = false; static bool gOneFrame = false; // Detects a trigger using the shape's simulation filter data. See createTriggerShape() function. bool isTrigger(const PxFilterData& data) { if(data.word0!=0xffffffff) return false; if(data.word1!=0xffffffff) return false; if(data.word2!=0xffffffff) return false; if(data.word3!=0xffffffff) return false; return true; } bool isTriggerShape(PxShape* shape) { const TriggerImpl impl = getImpl(); // Detects native built-in triggers. if(impl==REAL_TRIGGERS && (shape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)) return true; // Detects our emulated triggers using the simulation filter data. See createTriggerShape() function. if(impl==FILTER_SHADER && ::isTrigger(shape->getSimulationFilterData())) return true; // Detects our emulated triggers using the simulation filter callback. See createTriggerShape() function. if(impl==FILTER_CALLBACK && shape->userData) return true; return false; } static PxFilterFlags triggersUsingFilterShader(PxFilterObjectAttributes /*attributes0*/, PxFilterData filterData0, PxFilterObjectAttributes /*attributes1*/, PxFilterData filterData1, PxPairFlags& pairFlags, const void* /*constantBlock*/, PxU32 /*constantBlockSize*/) { // printf("contactReportFilterShader\n"); PX_ASSERT(getImpl()==FILTER_SHADER); // We need to detect whether one of the shapes is a trigger. const bool isTriggerPair = isTrigger(filterData0) || isTrigger(filterData1); // If we have a trigger, replicate the trigger codepath from PxDefaultSimulationFilterShader if(isTriggerPair) { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT; return PxFilterFlag::eDEFAULT; } else { // Otherwise use the default flags for regular pairs pairFlags = PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } } static PxFilterFlags triggersUsingFilterCallback(PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, PxPairFlags& pairFlags, const void* /*constantBlock*/, PxU32 /*constantBlockSize*/) { // printf("contactReportFilterShader\n"); PX_ASSERT(getImpl()==FILTER_CALLBACK); pairFlags = PxPairFlag::eCONTACT_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT|PxPairFlag::eNOTIFY_TOUCH_CCD; return PxFilterFlag::eCALLBACK; } class TriggersFilterCallback : public PxSimulationFilterCallback { virtual PxFilterFlags pairFound( PxU64 /*pairID*/, PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, const PxActor* /*a0*/, const PxShape* s0, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, const PxActor* /*a1*/, const PxShape* s1, PxPairFlags& pairFlags) PX_OVERRIDE { // printf("pairFound\n"); if(s0->userData || s1->userData) // See createTriggerShape() function { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT|PxPairFlag::eNOTIFY_TOUCH_CCD; } else pairFlags = PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlags(); } virtual void pairLost( PxU64 /*pairID*/, PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, bool /*objectRemoved*/) PX_OVERRIDE { // printf("pairLost\n"); } virtual bool statusChange(PxU64& /*pairID*/, PxPairFlags& /*pairFlags*/, PxFilterFlags& /*filterFlags*/) PX_OVERRIDE { // printf("statusChange\n"); return false; } }gTriggersFilterCallback; class ContactReportCallback: public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* /*constraints*/, PxU32 /*count*/) PX_OVERRIDE { printf("onConstraintBreak\n"); } void onWake(PxActor** /*actors*/, PxU32 /*count*/) PX_OVERRIDE { printf("onWake\n"); } void onSleep(PxActor** /*actors*/, PxU32 /*count*/) PX_OVERRIDE { printf("onSleep\n"); } void onTrigger(PxTriggerPair* pairs, PxU32 count) PX_OVERRIDE { // printf("onTrigger: %d trigger pairs\n", count); while(count--) { const PxTriggerPair& current = *pairs++; if(current.status & PxPairFlag::eNOTIFY_TOUCH_FOUND) printf("Shape is entering trigger volume\n"); if(current.status & PxPairFlag::eNOTIFY_TOUCH_LOST) printf("Shape is leaving trigger volume\n"); } } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) PX_OVERRIDE { printf("onAdvance\n"); } void onContact(const PxContactPairHeader& /*pairHeader*/, const PxContactPair* pairs, PxU32 count) PX_OVERRIDE { // printf("onContact: %d pairs\n", count); while(count--) { const PxContactPair& current = *pairs++; // The reported pairs can be trigger pairs or not. We only enabled contact reports for // trigger pairs in the filter shader, so we don't need to do further checks here. In a // real-world scenario you would probably need a way to tell whether one of the shapes // is a trigger or not. You could e.g. reuse the PxFilterData like we did in the filter // shader, or maybe use the shape's userData to identify triggers, or maybe put triggers // in a hash-set and test the reported shape pointers against it. Many options here. if(current.events & (PxPairFlag::eNOTIFY_TOUCH_FOUND|PxPairFlag::eNOTIFY_TOUCH_CCD)) printf("Shape is entering trigger volume\n"); if(current.events & PxPairFlag::eNOTIFY_TOUCH_LOST) printf("Shape is leaving trigger volume\n"); if(isTriggerShape(current.shapes[0]) && isTriggerShape(current.shapes[1])) printf("Trigger-trigger overlap detected\n"); } } }; static ContactReportCallback gContactReportCallback; static PxShape* createTriggerShape(const PxGeometry& geom, bool isExclusive) { const TriggerImpl impl = getImpl(); PxShape* shape = nullptr; if(impl==REAL_TRIGGERS) { const PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eTRIGGER_SHAPE; shape = gPhysics->createShape(geom, *gMaterial, isExclusive, shapeFlags); } else if(impl==FILTER_SHADER) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSIMULATION_SHAPE; shape = gPhysics->createShape(geom, *gMaterial, isExclusive, shapeFlags); // For this method to work, you need a way to mark shapes as triggers without using PxShapeFlag::eTRIGGER_SHAPE // (so that trigger-trigger pairs are reported), and without calling a PxShape function (so that the data is // available in a filter shader). // // One way is to reserve a special PxFilterData value/mask for triggers. It may not always be possible depending // on how you otherwise use the filter data). const PxFilterData triggerFilterData(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); shape->setSimulationFilterData(triggerFilterData); } else if(impl==FILTER_CALLBACK) { // We will have access to shape pointers in the filter callback so we just mark triggers in an arbitrary way here, // for example using the shape's userData. shape = gPhysics->createShape(geom, *gMaterial, isExclusive); shape->userData = shape; // Arbitrary rule: it's a trigger if non null } return shape; } static void createDefaultScene() { const bool ccd = usesCCD(); // Create trigger shape { const PxVec3 halfExtent(10.0f, ccd ? 0.01f : 1.0f, 10.0f); PxShape* shape = createTriggerShape(PxBoxGeometry(halfExtent), false); if(shape) { PxRigidStatic* body = gPhysics->createRigidStatic(PxTransform(0.0f, 10.0f, 0.0f)); body->attachShape(*shape); gScene->addActor(*body); shape->release(); } } // Create falling rigid body { const PxVec3 halfExtent(ccd ? 0.1f : 1.0f); PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(0.0f, ccd ? 30.0f : 20.0f, 0.0f)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 1.0f); gScene->addActor(*body); shape->release(); if(ccd) { body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); body->setLinearVelocity(PxVec3(0.0f, -140.0f, 0.0f)); } } } static void createTriggerTriggerScene() { struct Local { static void createSphereActor(const PxVec3& pos, const PxVec3& linVel) { PxShape* sphereShape = gPhysics->createShape(PxSphereGeometry(1.0f), *gMaterial, false); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(pos)); body->attachShape(*sphereShape); PxShape* triggerShape = createTriggerShape(PxSphereGeometry(4.0f), true); body->attachShape(*triggerShape); const bool isTriggershape = triggerShape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE; if(!isTriggershape) triggerShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); PxRigidBodyExt::updateMassAndInertia(*body, 1.0f); if(!isTriggershape) triggerShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true); gScene->addActor(*body); sphereShape->release(); triggerShape->release(); body->setLinearVelocity(linVel); } }; Local::createSphereActor(PxVec3(-5.0f, 1.0f, 0.0f), PxVec3( 1.0f, 0.0f, 0.0f)); Local::createSphereActor(PxVec3( 5.0f, 1.0f, 0.0f), PxVec3(-1.0f, 0.0f, 0.0f)); } static void initScene() { const TriggerImpl impl = getImpl(); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); // sceneDesc.flags &= ~PxSceneFlag::eENABLE_PCM; sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.simulationEventCallback = &gContactReportCallback; if(impl==REAL_TRIGGERS) { sceneDesc.filterShader = PxDefaultSimulationFilterShader; printf("- Using built-in triggers.\n"); } else if(impl==FILTER_SHADER) { sceneDesc.filterShader = triggersUsingFilterShader; printf("- Using regular shapes emulating triggers with a filter shader.\n"); } else if(impl==FILTER_CALLBACK) { sceneDesc.filterShader = triggersUsingFilterCallback; sceneDesc.filterCallback = &gTriggersFilterCallback; printf("- Using regular shapes emulating triggers with a filter callback.\n"); } if(usesCCD()) { sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; printf("- Using CCD.\n"); } else { printf("- Using no CCD.\n"); } gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); if(usesTriggerTrigger()) createTriggerTriggerScene(); else createDefaultScene(); } static void releaseScene() { PX_RELEASE(gScene); } void stepPhysics(bool /*interactive*/) { if(gPause && !gOneFrame) return; gOneFrame = false; if(gScene) { // printf("Update...\n"); gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } } void initPhysics(bool /*interactive*/) { printf("Press keys F1 to F9 to select a scenario.\n"); gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxInitExtensions(*gPhysics,gPvd); const PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); gMaterial = gPhysics->createMaterial(1.0f, 1.0f, 0.0f); initScene(); } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetTriggers done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } if(gScene) { if(key>=1 && key<=SCENARIO_COUNT) { gScenario = key-1; releaseScene(); initScene(); } if(key=='r' || key=='R') { releaseScene(); initScene(); } } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); for(PxU32 i=0; i<250; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
16,213
C++
29.825095
128
0.719546
NVIDIA-Omniverse/PhysX/physx/snippets/snippettriggers/SnippetTriggersRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); bool isTrigger(const PxFilterData& data); bool isTriggerShape(PxShape* shape); namespace { Snippets::Camera* sCamera; class MyTriggerRender : public Snippets::TriggerRender { public: virtual bool isTrigger(physx::PxShape* shape) const { return ::isTriggerShape(shape); } }; void renderCallback() { stepPhysics(true); if(0) { PxVec3 camPos = sCamera->getEye(); PxVec3 camDir = sCamera->getDir(); printf("camPos: (%ff, %ff, %ff)\n", double(camPos.x), double(camPos.y), double(camPos.z)); printf("camDir: (%ff, %ff, %ff)\n", double(camDir.x), double(camDir.y), double(camDir.z)); } Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); MyTriggerRender tr; Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, PxVec3(0.0f, 0.75f, 0.0f), &tr); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(8.757190f, 12.367847f, 23.541956f), PxVec3(-0.407947f, -0.042438f, -0.912019f)); Snippets::setupDefault("PhysX Snippet Triggers", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,610
C++
33.390476
136
0.746814
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmassproperties/SnippetMassPropertiesRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, (PxActor**)&actors[0], nbActors); Snippets::renderActors(&actors[0], (PxU32)actors.size(), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(34.613838f, 27.653027f, 9.363596f), PxVec3(-0.754040f, -0.401930f, -0.519496f)); Snippets::setupDefault("PhysX Snippet Mass Properties", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,008
C++
34.4
119
0.760971
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmassproperties/SnippetMassProperties.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. // **************************************************************************** // This snippet illustrates different ways of setting mass for rigid bodies. // // It creates 5 snowmen with different mass properties: // - massless with a weight at the bottom // - only the mass of the lowest snowball // - the mass of all the snowballs // - the whole mass but with a low center of gravity // - manual setup of masses // // The different mass properties can be visually inspected by firing a rigid // ball towards each snowman using the space key. // // For more details, please consult the "Rigid Body Dynamics" section of the // user guide. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; // create a dynamic ball to throw at the snowmen. static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static PxRigidDynamic* createSnowMan(const PxTransform& pos, PxU32 mode) { PxRigidDynamic* snowmanActor = gPhysics->createRigidDynamic(PxTransform(pos)); if(!snowmanActor) { printf("create snowman actor failed"); return NULL; } PxShape* armL = NULL; PxShape* armR = NULL; switch(mode%5) { case 0: // with a weight at the bottom { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.2), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,-.29,0))); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,10); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); } break; case 1: // only considering lowest shape mass { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); } break; case 2: // considering whole mass { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); } break; case 3: // considering whole mass with low COM { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); const PxVec3 localPos = PxVec3(0,-.5,0); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1,&localPos); } break; case 4: // setting up mass properties manually { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); snowmanActor->setMass(1); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); snowmanActor->setMassSpaceInertiaTensor(PxVec3(.05,100,100)); } break; default: break; } gScene->addActor(*snowmanActor); return snowmanActor; } static void createSnowMen() { PxU32 numSnowmen = 5; for(PxU32 i=0; i<numSnowmen; i++) { PxVec3 pos(i * 2.5f,1,-8); createSnowMan(PxTransform(pos), i); } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSnowMen(); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMassProperties done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(0.1f), camera.rotate(PxVec3(0,0,-1))*20); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,305
C++
34.463977
120
0.721333
NVIDIA-Omniverse/PhysX/physx/snippets/snippettrianglemeshcreate/SnippetTriangleMeshCreate.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. // **************************************************************************** // This snippet demonstrates the possibilities of triangle mesh creation. // // The snippet creates triangle mesh with a different cooking settings // and shows how these settings affect the triangle mesh creation speed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; float rand(float loVal, float hiVal) { return loVal + float(rand()/float(RAND_MAX))*(hiVal - loVal); } PxU32 rand(PxU32 loVal, PxU32 hiVal) { return loVal + PxU32(rand()%(hiVal - loVal)); } void indexToCoord(PxU32& x, PxU32& z, PxU32 index, PxU32 w) { x = index % w; z = index / w; } // Creates a random terrain data. void createRandomTerrain(const PxVec3& origin, PxU32 numRows, PxU32 numColumns, PxReal cellSizeRow, PxReal cellSizeCol, PxReal heightScale, PxVec3*& vertices, PxU32*& indices) { PxU32 numX = (numColumns + 1); PxU32 numZ = (numRows + 1); PxU32 numVertices = numX*numZ; PxU32 numTriangles = numRows*numColumns * 2; if (vertices == NULL) vertices = new PxVec3[numVertices]; if (indices == NULL) indices = new PxU32[numTriangles * 3]; PxU32 currentIdx = 0; for (PxU32 i = 0; i <= numRows; i++) { for (PxU32 j = 0; j <= numColumns; j++) { PxVec3 v(origin.x + PxReal(j)*cellSizeRow, origin.y, origin.z + PxReal(i)*cellSizeCol); vertices[currentIdx++] = v; } } currentIdx = 0; for (PxU32 i = 0; i < numRows; i++) { for (PxU32 j = 0; j < numColumns; j++) { PxU32 base = (numColumns + 1)*i + j; indices[currentIdx++] = base + 1; indices[currentIdx++] = base; indices[currentIdx++] = base + numColumns + 1; indices[currentIdx++] = base + numColumns + 2; indices[currentIdx++] = base + 1; indices[currentIdx++] = base + numColumns + 1; } } for (PxU32 i = 0; i < numVertices; i++) { PxVec3& v = vertices[i]; v.y += heightScale * rand(-1.0f, 1.0f); } } // Setup common cooking params void setupCommonCookingParams(PxCookingParams& params, bool skipMeshCleanup, bool skipEdgeData) { // we suppress the triangle mesh remap table computation to gain some speed, as we will not need it // in this snippet params.suppressTriangleMeshRemapTable = true; // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. The input mesh must be valid. // The following conditions are true for a valid triangle mesh : // 1. There are no duplicate vertices(within specified vertexWeldTolerance.See PxCookingParams::meshWeldTolerance) // 2. There are no large triangles(within specified PxTolerancesScale.) // It is recommended to run a separate validation check in debug/checked builds, see below. if (!skipMeshCleanup) params.meshPreprocessParams &= ~static_cast<PxMeshPreprocessingFlags>(PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH); else params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; // If eDISABLE_ACTIVE_EDGES_PRECOMPUTE is set, the cooking does not compute the active (convex) edges, and instead // marks all edges as active. This makes cooking faster but can slow down contact generation. This flag may change // the collision behavior, as all edges of the triangle mesh will now be considered active. if (!skipEdgeData) params.meshPreprocessParams &= ~static_cast<PxMeshPreprocessingFlags>(PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE); else params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; } // Creates a triangle mesh using BVH33 midphase with different settings. void createBV33TriangleMesh(PxU32 numVertices, const PxVec3* vertices, PxU32 numTriangles, const PxU32* indices, bool skipMeshCleanup, bool skipEdgeData, bool inserted, bool cookingPerformance, bool meshSizePerfTradeoff) { PxU64 startTime = SnippetUtils::getCurrentTimeCounterValue(); PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = numTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale scale; PxCookingParams params(scale); // Create BVH33 midphase params.midphaseDesc = PxMeshMidPhase::eBVH33; // setup common cooking params setupCommonCookingParams(params, skipMeshCleanup, skipEdgeData); // The COOKING_PERFORMANCE flag for BVH33 midphase enables a fast cooking path at the expense of somewhat lower quality BVH construction. if (cookingPerformance) params.midphaseDesc.mBVH33Desc.meshCookingHint = PxMeshCookingHint::eCOOKING_PERFORMANCE; else params.midphaseDesc.mBVH33Desc.meshCookingHint = PxMeshCookingHint::eSIM_PERFORMANCE; // If meshSizePerfTradeoff is set to true, smaller mesh cooked mesh is produced. The mesh size/performance trade-off // is controlled by setting the meshSizePerformanceTradeOff from 0.0f (smaller mesh) to 1.0f (larger mesh). if(meshSizePerfTradeoff) { params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff = 0.0f; } else { // using the default value params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff = 0.55f; } #if defined(PX_CHECKED) || defined(PX_DEBUG) // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. // We should check the validity of provided triangles in debug/checked builds though. if (skipMeshCleanup) { PX_ASSERT(PxValidateTriangleMesh(params, meshDesc)); } #endif // DEBUG PxTriangleMesh* triMesh = NULL; PxU32 meshSize = 0; // The cooked mesh may either be saved to a stream for later loading, or inserted directly into PxPhysics. if (inserted) { triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } else { PxDefaultMemoryOutputStream outBuffer; PxCookTriangleMesh(params, meshDesc, outBuffer); PxDefaultMemoryInputData stream(outBuffer.getData(), outBuffer.getSize()); triMesh = gPhysics->createTriangleMesh(stream); meshSize = outBuffer.getSize(); } // Print the elapsed time for comparison PxU64 stopTime = SnippetUtils::getCurrentTimeCounterValue(); float elapsedTime = SnippetUtils::getElapsedTimeInMilliseconds(stopTime - startTime); printf("\t -----------------------------------------------\n"); printf("\t Create triangle mesh with %d triangles: \n",numTriangles); cookingPerformance ? printf("\t\t Cooking performance on\n") : printf("\t\t Cooking performance off\n"); inserted ? printf("\t\t Mesh inserted on\n") : printf("\t\t Mesh inserted off\n"); !skipEdgeData ? printf("\t\t Precompute edge data on\n") : printf("\t\t Precompute edge data off\n"); !skipMeshCleanup ? printf("\t\t Mesh cleanup on\n") : printf("\t\t Mesh cleanup off\n"); printf("\t\t Mesh size/performance trade-off: %f \n", double(params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff)); printf("\t Elapsed time in ms: %f \n", double(elapsedTime)); if(!inserted) { printf("\t Mesh size: %d \n", meshSize); } triMesh->release(); } // Creates a triangle mesh using BVH34 midphase with different settings. void createBV34TriangleMesh(PxU32 numVertices, const PxVec3* vertices, PxU32 numTriangles, const PxU32* indices, bool skipMeshCleanup, bool skipEdgeData, bool inserted, const PxU32 numTrisPerLeaf) { PxU64 startTime = SnippetUtils::getCurrentTimeCounterValue(); PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = numTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale scale; PxCookingParams params(scale); // Create BVH34 midphase params.midphaseDesc = PxMeshMidPhase::eBVH34; // setup common cooking params setupCommonCookingParams(params, skipMeshCleanup, skipEdgeData); // Cooking mesh with less triangles per leaf produces larger meshes with better runtime performance // and worse cooking performance. Cooking time is better when more triangles per leaf are used. params.midphaseDesc.mBVH34Desc.numPrimsPerLeaf = numTrisPerLeaf; #if defined(PX_CHECKED) || defined(PX_DEBUG) // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. // We should check the validity of provided triangles in debug/checked builds though. if (skipMeshCleanup) { PX_ASSERT(PxValidateTriangleMesh(params, meshDesc)); } #endif // DEBUG PxTriangleMesh* triMesh = NULL; PxU32 meshSize = 0; // The cooked mesh may either be saved to a stream for later loading, or inserted directly into PxPhysics. if (inserted) { triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } else { PxDefaultMemoryOutputStream outBuffer; PxCookTriangleMesh(params, meshDesc, outBuffer); PxDefaultMemoryInputData stream(outBuffer.getData(), outBuffer.getSize()); triMesh = gPhysics->createTriangleMesh(stream); meshSize = outBuffer.getSize(); } // Print the elapsed time for comparison PxU64 stopTime = SnippetUtils::getCurrentTimeCounterValue(); float elapsedTime = SnippetUtils::getElapsedTimeInMilliseconds(stopTime - startTime); printf("\t -----------------------------------------------\n"); printf("\t Create triangle mesh with %d triangles: \n", numTriangles); inserted ? printf("\t\t Mesh inserted on\n") : printf("\t\t Mesh inserted off\n"); !skipEdgeData ? printf("\t\t Precompute edge data on\n") : printf("\t\t Precompute edge data off\n"); !skipMeshCleanup ? printf("\t\t Mesh cleanup on\n") : printf("\t\t Mesh cleanup off\n"); printf("\t\t Num triangles per leaf: %d \n", numTrisPerLeaf); printf("\t Elapsed time in ms: %f \n", double(elapsedTime)); if (!inserted) { printf("\t Mesh size: %d \n", meshSize); } triMesh->release(); } void createTriangleMeshes() { const PxU32 numColumns = 128; const PxU32 numRows = 128; const PxU32 numVertices = (numColumns + 1)*(numRows + 1); const PxU32 numTriangles = numColumns*numRows * 2; PxVec3* vertices = new PxVec3[numVertices]; PxU32* indices = new PxU32[numTriangles * 3]; srand(50); createRandomTerrain(PxVec3(0.0f, 0.0f, 0.0f), numRows, numColumns, 1.0f, 1.0f, 1.f, vertices, indices); // Create triangle mesh using BVH33 midphase with different settings printf("-----------------------------------------------\n"); printf("Create triangles mesh using BVH33 midphase: \n\n"); // Favor runtime speed, cleaning the mesh and precomputing active edges. Store the mesh in a stream. // These are the default settings, suitable for offline cooking. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, false, false, false, false, false); // Favor mesh size, cleaning the mesh and precomputing active edges. Store the mesh in a stream. createBV33TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, false, true); // Favor cooking speed, skip mesh cleanup, but precompute active edges. Insert into PxPhysics. // These settings are suitable for runtime cooking, although selecting fast cooking may reduce // runtime performance of simulation and queries. We still need to ensure the triangles // are valid, so we perform a validation check in debug/checked builds. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, true, false, true, true, false); // Favor cooking speed, skip mesh cleanup, and don't precompute the active edges. Insert into PxPhysics. // This is the fastest possible solution for runtime cooking, but all edges are marked as active, which can // further reduce runtime performance, and also affect behavior. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, false, true, true, true, false); // Create triangle mesh using BVH34 midphase with different settings printf("-----------------------------------------------\n"); printf("Create triangles mesh using BVH34 midphase: \n\n"); // Favor runtime speed, cleaning the mesh and precomputing active edges. Store the mesh in a stream. // These are the default settings, suitable for offline cooking. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, 4); // Favor mesh size, cleaning the mesh and precomputing active edges. Store the mesh in a stream. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, 15); // Favor cooking speed, skip mesh cleanup, but precompute active edges. Insert into PxPhysics. // These settings are suitable for runtime cooking, although selecting more triangles per leaf may reduce // runtime performance of simulation and queries. We still need to ensure the triangles // are valid, so we perform a validation check in debug/checked builds. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, true, false, true, 15); // Favor cooking speed, skip mesh cleanup, and don't precompute the active edges. Insert into PxPhysics. // This is the fastest possible solution for runtime cooking, but all edges are marked as active, which can // further reduce runtime performance, and also affect behavior. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, true, true, 15); delete [] vertices; delete [] indices; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true); createTriangleMeshes(); } void cleanupPhysics() { PX_RELEASE(gPhysics); PX_RELEASE(gFoundation); printf("SnippetTriangleMeshCreate done.\n"); } int snippetMain(int, const char*const*) { initPhysics(); cleanupPhysics(); return 0; }
15,642
C++
39.525907
139
0.738077
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmultipruners/SnippetMultiPrunersRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet Multi Pruners", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,901
C++
33.547619
117
0.749397
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmultipruners/SnippetMultiPruners.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. // **************************************************************************** // This snippet shows how to use a custom scene query system with N pruners // instead of the traditional two in PxScene. This is mainly useful for large // world with a lot of actors and a lot of updates. The snippet creates a // "worst case scenario" involving hundreds of thousands of actors, which are // all artificially updated each frame to put a lot of pressure on the query // structures. This is not entirely realistic but it makes the gains from the // custom query system more obvious. There is a virtual "player" moving around // in that world and regions are added and removed at runtime according to the // player's position. Each region contains thousands of actors, which stresses // the tree building code, the tree refit code, the build step code, and many // parts of the SQ update pipeline. Pruners can be updated in parallel, which // is more useful with N pruners than it was with the two PxScene build-in pruners. // // Rendering is disabled by default since it can be quite slow for so many // actors. // // Note that the cost of actual scene queries (raycasts, etc) might go up when // using multiple pruners. However the cost of updating the SQ structures can be // much higher than the cost of the scene queries themselves, so this can be a // good trade-off. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "foundation/PxTime.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; // Define this to use a custom pruner. Undefine to use the default PxScene code. #define USE_CUSTOM_PRUNER // This number of threads is used both for the default PhysX CPU dispatcher, and // for the custom concurrent build steps when a custom pruner is used. It does not // have much of an impact when USE_CUSTOM_PRUNER is undefined. #define NUM_WORKER_THREADS 8 //#define NUM_WORKER_THREADS 4 //#define NUM_WORKER_THREADS 2 //#define NUM_WORKER_THREADS 1 #ifdef RENDER_SNIPPET // Enable or disable rendering. Disabled by default, since the default scene uses 648081 actors. // There is a custom piece of code that renders the scene as a single mesh though, so it should // still be usable on fast PCs when enabled. static const bool gEnableRendering = false; #endif // Number of frames to simulate, only used when gEnableRendering == false static const PxU32 gNbFramesToSimulate = 100; // The PhysX tree rebuild rate hint. It is usually a *bad idea* to decrease it to 10 (the default // value is 100), but people do this, and it puts more stress on the build code, which fits the // worst case scenario we're looking for in this snippet. But do note that in most cases it should // really be left to "100", or actually increased in large scenes. static PxU32 gDynamicTreeRebuildRateHint = 10; // How many objects are added in each region. This has a direct impact on performance in all parts // of the system. //static const PxU32 gNbObjectsPerRegion = 400; //static const PxU32 gNbObjectsPerRegion = 800; //static const PxU32 gNbObjectsPerRegion = 2000; //static const PxU32 gNbObjectsPerRegion = 4000; static const PxU32 gNbObjectsPerRegion = 8000; static const float gGlobalScale = 1.0f; // Size of added objects. static const float gObjectScale = 0.01f * gGlobalScale; // This controls whether objects are artificially updated each frame. This resets the objects' positions // to what they already are, no nothing is moving but internally it forces all trees to be refit & rebuilt // constantly. This has a big impact on performance. // // Using "false" here means that: // - if USE_CUSTOM_PRUNER is NOT defined, the new objects are added to a unique tree in PxScene, which triggers // a rebuild. The refit operation is not necessary and skipped. // - if USE_CUSTOM_PRUNER is defined, the new objects are added to a per-region pruner in each region. There is // no rebuild necessary, and no refit either. // // Using "true" here means that all involved trees are constantly refit & rebuilt over a number of frames. static const bool gUpdateObjectsInRegion = true; // Range of player's motion static const float gRange = 10.0f * gGlobalScale; #ifdef RENDER_SNIPPET // Size of player static const float gPlayerSize = 0.1f * gGlobalScale; #endif // Speed of player. If you increase it too much the player might leave a region before its tree gets rebuilt, // which means some parts of the update pipeline are never executed. static const float gPlayerSpeed = 0.1f; //static const float gPlayerSpeed = 0.01f; // Size of active area. The world is effectively infinite but only this active area is considered by the // streaming code. The active area is a square whose edge size is gActiveAreaSize*2. static const float gActiveAreaSize = 5.0f * gGlobalScale; // Number of cells per side == number of regions per side. static const PxU32 gNbCellsPerSide = 8; #ifdef USE_CUSTOM_PRUNER // Number of pruners in the system static const PxU32 gNbPruners = (gNbCellsPerSide+1)*(gNbCellsPerSide+1); // Use true to update all pruners in parallel, false to update them sequentially static const bool gUseConcurrentBuildSteps = true; // Use tree of pruners or not. This is mainly useful if you have a large number of pruners in // the system. There is a small cost associated with maintaining that extra tree but since the // number of pruners should still be vastly smaller than the total number of objects, this is // usually quite cheap. You can profile the ratcast cost by modifying the code at the end of // this snippet and see how using a tree of pruners improves performance. static const bool gUseTreeOfPruners = false; #endif static float gGlobalTime = 0.0f; static SnippetUtils::BasicRandom gRandom(42); static const PxVec3 gYellow(1.0f, 1.0f, 0.0f); static const PxVec3 gRed(1.0f, 0.0f, 0.0f); static const PxVec3 gGreen(0.0f, 1.0f, 0.0f); static PxVec3 computePlayerPos(float globalTime) { const float Amplitude = gRange; const float t = globalTime * gPlayerSpeed; const float x = sinf(t*2.17f) * sinf(t) * Amplitude; const float z = sinf(t*0.77f) * cosf(t) * Amplitude; return PxVec3(x, 0.0f, z); } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #define INVALID_ID 0xffffffff #ifdef RENDER_SNIPPET static PxU8 gBoxIndices[] = { 0,2,1, 0,3,2, 1,6,5, 1,2,6, 5,7,4, 5,6,7, 4,3,0, 4,7,3, 3,6,2, 3,7,6, 5,0,1, 5,4,0 }; #endif namespace { #ifdef USE_CUSTOM_PRUNER struct PrunerData { PrunerData() : mPrunerIndex(INVALID_ID), mNbObjects(0) {} PxU32 mPrunerIndex; PxU32 mNbObjects; }; #endif struct RegionData { PxArray<PxRigidStatic*> mObjects; #ifdef USE_CUSTOM_PRUNER PrunerData* mPrunerData; #endif #ifdef RENDER_SNIPPET PxU32 mNbVerts, mNbTris; PxVec3* mVerts; PxU32* mIndices; #endif }; #ifdef USE_CUSTOM_PRUNER // This adapter class will be used by the PxCustomSceneQuerySystem to map each new actor/shape to a user-defined pruner class SnippetCustomSceneQuerySystemAdapter : public PxCustomSceneQuerySystemAdapter { public: PrunerData mPrunerData[gNbPruners]; SnippetCustomSceneQuerySystemAdapter() { } void createPruners(PxCustomSceneQuerySystem* customSQ) { // We create a pool of pruners, large enough to provide one pruner per region. This is an arbitrary choice, we could also // map multiple regions to the same pruner (as long as these regions are close to each other it's just fine). if(customSQ) { for(PxU32 i=0;i<gNbPruners;i++) mPrunerData[i].mPrunerIndex = customSQ->addPruner(PxPruningStructureType::eDYNAMIC_AABB_TREE, PxDynamicTreeSecondaryPruner::eINCREMENTAL); //mPrunerData[i].mPrunerIndex = customSQ->addPruner(PxPruningStructureType::eDYNAMIC_AABB_TREE, PxDynamicTreeSecondaryPruner::eBVH); } } // This is called by the streaming code to assign a pruner to a region PrunerData* findFreePruner() { for(PxU32 i=0;i<gNbPruners;i++) { if(mPrunerData[i].mNbObjects==0) return &mPrunerData[i]; } PX_ASSERT(0); return NULL; } // This is called by the streaming code to release a pruner when a region is deleted void releasePruner(PxU32 index) { PX_ASSERT(mPrunerData[index].mNbObjects==0); mPrunerData[index].mNbObjects=0; } // This is called by PxCustomSceneQuerySystem to assign a pruner index to a new actor/shape virtual PxU32 getPrunerIndex(const PxRigidActor& actor, const PxShape& /*shape*/) const { const PrunerData* prunerData = reinterpret_cast<const PrunerData*>(actor.userData); return prunerData->mPrunerIndex; } // This is called by PxCustomSceneQuerySystem to validate a pruner for scene queries virtual bool processPruner(PxU32 /*prunerIndex*/, const PxQueryThreadContext* /*context*/, const PxQueryFilterData& /*filterData*/, PxQueryFilterCallback* /*filterCall*/) const { // We could filter out empty pruners here if we have some, but for now we don't bother return true; } }; #endif struct StreamRegion { PX_FORCE_INLINE StreamRegion() : mKey(0), mTimestamp(INVALID_ID), mRegionData(NULL) {} PxU64 mKey; PxU32 mTimestamp; PxBounds3 mCellBounds; RegionData* mRegionData; }; typedef PxHashMap<PxU64, StreamRegion> StreamingCache; class Streamer { PX_NOCOPY(Streamer) public: Streamer(float activeAreaSize, PxU32 nbCellsPerSide); ~Streamer(); void update(const PxVec3& playerPos); void renderDebug(); void render(); PxBounds3 mStreamingBounds; StreamingCache mStreamingCache; PxU32 mTimestamp; const float mActiveAreaSize; const PxU32 mNbCellsPerSide; void addRegion(StreamRegion& region); void updateRegion(StreamRegion& region); void removeRegion(StreamRegion& region); }; } #ifdef USE_CUSTOM_PRUNER static SnippetCustomSceneQuerySystemAdapter gAdapter; #endif Streamer::Streamer(float activeAreaSize, PxU32 nbCellsPerSide) : mTimestamp(0), mActiveAreaSize(activeAreaSize), mNbCellsPerSide(nbCellsPerSide) { mStreamingBounds.setEmpty(); } Streamer::~Streamer() { } void Streamer::addRegion(StreamRegion& region) { PX_ASSERT(region.mRegionData==NULL); // We disable the simulation flag to measure the cost of SQ structures exclusively const PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE; PxVec3 extents = region.mCellBounds.getExtents(); extents.x -= 0.01f * gGlobalScale; extents.z -= 0.01f * gGlobalScale; extents.y = 0.1f * gGlobalScale; PxVec3 center = region.mCellBounds.getCenter(); center.y = -0.1f * gGlobalScale; // In each region we create one "ground" shape and a number of extra smaller objects on it. We use // static objects to make sure the timings aren't polluted by dynamics-related costs. Dynamic actors // can also move to neighboring regions, which in theory means they should be transferred to another // pruner to avoid unpleasant visual artefacts when removing an entire region. This is beyond the // scope of this snippet so, static actors it is. // // The number of static actors in the world is usually much larger than the number of dynamic actors. // Dynamic actors move constantly, so they usually always trigger a refit & rebuild of the corresponding // trees. It is therefore a good idea to separate static and dynamic actors, to avoid the cost of // refit & rebuild for the static parts. In the context of a streaming world it is sometimes good enough // to put static actors in separate pruners (like we do here) but still stuff all dynamic actors in a // unique separate pruner (i.e. the same for the whole world). It avoids the aforementioned issues with // dynamic actors moving to other regions, and if the total number of dynamic actors remains small a // single structure for dynamic actors is often enough. PxShape* groundShape = gPhysics->createShape(PxBoxGeometry(extents), *gMaterial, false, shapeFlags); PxRigidStatic* ground = PxCreateStatic(*gPhysics, PxTransform(center), *groundShape); RegionData* regionData = new RegionData; regionData->mObjects.pushBack(ground); region.mRegionData = regionData; #ifdef USE_CUSTOM_PRUNER regionData->mPrunerData = gAdapter.findFreePruner(); ground->userData = regionData->mPrunerData; regionData->mPrunerData->mNbObjects++; #endif gScene->addActor(*ground); if(gNbObjectsPerRegion) { const PxU32 nbExtraObjects = gNbObjectsPerRegion; const float objectScale = gObjectScale; const float coeffY = objectScale * 20.0f; center.y = objectScale; const PxBoxGeometry boxGeom(objectScale, objectScale, objectScale); PxShape* shape = gPhysics->createShape(boxGeom, *gMaterial, false, shapeFlags); PxRigidActor* actors[nbExtraObjects]; for(PxU32 j=0;j<nbExtraObjects;j++) { PxVec3 c = center; c.x += gRandom.randomFloat() * extents.x * (2.0f - objectScale); c.y += fabsf(gRandom.randomFloat()) * coeffY; c.z += gRandom.randomFloat() * extents.z * (2.0f - objectScale); PxRigidStatic* actor = PxCreateStatic(*gPhysics, PxTransform(c), *shape); actors[j] = actor; regionData->mObjects.pushBack(actor); #ifdef USE_CUSTOM_PRUNER actor->userData = regionData->mPrunerData; regionData->mPrunerData->mNbObjects++; #endif } /* if(0) { PxPruningStructure* ps = physics.createPruningStructure(actors, nbDynamicObjects); scene.addActors(*ps); } else*/ { gScene->addActors(reinterpret_cast<PxActor**>(actors), nbExtraObjects); } } #ifdef RENDER_SNIPPET // Precompute single render mesh for this region (rendering them as individual actors is too // slow). This is also only possible because we used static actors. { const PxU32 nbActors = regionData->mObjects.size(); const PxU32 nbVerts = nbActors*8; const PxU32 nbTris = nbActors*12; PxVec3* pts = new PxVec3[nbVerts]; PxVec3* dstPts = pts; PxU32* indices = new PxU32[nbTris*3]; PxU32* dstIndices = indices; PxU32 baseIndex = 0; for(PxU32 i=0;i<nbActors;i++) { const PxVec3 c = regionData->mObjects[i]->getGlobalPose().p; PxShape* shape; regionData->mObjects[i]->getShapes(&shape, 1); const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(shape->getGeometry()); const PxVec3 minimum = c - boxGeom.halfExtents; const PxVec3 maximum = c + boxGeom.halfExtents; dstPts[0] = PxVec3(minimum.x, minimum.y, minimum.z); dstPts[1] = PxVec3(maximum.x, minimum.y, minimum.z); dstPts[2] = PxVec3(maximum.x, maximum.y, minimum.z); dstPts[3] = PxVec3(minimum.x, maximum.y, minimum.z); dstPts[4] = PxVec3(minimum.x, minimum.y, maximum.z); dstPts[5] = PxVec3(maximum.x, minimum.y, maximum.z); dstPts[6] = PxVec3(maximum.x, maximum.y, maximum.z); dstPts[7] = PxVec3(minimum.x, maximum.y, maximum.z); dstPts += 8; for(PxU32 j=0;j<12*3;j++) dstIndices[j] = gBoxIndices[j] + baseIndex; dstIndices += 12*3; baseIndex += 8; } regionData->mVerts = pts; regionData->mIndices = indices; regionData->mNbVerts = nbVerts; regionData->mNbTris = nbTris; } #endif } void Streamer::updateRegion(StreamRegion& region) { RegionData* regionData = region.mRegionData; if(gUpdateObjectsInRegion) { // Artificial update to trigger the tree refit & rebuild code const PxU32 nbObjects = regionData->mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const PxTransform pose = regionData->mObjects[i]->getGlobalPose(); regionData->mObjects[i]->setGlobalPose(pose); } } } void Streamer::removeRegion(StreamRegion& region) { PX_ASSERT(region.mRegionData); RegionData* regionData = region.mRegionData; #ifdef RENDER_SNIPPET delete [] regionData->mIndices; delete [] regionData->mVerts; #endif // Because we used static actors only we can just release all actors, they didn't move to other regions const PxU32 nbObjects = regionData->mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) regionData->mObjects[i]->release(); #ifdef USE_CUSTOM_PRUNER PX_ASSERT(regionData->mPrunerData); regionData->mPrunerData->mNbObjects-=nbObjects; PX_ASSERT(regionData->mPrunerData->mNbObjects==0); gAdapter.releasePruner(regionData->mPrunerData->mPrunerIndex); #endif delete region.mRegionData; region.mRegionData = NULL; } void Streamer::update(const PxVec3& playerPos) { const float activeAreaSize = mActiveAreaSize; mStreamingBounds = PxBounds3::centerExtents(playerPos, PxVec3(activeAreaSize)); const float worldSize = activeAreaSize*2.0f; const PxU32 nbCellsPerSide = mNbCellsPerSide; const float cellSize = worldSize/float(nbCellsPerSide); const float cellSizeX = cellSize; const float cellSizeZ = cellSize; const PxI32 x0 = PxI32(floorf(mStreamingBounds.minimum.x/cellSizeX)); const PxI32 z0 = PxI32(floorf(mStreamingBounds.minimum.z/cellSizeZ)); const PxI32 x1 = PxI32(ceilf(mStreamingBounds.maximum.x/cellSizeX)); const PxI32 z1 = PxI32(ceilf(mStreamingBounds.maximum.z/cellSizeZ)); // Generally speaking when streaming objects in and out of the game world, we want to first remove // old objects then add new objects (in this order) to give the system a chance to recycle removed // entries and use less resources overall. That's why we split the loop to add objects in two parts. // The first part below finds currently touched regions and updates their timestamp. for(PxI32 j=z0;j<z1;j++) { for(PxI32 i=x0;i<x1;i++) { const PxU64 Key = (PxU64(i)<<32)|PxU64(PxU32(j)); StreamRegion& region = mStreamingCache[Key]; if(region.mTimestamp!=INVALID_ID) { // This region was already active => update its timestamp. PX_ASSERT(region.mKey==Key); region.mTimestamp = mTimestamp; updateRegion(region); } } } // This loop checks all regions in the system and removes the ones that are neither new // (mTimestamp==INVALID_ID) nor persistent (mTimestamp==current timestamp). { PxArray<PxU64> toRemove; // Delayed removal to avoid touching the hashmap while we're iterating it for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) { if(iter->second.mTimestamp!=mTimestamp && iter->second.mTimestamp!=INVALID_ID) { removeRegion(iter->second); toRemove.pushBack(iter->second.mKey); } } const PxU32 nbToGo = toRemove.size(); for(PxU32 i=0;i<nbToGo;i++) { bool b = mStreamingCache.erase(toRemove[i]); PX_ASSERT(b); PX_UNUSED(b); } } // Finally we do our initial loop again looking for new regions (mTimestamp==INVALID_ID) and actually add them. for(PxI32 j=z0;j<z1;j++) { for(PxI32 i=x0;i<x1;i++) { const PxU64 Key = (PxU64(i)<<32)|PxU64(PxU32(j)); StreamRegion& region = mStreamingCache[Key]; if(region.mTimestamp==INVALID_ID) { // New entry region.mKey = Key; region.mTimestamp = mTimestamp; region.mCellBounds.minimum = PxVec3(float(i)*cellSizeX, 0.0f, float(j)*cellSizeZ); region.mCellBounds.maximum = PxVec3(float(i+1)*cellSizeX, 0.0f, float(j+1)*cellSizeZ); addRegion(region); } } } mTimestamp++; } void Streamer::renderDebug() { #ifdef RENDER_SNIPPET Snippets::DrawBounds(mStreamingBounds, gGreen); for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) Snippets::DrawBounds(iter->second.mCellBounds, gRed); #endif } void Streamer::render() { #ifdef RENDER_SNIPPET for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) { const RegionData* data = iter->second.mRegionData; Snippets::renderMesh(data->mNbVerts, data->mVerts, data->mNbTris, data->mIndices, PxVec3(0.1f, 0.2f, 0.3f)); } #endif } static Streamer* gStreamer = NULL; #ifdef USE_CUSTOM_PRUNER static PxCustomSceneQuerySystem* gCustomSQ = NULL; #endif static bool gHasRaycastHit; static PxRaycastHit gRaycastHit; static PxVec3 gOrigin; void renderScene() { #ifdef RENDER_SNIPPET if(0) // Disabled, this is too slow { PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { //printf("Rendering %d actors\n", nbActors); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), false, PxVec3(0.1f, 0.2f, 0.3f), NULL, true, false); } } else { if(gStreamer) gStreamer->render(); } if(gHasRaycastHit) { Snippets::DrawLine(gOrigin, gRaycastHit.position, gYellow); Snippets::DrawFrame(gRaycastHit.position, 1.0f); } else Snippets::DrawLine(gOrigin, gOrigin - PxVec3(0.0f, 100.0f, 0.0f), gYellow); const PxVec3 playerPos = computePlayerPos(gGlobalTime); const PxBounds3 playerBounds = PxBounds3::centerExtents(playerPos, PxVec3(gPlayerSize)); Snippets::DrawBounds(playerBounds, gYellow); // const PxBounds3 activeAreaBounds = PxBounds3::centerExtents(playerPos, PxVec3(gActiveAreaSize)); // Snippets::DrawBounds(activeAreaBounds, gGreen); if(gStreamer) gStreamer->renderDebug(); #endif } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); if(1) { gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); //gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPvd->connect(*transport,PxPvdInstrumentationFlag::ePROFILE); } gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), false, gPvd); gDispatcher = PxDefaultCpuDispatcherCreate(NUM_WORKER_THREADS); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.dynamicStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.dynamicTreeRebuildRateHint = gDynamicTreeRebuildRateHint; #ifdef USE_CUSTOM_PRUNER // For concurrent build steps we're going to use the new custom API in PxCustomSceneQuerySystem so we tell the system // to disable the built-in build-step & commit functions (which are otherwise executed in fetchResults). sceneDesc.sceneQueryUpdateMode = gUseConcurrentBuildSteps ? PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED : PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED; // Create our custom scene query system and tell PxSceneDesc about it PxCustomSceneQuerySystem* customSQ = PxCreateCustomSceneQuerySystem(sceneDesc.sceneQueryUpdateMode, 0x0102030405060708, gAdapter, gUseTreeOfPruners); if(customSQ) { gAdapter.createPruners(customSQ); sceneDesc.sceneQuerySystem = customSQ; gCustomSQ = customSQ; } #endif gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); gStreamer = new Streamer(gActiveAreaSize, gNbCellsPerSide); } #ifdef USE_CUSTOM_PRUNER class TaskBuildStep : public PxLightCpuTask { public: TaskBuildStep() : PxLightCpuTask(), mIndex(INVALID_ID) {} virtual void run() { PX_SIMD_GUARD gCustomSQ->customBuildstep(mIndex); } virtual const char* getName() const { return "TaskBuildStep"; } PxU32 mIndex; }; class TaskWait: public PxLightCpuTask { public: TaskWait(SnippetUtils::Sync* syncHandle) : PxLightCpuTask(), mSyncHandle(syncHandle) {} virtual void run() {} PX_INLINE void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSyncHandle); } virtual const char* getName() const { return "TaskWait"; } private: SnippetUtils::Sync* mSyncHandle; }; static void concurrentBuildSteps() { const PxU32 nbPruners = gCustomSQ->startCustomBuildstep(); PX_UNUSED(nbPruners); { PX_ASSERT(nbPruners==gNbPruners); SnippetUtils::Sync* buildStepsComplete = SnippetUtils::syncCreate(); SnippetUtils::syncReset(buildStepsComplete); TaskWait taskWait(buildStepsComplete); TaskBuildStep taskBuildStep[gNbPruners]; for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].mIndex = i; PxTaskManager* tm = gScene->getTaskManager(); tm->resetDependencies(); tm->startSimulation(); taskWait.setContinuation(*tm, NULL); for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].setContinuation(&taskWait); taskWait.removeReference(); for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].removeReference(); SnippetUtils::syncWait(buildStepsComplete); SnippetUtils::syncRelease(buildStepsComplete); } gCustomSQ->finishCustomBuildstep(); } #endif static PxTime gTime; void stepPhysics(bool /*interactive*/) { if(gStreamer) { const PxVec3 playerPos = computePlayerPos(gGlobalTime); gStreamer->update(playerPos); gOrigin = playerPos+PxVec3(0.0f, 10.0f, 0.0f); } const PxU32 nbActors = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); const float dt = 1.0f/60.0f; gTime.getElapsedSeconds(); { gScene->simulate(dt); gScene->fetchResults(true); #ifdef USE_CUSTOM_PRUNER if(gUseConcurrentBuildSteps) concurrentBuildSteps(); #endif } PxTime::Second time = gTime.getElapsedSeconds()*1000.0; // Ignore first frames to skip the cost of creating all the initial regions static PxU32 nbIgnored = 16; static PxU32 nbCalls = 0; static PxF64 totalTime = 0; static PxF64 peakTime = 0; if(nbIgnored) nbIgnored--; else { nbCalls++; totalTime+=time; if(time>peakTime) peakTime = time; if(1) printf("%d: time: %f ms | avg: %f ms | peak: %f ms | %d actors\n", nbCalls, time, totalTime/PxU64(nbCalls), peakTime, nbActors); } gTime.getElapsedSeconds(); { PxRaycastBuffer buf; gScene->raycast(gOrigin, PxVec3(0.0f, -1.0f, 0.0f), 100.0f, buf); gHasRaycastHit = buf.hasBlock; if(buf.hasBlock) gRaycastHit = buf.block; } time = gTime.getElapsedSeconds()*1000.0; if(0) printf("raycast time: %f us\n", time*1000.0); gGlobalTime += dt; } void cleanupPhysics(bool /*interactive*/) { delete gStreamer; PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMultiPruners done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { } static void runWithoutRendering() { static const PxU32 frameCount = gNbFramesToSimulate; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); } int snippetMain(int, const char*const*) { printf("Multi Pruners snippet.\n"); #ifdef RENDER_SNIPPET if(gEnableRendering) { extern void renderLoop(); renderLoop(); } else runWithoutRendering(); #else runWithoutRendering(); #endif return 0; }
29,388
C++
32.20791
178
0.736865
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometryqueries/SnippetCustomGeometryQueries.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. // **************************************************************************** // This snippet shows how to implement custom geometries queries // callbacks, using PhysX geometry queries. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit); void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit); void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit); /* Two crossed bars. */ struct BarCrosss : PxCustomGeometry::Callbacks { PxVec3 barExtents; DECLARE_CUSTOM_GEOMETRY_TYPE BarCrosss() : barExtents(27, 9, 3) {} virtual PxBounds3 getLocalBounds(const PxGeometry&) const { return PxBounds3(-PxVec3(barExtents.x * 0.5f, barExtents.y * 0.5f, barExtents.x * 0.5f), PxVec3(barExtents.x * 0.5f, barExtents.y * 0.5f, barExtents.x * 0.5f)); } virtual bool generateContacts(const PxGeometry&, const PxGeometry&, const PxTransform&, const PxTransform&, const PxReal, const PxReal, const PxReal, PxContactBuffer&) const { return false; } virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry&, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32, PxGeomRaycastHit* rayHits, PxU32, PxRaycastThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose; PxGeomRaycastHit hits[2]; PxGeometryQuery::raycast(origin, unitDir, barGeom, p0, maxDist, hitFlags, 1, hits + 0); p0 = pose.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); PxGeometryQuery::raycast(origin, unitDir, barGeom, p0, maxDist, hitFlags, 1, hits + 1); rayHits[0] = hits[0].distance < hits[1].distance ? hits[0] : hits[1]; return hits[0].distance < PX_MAX_REAL || hits[1].distance < PX_MAX_REAL ? 1 : 0; } virtual bool overlap(const PxGeometry&, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose0; if (PxGeometryQuery::overlap(barGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; p0 = pose0.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); if (PxGeometryQuery::overlap(barGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; return false; } virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry&, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose0; PxGeomSweepHit hits[2]; PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, barGeom, p0, hits[0], hitFlags, inflation); p0 = pose0.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, barGeom, p0, hits[1], hitFlags, inflation); sweepHit = hits[0].distance < hits[1].distance ? hits[0] : hits[1]; return hits[0].distance < PX_MAX_REAL || hits[1].distance < PX_MAX_REAL; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const {} virtual void computeMassProperties(const PxGeometry&, PxMassProperties&) const {} virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(BarCrosss) static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* gActor = NULL; static BarCrosss gBarCrosss; static PxReal gTime = 0; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f * 3, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create bar cross actor PxRigidDynamic* barCrossActor = gPhysics->createRigidDynamic(PxTransform(PxVec3(0, gBarCrosss.barExtents.y * 0.5f, 0))); barCrossActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); PxRigidActorExt::createExclusiveShape(*barCrossActor, PxCustomGeometry(gBarCrosss), *gMaterial); gScene->addActor(*barCrossActor); gActor = barCrossActor; } void debugRender() { PxGeometryHolder geom; geom.storeAny(PxBoxGeometry(gBarCrosss.barExtents * 0.5f)); PxTransform pose = gActor->getGlobalPose(); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.7f)); pose = pose.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.7f)); // Raycast { PxVec3 origin((gBarCrosss.barExtents.x + 10) * 0.5f, 0, 0); PxVec3 unitDir(-1, 0, 0); float maxDist = gBarCrosss.barExtents.x + 20; PxRaycastBuffer buffer; gScene->raycast(origin, unitDir, maxDist, buffer); renderRaycast(origin, unitDir, maxDist, buffer.hasBlock ? &buffer.block : nullptr); } // Sweep { PxVec3 origin(0, 0, (gBarCrosss.barExtents.x + 10) * 0.5f); PxVec3 unitDir(0, 0, -1); float maxDist = gBarCrosss.barExtents.x + 20; PxVec3 halfExtents(1.5f, 0.5f, 1.0f); PxSweepBuffer buffer; gScene->sweep(PxBoxGeometry(halfExtents), PxTransform(origin), unitDir, maxDist, buffer); renderSweepBox(origin, unitDir, maxDist, halfExtents, buffer.hasBlock ? &buffer.block : nullptr); } // Overlap { PxVec3 origin((gBarCrosss.barExtents.x) * -0.4f, 0, (gBarCrosss.barExtents.x) * -0.4f); PxVec3 halfExtents(gBarCrosss.barExtents.z * 1.5f, gBarCrosss.barExtents.y * 1.1f, gBarCrosss.barExtents.z * 1.5f); PxOverlapBuffer buffer; gScene->overlap(PxBoxGeometry(halfExtents), PxTransform(origin), buffer, PxQueryFilterData(PxQueryFlag::eANY_HIT | PxQueryFlag::eDYNAMIC)); renderOverlapBox(origin, halfExtents, buffer.hasAnyHits()); } } void stepPhysics(bool /*interactive*/) { gTime += 1.0f / 60.0f; gActor->setKinematicTarget(PxTransform(PxQuat(gTime * 0.3f, PxVec3(0, 1, 0)))); gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGeometryQueries done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
10,426
C++
37.476015
148
0.736716
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometryqueries/SnippetCustomGeometryQueriesRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(30.0f, 30.0f, 30.0f), PxVec3(-0.6f, -0.5f, -0.6f)); Snippets::setupDefault("PhysX Snippet GeometryQueries", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } static void PxVertex3f(const PxVec3& v) { ::glVertex3f(v.x, v.y, v.z); }; static void PxScalef(const PxVec3& v) { ::glScalef(v.x, v.y, v.z); }; void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); } else { glColor4f(0.6f, 0.0f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.6f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * hit->distance); PxVertex3f(hit->position); PxVertex3f(hit->position + hit->normal); glEnd(); PxTransform boxPose(origin + unitDir * hit->distance); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.3f, 0.0f, 1.0f); glBegin(GL_LINES); PxVertex3f(origin); PxVertex3f(origin + unitDir * maxDist); glEnd(); } glEnable(GL_LIGHTING); } void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit) { glDisable(GL_LIGHTING); if (hit) { glColor4f(0.0f, 0.0f, 1.0f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } else { glColor4f(0.0f, 0.0f, 0.6f, 1.0f); PxTransform boxPose(origin); PxMat44 boxMat(boxPose); glPushMatrix(); glMultMatrixf(&boxMat.column0.x); PxScalef(halfExtents * 2); glutWireCube(1); glPopMatrix(); } glEnable(GL_LIGHTING); } #endif
5,159
C++
28.152542
137
0.723978
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2multithreading/SnippetVehicleMultithreading.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. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a vehicle with direct drive using parameters, states and // components maintained by the PhysX Vehicle SDK. Particlar attention is paid // to the simulation of a PhysX vehicle in a multi-threaded environment. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a direct drive drivetrain model that forwards input controls to wheel torques and angles. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). //This snippet // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPVD.h" #include "common/PxProfileZone.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; PxTaskManager* gTaskManager = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicles with direct drivetrain #define NUM_VEHICLES 1024 DirectDriveVehicle gVehicles[NUM_VEHICLES]; PxVehiclePhysXActorBeginComponent* gPhysXBeginComponents[NUM_VEHICLES]; PxVehiclePhysXActorEndComponent* gPhysXEndComponents[NUM_VEHICLES]; #define NUM_WORKER_THREADS 4 #define UPDATE_BATCH_SIZE 1 #define NB_SUBSTEPS 1 //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicles a name so they can be identified in PVD. const char gVehicleName[] = "directDrive"; //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; //Track the number of simulation steps. PxU32 gNbSimulateSteps = 0; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxF32 duration; }; Command gCommands[] = { {0.0f, 0.5f, 0.0f, 4.26f}, //throttle for 256 update steps at 60Hz }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //Profile the different phases of a simulate step. struct UpdatePhases { enum Enum { eVEHICLE_PHYSX_BEGIN_COMPONENTS, eVEHICLE_UPDATE_COMPONENTS, eVEHICLE_PHYSX_END_COMPONENTS, ePHYSX_SCENE_SIMULATE, eMAX_NUM_UPDATE_STAGES }; }; static const char* gUpdatePhaseNames[UpdatePhases::eMAX_NUM_UPDATE_STAGES] = { "vehiclePhysXBeginComponents", "vehicleUpdateComponents", "vehiclePhysXEndComponents", "physXSceneSimulate" }; struct ProfileZones { PxU64 times[UpdatePhases::eMAX_NUM_UPDATE_STAGES]; ProfileZones() { for (int i = 0; i < UpdatePhases::eMAX_NUM_UPDATE_STAGES; ++i) times[i] = 0; } void print() { for (int i = 0; i < UpdatePhases::eMAX_NUM_UPDATE_STAGES; ++i) { float ms = SnippetUtils::getElapsedTimeInMilliseconds(times[i]); printf("%s: %f ms\n", gUpdatePhaseNames[i], PxF64(ms)); } } void zoneStart(UpdatePhases::Enum zoneId) { PxU64 time = SnippetUtils::getCurrentTimeCounterValue(); times[zoneId] -= time; } void zoneEnd(UpdatePhases::Enum zoneId) { PxU64 time = SnippetUtils::getCurrentTimeCounterValue(); times[zoneId] += time; } }; ProfileZones gProfileZones; class ScopedProfileZone { private: ScopedProfileZone(const ScopedProfileZone&); ScopedProfileZone& operator=(const ScopedProfileZone&); public: ScopedProfileZone(ProfileZones& zones, UpdatePhases::Enum zoneId) : mZones(zones) , mZoneId(zoneId) { zones.zoneStart(zoneId); } ~ScopedProfileZone() { mZones.zoneEnd(mZoneId); } private: ProfileZones& mZones; UpdatePhases::Enum mZoneId; }; #define SNIPPET_PROFILE_ZONE(zoneId) ScopedProfileZone PX_CONCAT(_scoped, __LINE__)(gProfileZones, zoneId) //TaskVehicleUpdates allows vehicle updates to be performed concurrently across //multiple threads. class TaskVehicleUpdates : public PxLightCpuTask { public: TaskVehicleUpdates() : PxLightCpuTask(), mTimestep(0), mGravity(PxVec3(0, 0, 0)), mThreadId(0xffffffff), mCommandProgress(0) { } void setThreadId(const PxU32 threadId) { mThreadId = threadId; } void setTimestep(const PxF32 timestep) { mTimestep = timestep; } void setGravity(const PxVec3& gravity) { mGravity = gravity; } void setCommandProgress(const PxU32 commandProgress) { mCommandProgress = commandProgress; } virtual void run() { PxU32 vehicleId = mThreadId * UPDATE_BATCH_SIZE; while (vehicleId < NUM_VEHICLES) { const PxU32 numToUpdate = PxMin(NUM_VEHICLES - vehicleId, static_cast<PxU32>(UPDATE_BATCH_SIZE)); for (PxU32 i = 0; i < numToUpdate; i++) { gVehicles[vehicleId + i].mCommandState.brakes[0] = gCommands[mCommandProgress].brake; gVehicles[vehicleId + i].mCommandState.nbBrakes = 1; gVehicles[vehicleId + i].mCommandState.throttle = gCommands[mCommandProgress].throttle; gVehicles[vehicleId + i].mCommandState.steer = gCommands[mCommandProgress].steer; gVehicles[vehicleId + i].mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eFORWARD; gVehicles[vehicleId + i].step(mTimestep, gVehicleSimulationContext); } vehicleId += NUM_WORKER_THREADS * UPDATE_BATCH_SIZE; } } virtual const char* getName() const { return "TaskVehicleUpdates"; } private: PxF32 mTimestep; PxVec3 mGravity; PxU32 mThreadId; PxU32 mCommandProgress; }; //TaskWait runs after all concurrent updates have completed. class TaskWait : public PxLightCpuTask { public: TaskWait(SnippetUtils::Sync* syncHandle) : PxLightCpuTask(), mSyncHandle(syncHandle) { } virtual void run() { } PX_INLINE void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSyncHandle); } virtual const char* getName() const { return "TaskWait"; } private: SnippetUtils::Sync* mSyncHandle; }; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::ePROFILE); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; gDispatcher = PxDefaultCpuDispatcherCreate(NUM_WORKER_THREADS); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, false); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); ///////////////////////////////////////////// //Create a task manager that will be used to //update the vehicles concurrently across //multiple threads. ///////////////////////////////////////////// gTaskManager = PxTaskManager::createTaskManager(gFoundation->getErrorCallback(), gDispatcher); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gTaskManager); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json BaseVehicleParams baseParams; readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams); PhysXIntegrationParams physxParams; setPhysXIntegrationParams(baseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, physxParams); DirectDrivetrainParams directDrivetrainParams; readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams); //Create the params, states and component sequences for direct drive vehicles. //Take care not to add PxVehiclePhysXActorBeginComponent or PxVehiclePhysXActorEndComponent //to the sequences because are executed in a separate step. for (PxU32 i = 0; i < NUM_VEHICLES; i++) { //Set the vehicle params. //Every vehicle is identical. gVehicles[i].mBaseParams = baseParams; gVehicles[i].mPhysXParams = physxParams; gVehicles[i].mDirectDriveParams = directDrivetrainParams; //Set the states to default and create the component sequence. //Take care not to add PxVehiclePhysXActorBeginComponent and PxVehiclePhysXActorEndComponent //to the sequence because these are handled separately to take advantage of multi-threading. const bool addPhysXBeginAndEndComponentsToSequence = false; if (!gVehicles[i].initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, addPhysXBeginAndEndComponentsToSequence)) { return false; } //Force a known substep count per simulation step so that we have a perfect understanding of //the amount of computational effort involved in running the snippet. gVehicles[i].mComponentSequence.setSubsteps(gVehicles[i].mComponentSequenceSubstepGroupHandle, NB_SUBSTEPS); //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(5.0f*(PxI32(i) - NUM_VEHICLES/2), 0.0f, 0.0f), PxQuat(PxIdentity)); gVehicles[i].setUpActor(*gScene, pose, gVehicleName); } //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXBeginComponents[i] = (static_cast<PxVehiclePhysXActorBeginComponent*>(gVehicles + i)); gPhysXEndComponents[i] = (static_cast<PxVehiclePhysXActorEndComponent*>(gVehicles + i)); } //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gVehicles[i].destroy(); } } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void concurrentVehicleUpdates(const PxReal timestep) { SnippetUtils::Sync* vehicleUpdatesComplete = SnippetUtils::syncCreate(); SnippetUtils::syncReset(vehicleUpdatesComplete); //Create tasks that will update the vehicles concurrently then wait until all vehicles //have completed their update. TaskWait taskWait(vehicleUpdatesComplete); TaskVehicleUpdates taskVehicleUpdates[NUM_WORKER_THREADS]; for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].setThreadId(i); taskVehicleUpdates[i].setTimestep(timestep); taskVehicleUpdates[i].setGravity(gScene->getGravity()); taskVehicleUpdates[i].setCommandProgress(gCommandProgress); } //Start the task manager. gTaskManager->resetDependencies(); gTaskManager->startSimulation(); //Perform a vehicle simulation step and profile each phase of the simulation. { //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_PHYSX_BEGIN_COMPONENTS); for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXBeginComponents[i]->update(timestep, gVehicleSimulationContext); } } //Multi-threaded update of direct drive vehicles. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_UPDATE_COMPONENTS); //Update the vehicles concurrently then wait until all vehicles //have completed their update. taskWait.setContinuation(*gTaskManager, NULL); for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].setContinuation(&taskWait); } taskWait.removeReference(); for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].removeReference(); } //Wait for the signal that the work has been completed. SnippetUtils::syncWait(vehicleUpdatesComplete); //Release the sync handle SnippetUtils::syncRelease(vehicleUpdatesComplete); } //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_PHYSX_END_COMPONENTS); for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXEndComponents[i]->update(timestep, gVehicleSimulationContext); } } } } void stepPhysics() { if(gNbCommands == gCommandProgress) return; const PxF32 timestep = 0.0166667f; //Multithreaded update of all vehicles. concurrentVehicleUpdates(timestep); //Forward integrate the phsyx scene by a single timestep. SNIPPET_PROFILE_ZONE(UpdatePhases::ePHYSX_SCENE_SIMULATE); gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if(gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } gNbSimulateSteps++; } int snippetMain(int argc, const char*const* argv) { if(!parseVehicleDataPath(argc, argv, "SnippetVehicle2Multithreading", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. DirectDrivetrainParams directDrivetrainParams; if (!readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams)) return 1; printf("Initialising ... \n"); if(initPhysics()) { printf("Simulating %d vehicles with %d threads \n", NUM_VEHICLES, NUM_WORKER_THREADS); while(gCommandProgress != gNbCommands) { stepPhysics(); } printf("Completed %d simulate steps with %d substeps per simulate step \n", gNbSimulateSteps, NB_SUBSTEPS); gProfileZones.print(); cleanupPhysics(); } return 0; }
21,867
C++
32.437309
127
0.755339
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbody/SnippetSoftBody.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_SOFTBODY_H #define PHYSX_SNIPPET_SOFTBODY_H #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #include <vector> class SoftBody { public: SoftBody(physx::PxSoftBody* softBody, physx::PxCudaContextManager* cudaContextManager) : mSoftBody(softBody), mCudaContextManager(cudaContextManager) { mPositionsInvMass = PX_PINNED_HOST_ALLOC_T(physx::PxVec4, cudaContextManager, softBody->getCollisionMesh()->getNbVertices()); } ~SoftBody() { } void release() { if (mSoftBody) mSoftBody->release(); if (mPositionsInvMass) PX_PINNED_HOST_FREE(mCudaContextManager, mPositionsInvMass); } void copyDeformedVerticesFromGPUAsync(CUstream stream) { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoHAsync(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4), stream); } void copyDeformedVerticesFromGPU() { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoH(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4)); } physx::PxVec4* mPositionsInvMass; physx::PxSoftBody* mSoftBody; physx::PxCudaContextManager* mCudaContextManager; }; #endif
3,270
C
38.890243
205
0.772783
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbody/MeshGenerator.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_MESHGENERATOR_H #define PHYSX_MESHGENERATOR_H #include "PxPhysicsAPI.h" #include "extensions/PxRemeshingExt.h" namespace meshgenerator { using namespace physx; void createCube(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& pos, PxReal scaling) { triVerts.clear(); triIndices.clear(); triVerts.pushBack(scaling * PxVec3(0.5f, -0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, -0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, -0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, -0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, 0.5f, -0.5f) + pos); triVerts.pushBack(scaling * PxVec3(0.5f, 0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, 0.5f, 0.5f) + pos); triVerts.pushBack(scaling * PxVec3(-0.5f, 0.5f, -0.5f) + pos); triIndices.pushBack(1); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(6); triIndices.pushBack(5); triIndices.pushBack(4); triIndices.pushBack(5); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(6); triIndices.pushBack(2); triIndices.pushBack(2); triIndices.pushBack(6); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(3); triIndices.pushBack(7); triIndices.pushBack(0); triIndices.pushBack(1); triIndices.pushBack(3); triIndices.pushBack(4); triIndices.pushBack(7); triIndices.pushBack(5); triIndices.pushBack(0); triIndices.pushBack(4); triIndices.pushBack(1); triIndices.pushBack(1); triIndices.pushBack(5); triIndices.pushBack(2); triIndices.pushBack(3); triIndices.pushBack(2); triIndices.pushBack(7); triIndices.pushBack(4); triIndices.pushBack(0); triIndices.pushBack(7); } void createConeY(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, PxReal height, PxU32 numPointsOnRing = 32) { triVerts.clear(); triIndices.clear(); for (PxU32 i = 0; i < numPointsOnRing; ++i) { PxReal angle = i * 2.0f * 3.1415926535898f / numPointsOnRing; triVerts.pushBack(center + radius * PxVec3(PxSin(angle), 0, PxCos(angle))); } triVerts.pushBack(center); triVerts.pushBack(center + PxVec3(0, height, 0)); for (PxU32 i = 0; i < numPointsOnRing; ++i) { triIndices.pushBack(numPointsOnRing); triIndices.pushBack(i); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(numPointsOnRing + 1); triIndices.pushBack((i + 1) % numPointsOnRing); triIndices.pushBack(i); } } void projectPointsOntoSphere(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); triVerts[i] = center + radius * dir; } } void createSphere(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, const PxReal maxEdgeLength) { triVerts.clear(); triIndices.clear(); createCube(triVerts, triIndices, center, radius); projectPointsOntoSphere(triVerts, center, radius); while (PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 1)) projectPointsOntoSphere(triVerts, center, radius); } } #endif
4,839
C
43.403669
151
0.744989
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbody/SnippetSoftBodyRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "SnippetSoftBody.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern std::vector<SoftBody> gSoftBodies; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynColor(1.0f, 0.5f, 0.25f); const PxVec3 rcaColor(0.6f*0.75f, 0.8f*0.75f, 1.0f*0.75f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; Snippets::renderSoftBody(sb->mSoftBody, sb->mPositionsInvMass, true, rcaColor); } Snippets::finishRender(); } void cleanup() { delete sCamera; cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(10.0f, 10.0f, 10.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet Softbody", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); cleanup(); } #endif
3,320
C++
31.881188
136
0.748494
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbody/SnippetSoftBody.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. // **************************************************************************** // This snippet demonstrates how to setup softbodies. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsoftbody/SnippetSoftBody.h" #include "../snippetsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount) { PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createCube(triVerts, triIndices, PxVec3(0, 9, 0), 2.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); createSoftBody(params, triVerts, triIndices, true); createSphere(triVerts, triIndices, PxVec3(0, 4.5, 0), 2.5, maxEdgeLength); createSoftBody(params, triVerts, triIndices); createConeY(triVerts, triIndices, PxVec3(0, 11.5, 0), 2.0f, 3.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); createSoftBody(params, triVerts, triIndices); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); } } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Softbody done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,158
C++
36.765799
175
0.767769
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitfetchresults/SnippetSplitFetchResults.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. // **************************************************************************** // This snippet illustrates the use of split fetchResults() calls to improve // the performace contact report processing. // // It defines a filter shader function that requests touch reports for // all pairs, and a contact callback function that saves the contact points. // It configures the scene to use this filter and callback, and prints the // number of contact reports each frame. If rendering, it renders each // contact as a line whose length and direction are defined by the contact // impulse. The callback can be processed earlier than usual by using the // split fetchResults() sequence of fetchResultsStart(), processCallbacks(), // fetchResultsFinish(). // // **************************************************************************** #include <vector> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "foundation/PxAtomic.h" #include "task/PxTask.h" #define PARALLEL_CALLBACKS 1 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; const PxI32 maxCount = 10000; PxI32 gSharedIndex = 0; PxVec3* gContactPositions; PxVec3* gContactImpulses; PxVec3* gContactVertices; class CallbackFinishTask : public PxLightCpuTask { SnippetUtils::Sync* mSync; public: CallbackFinishTask(){ mSync = SnippetUtils::syncCreate(); } virtual void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSync); } void reset() { SnippetUtils::syncReset(mSync); } void wait() { SnippetUtils::syncWait(mSync); } virtual void run() { /*Do nothing - release the sync in the release method for thread-safety*/} virtual const char* getName() const { return "CallbackFinishTask"; } } callbackFinishTask; PxFilterFlags contactReportFilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(filterData0); PX_UNUSED(filterData1); PX_UNUSED(constantBlockSize); PX_UNUSED(constantBlock); // all initial and persisting reports for everything, with per-point data pairFlags = PxPairFlag::eSOLVE_CONTACT | PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eNOTIFY_CONTACT_POINTS; return PxFilterFlag::eDEFAULT; } class ContactReportCallback : public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) { PX_UNUSED(constraints); PX_UNUSED(count); } void onWake(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onSleep(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onTrigger(PxTriggerPair* pairs, PxU32 count) { PX_UNUSED(pairs); PX_UNUSED(count); } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) {} void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) { PX_UNUSED((pairHeader)); //Maximum of 64 vertices can be produced by contact gen PxContactPairPoint contactPoints[64]; for (PxU32 i = 0; i<nbPairs; i++) { PxU32 contactCount = pairs[i].contactCount; if (contactCount) { pairs[i].extractContacts(&contactPoints[0], contactCount); PxI32 startIdx = physx::PxAtomicAdd(&gSharedIndex, int32_t(contactCount)); for (PxU32 j = 0; j<contactCount; j++) { gContactPositions[startIdx+j] = contactPoints[j].position; gContactImpulses[startIdx+j] = contactPoints[j].impulse; gContactVertices[2*(startIdx + j)] = contactPoints[j].position; gContactVertices[2*(startIdx + j) + 1] = contactPoints[j].position + contactPoints[j].impulse * 0.1f; } } } } }; ContactReportCallback gContactReportCallback; void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i<size; i++) { for (PxU32 j = 0; j<size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool /*interactive*/) { gContactPositions = new PxVec3[maxCount]; gContactImpulses = new PxVec3[maxCount]; gContactVertices = new PxVec3[2*maxCount]; gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.filterShader = contactReportFilterShader; sceneDesc.simulationEventCallback = &gContactReportCallback; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); const PxU32 nbStacks = 50; for (PxU32 i = 0; i < nbStacks; ++i) { createStack(PxTransform(PxVec3(0, 3.0f, 10.f - 5.f*i)), 5, 2.0f); } } void stepPhysics(bool /*interactive*/) { gSharedIndex = 0; gScene->simulate(1.0f / 60.0f); #if !PARALLEL_CALLBACKS gScene->fetchResults(true); #else //Call fetchResultsStart. Get the set of pair headers const PxContactPairHeader* pairHeader; PxU32 nbContactPairs; gScene->fetchResultsStart(pairHeader, nbContactPairs, true); //Set up continuation task to be run after callbacks have been processed in parallel callbackFinishTask.setContinuation(*gScene->getTaskManager(), NULL); callbackFinishTask.reset(); //process the callbacks gScene->processCallbacks(&callbackFinishTask); callbackFinishTask.removeReference(); callbackFinishTask.wait(); gScene->fetchResultsFinish(); #endif printf("%d contact reports\n", PxU32(gSharedIndex)); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); delete gContactPositions; delete gContactImpulses; delete gContactVertices; printf("SnippetSplitFetchResults done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); for (PxU32 i = 0; i<250; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
9,427
C++
33.534798
113
0.73735
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitfetchresults/SnippetSplitFetchResultsRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern PxVec3* gContactPositions; extern PxVec3* gContactImpulses; extern PxI32 gSharedIndex; extern PxVec3* gContactVertices; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if (nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } PxI32 count = gSharedIndex; if (count) { glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(count*2)); glDisableClientState(GL_VERTEX_ARRAY); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f, -0.2f, -0.7f)); Snippets::setupDefault("PhysX Snippet Split fetchResults", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,367
C++
33.367347
137
0.749629
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2truck/SnippetVehicleTruck.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. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate multiple vehicles jointed together. The snippet introduces // the simple example of a tractor pulling a trailer. The wheels of the tractor // respond to brake, throttle and steer. The trailer, on the other hand, has no // engine or steering column and is only able to apply brake torques to the wheels. // The snippet uses only parameters, states and components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a drivetrain model that forwards input controls to wheel torques via a drivetrain model // that includes engine, clutch, differential and gears. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/EngineDrivetrainSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The tractor with engine drivetrain. //The trailer with direct drivetrain //A joint connecting the two vehicles together. EngineDriveVehicle gTractor; DirectDriveVehicle gTrailer; PxD6Joint* gJoint = NULL; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicles names so they can be identified in PVD. const char gTractorName[] = "tractor"; const char gTrailerName[] = "trailer"; //Commands are issued to the vehicles in a pre-choreographed sequence. //Note: // the tractor responds to brake, throttle and steer commands. // the trailer responds only to brake commands. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxU32 gear; PxF32 duration; }; const PxU32 gTargetGearCommand = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; Command gCommands[] = { {0.5f, 0.0f, 0.0f, gTargetGearCommand, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.65f, 0.0f, gTargetGearCommand, 5.0f}, //throttle for 5 seconds {0.5f, 0.0f, 0.0f, gTargetGearCommand, 5.0f}, //brake for 5 seconds {0.0f, 0.75f, 0.0f, gTargetGearCommand, 5.0f} //throttle for 5 seconds }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitExtensions(*gPhysics, gPvd); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PxCloseExtensions(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the tractor params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gTractor.mBaseParams); setPhysXIntegrationParams(gTractor.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gTractor.mPhysXParams); readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", gTractor.mEngineDriveParams); //Load the trailer params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gTrailer.mBaseParams); setPhysXIntegrationParams(gTrailer.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gTrailer.mPhysXParams); readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", gTrailer.mBaseParams.axleDescription, gTrailer.mDirectDriveParams); //Set the states to default. if (!gTractor.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, EngineDriveVehicle::eDIFFTYPE_FOURWHEELDRIVE)) { return false; } if (!gTrailer.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial)) { return false; } //Create a PhysX joint to connect tractor and trailer. //Create a joint anchor that is 1.5m behind the rear wheels of the tractor and 1.5m in front of the front wheels of the trailer. PxTransform anchorTractorFrame(PxIdentity); { //Rear wheels are 2 and 3. PxRigidBody* rigidActor = gTractor.mPhysXState.physxActor.rigidBody; const PxTransform cMassLocalPoseActorFrame = rigidActor->getCMassLocalPose(); const PxVec3 frontAxlePosCMassFrame = (gTractor.mBaseParams.suspensionParams[2].suspensionAttachment.p + gTractor.mBaseParams.suspensionParams[3].suspensionAttachment.p)*0.5f; const PxQuat frontAxleQuatCMassFrame = gTractor.mBaseParams.suspensionParams[2].suspensionAttachment.q; const PxTransform anchorCMassFrame(frontAxlePosCMassFrame - PxVec3(0, 0, 1.5f), frontAxleQuatCMassFrame); anchorTractorFrame = cMassLocalPoseActorFrame * anchorCMassFrame; } PxTransform anchorTrailerFrame(PxIdentity); { //Front wheels are 0 and 1. PxRigidBody* rigidActor = gTrailer.mPhysXState.physxActor.rigidBody; const PxTransform cMassLocalPoseActorFrame = rigidActor->getCMassLocalPose(); const PxVec3 rearAxlePosCMassFrame = (gTrailer.mBaseParams.suspensionParams[0].suspensionAttachment.p + gTractor.mBaseParams.suspensionParams[1].suspensionAttachment.p)*0.5f; const PxQuat rearAxleQuatCMassFrame = gTrailer.mBaseParams.suspensionParams[0].suspensionAttachment.q; const PxTransform anchorCMassFrame(rearAxlePosCMassFrame + PxVec3(0, 0, 1.5f), rearAxleQuatCMassFrame); anchorTrailerFrame = cMassLocalPoseActorFrame * anchorCMassFrame; } //Apply a start pose to the physx actor of tractor and trailer and add them to the physx scene. const PxTransform tractorPose(PxVec3(0.000000000f, -0.0500000119f, -1.59399998f), PxQuat(PxIdentity)); gTractor.setUpActor(*gScene, tractorPose, gTractorName); const PxTransform trailerPose = tractorPose*anchorTractorFrame*anchorTrailerFrame.getInverse(); gTrailer.setUpActor(*gScene, trailerPose, gTrailerName); //Create a joint between tractor and trailer. { gJoint = PxD6JointCreate(*gPhysics, gTractor.mPhysXState.physxActor.rigidBody, anchorTractorFrame, gTrailer.mPhysXState.physxActor.rigidBody, anchorTrailerFrame); gJoint->setMotion(PxD6Axis::eX, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eY, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eZ, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); gJoint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); gJoint->getConstraint()->setFlags(gJoint->getConstraint()->getFlags() | PxConstraintFlag::eCOLLISION_ENABLED); } //Set the tractor in 1st gear and to use the autobox gTractor.mEngineDriveState.gearboxState.currentGear = gTractor.mEngineDriveParams.gearBoxParams.neutralGear + 1; gTractor.mEngineDriveState.gearboxState.targetGear = gTractor.mEngineDriveParams.gearBoxParams.neutralGear + 1; gTractor.mTransmissionCommandState.targetGear = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; //Set the trailer in neutral gear to prevent any drive torques being applied to the trailer. gTrailer.mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL; //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gJoint->release(); gTractor.destroy(); gTrailer.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; const PxReal timestep = 1.0f/60.0f; //Apply the brake, throttle and steer to the command state of the tractor. const Command& command = gCommands[gCommandProgress]; gTractor.mCommandState.brakes[0] = command.brake; gTractor.mCommandState.nbBrakes = 1; gTractor.mCommandState.throttle = command.throttle; gTractor.mCommandState.steer = command.steer; gTractor.mTransmissionCommandState.targetGear = command.gear; //Apply the brake to the command state of the trailer. gTrailer.mCommandState.brakes[0] = command.brake; gTrailer.mCommandState.nbBrakes = 1; //Apply substepping at low forward speed to improve simulation fidelity. //Tractor and trailer will have approximately the same forward speed so we can apply //the same substepping rules to the tractor and trailer. const PxVec3 linVel = gTractor.mPhysXState.physxActor.rigidBody->getLinearVelocity(); const PxVec3 forwardDir = gTractor.mPhysXState.physxActor.rigidBody->getGlobalPose().q.getBasisVector2(); const PxReal forwardSpeed = linVel.dot(forwardDir); const PxU8 nbSubsteps = (forwardSpeed < 5.0f ? 3 : 1); gTractor.mComponentSequence.setSubsteps(gTractor.mComponentSequenceSubstepGroupHandle, nbSubsteps); gTrailer.mComponentSequence.setSubsteps(gTrailer.mComponentSequenceSubstepGroupHandle, nbSubsteps); //Reset the sticky states on the trailer using the actuation state of the truck. //Vehicles are brought to rest with sticky constraints that apply velocity constraints to the tires of the vehicle. //A drive torque applied to any wheel of the tractor signals an intent to accelerate. //An intent to accelerate will release any sticky constraints applied to the tires of the tractor. //It is important to apply the intent to accelerate to the wheels of the trailer as well to prevent the trailer being //held at rest with its own sticky constraints. //It is not possible to determine an intent to accelerate from the trailer alone because the wheels of the trailer //do not respond to the throttle commands and therefore receive zero drive torque. //The function PxVehicleTireStickyStateReset() will reset the sticky states of the trailer using an intention to //accelerate derived from the state of the tractor. const PxVehicleArrayData<const PxVehicleWheelActuationState> tractorActuationStates(gTractor.mBaseState.actuationStates); PxVehicleArrayData<PxVehicleTireStickyState> trailerTireStickyStates(gTrailer.mBaseState.tireStickyStates); const bool intentionToAccelerate = PxVehicleAccelerationIntentCompute(gTractor.mBaseParams.axleDescription, tractorActuationStates); PxVehicleTireStickyStateReset(intentionToAccelerate, gTrailer.mBaseParams.axleDescription, trailerTireStickyStates); //Forward integrate the vehicles by a single timestep. gTractor.step(timestep, gVehicleSimulationContext); gTrailer.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2Truck", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. EngineDrivetrainParams engineDrivetrainParams; if (!readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", engineDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { while (gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
20,422
C++
43.494553
177
0.781804
NVIDIA-Omniverse/PhysX/physx/snippets/snippetccd/SnippetCCDRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.502444f, -0.442113f, -0.743025f)); Snippets::setupDefault("PhysX Snippet CCD", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,111
C++
33.577777
136
0.757313
NVIDIA-Omniverse/PhysX/physx/snippets/snippetccd/SnippetCCD.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. // **************************************************************************** // This snippet illustrates how to use different types of CCD methods, // including linear, raycast and speculative CCD. // // The scene has two parts: // - a simple box stack and a fast moving sphere. Without (linear) CCD the // sphere goes through the box stack. With CCD the sphere hits the stack and // the behavior is more convincing. // - a simple rotating plank (fixed in space except for one rotation axis) // that collides with a falling box. Wihout (angular) CCD the collision is missed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "extensions/PxRaycastCCD.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static RaycastCCDManager* gRaycastCCD = NULL; static PxReal stackZ = 10.0f; enum CCDAlgorithm { // Uses linear CCD algorithm LINEAR_CCD, // Uses speculative/angular CCD algorithm SPECULATIVE_CCD, // Uses linear & angular CCD at the same time FULL_CCD, // Uses raycast CCD algorithm RAYCAST_CCD, // Switch to NO_CCD to see the sphere go through the box stack without CCD. NO_CCD, // Number of CCD algorithms used in this snippet CCD_COUNT }; static bool gPause = false; static bool gOneFrame = false; static const PxU32 gScenarioCount = CCD_COUNT; static PxU32 gScenario = 0; static PX_FORCE_INLINE CCDAlgorithm getCCDAlgorithm() { return CCDAlgorithm(gScenario); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0), bool enableLinearCCD = false, bool enableSpeculativeCCD = false) { PX_ASSERT(gScene); PxRigidDynamic* dynamic = NULL; if(gScene) { dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); if(enableLinearCCD) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if(enableSpeculativeCCD) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); } return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent, bool enableLinearCCD = false, bool enableSpeculativeCCD = false) { PX_ASSERT(gScene); if(!gScene) return; PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); PX_ASSERT(shape); if(!shape) return; for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { const PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); if(enableLinearCCD) body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if(enableSpeculativeCCD) body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); gScene->addActor(*body); } } shape->release(); } static PxFilterFlags ccdFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(filterData0); PX_UNUSED(attributes1); PX_UNUSED(filterData1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); pairFlags = PxPairFlag::eSOLVE_CONTACT | PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eDETECT_CCD_CONTACT; return PxFilterFlags(); } static void registerForRaycastCCD(PxRigidDynamic* actor) { if(actor) { PxShape* shape = NULL; actor->getShapes(&shape, 1); // Register each object for which CCD should be enabled. In this snippet we only enable it for the sphere. gRaycastCCD->registerRaycastCCDObject(actor, shape); } } static void initScene() { PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; bool enableLinearCCD = false; bool enableSpeculativeCCD = false; const CCDAlgorithm ccd = getCCDAlgorithm(); if(ccd == LINEAR_CCD) { enableLinearCCD = true; sceneDesc.filterShader = ccdFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; gScene = gPhysics->createScene(sceneDesc); printf("- Using linear CCD.\n"); } else if(ccd == SPECULATIVE_CCD) { enableSpeculativeCCD = true; gScene = gPhysics->createScene(sceneDesc); printf("- Using speculative/angular CCD.\n"); } else if(ccd == FULL_CCD) { enableLinearCCD = true; enableSpeculativeCCD = true; sceneDesc.filterShader = ccdFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; gScene = gPhysics->createScene(sceneDesc); printf("- Using full CCD.\n"); } else if(ccd == RAYCAST_CCD) { gScene = gPhysics->createScene(sceneDesc); gRaycastCCD = new RaycastCCDManager(gScene); printf("- Using raycast CCD.\n"); } else if(ccd == NO_CCD) { gScene = gPhysics->createScene(sceneDesc); printf("- Using no CCD.\n"); } // Create a scenario that requires angular CCD: a rotating plank colliding with a falling box. { PxRigidDynamic* actor = createDynamic(PxTransform(PxVec3(40.0f, 20.0f, 0.0f)), PxBoxGeometry(10.0f, 1.0f, 0.1f), PxVec3(0.0f), enableLinearCCD, enableSpeculativeCCD); actor->setAngularVelocity(PxVec3(0.0f, 10.0f, 0.0f)); actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_X, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_Y, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_Z, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, true); if(gRaycastCCD) registerForRaycastCCD(actor); PxRigidDynamic* actor2 = createDynamic(PxTransform(PxVec3(40.0f, 20.0f, 10.0f)), PxBoxGeometry(0.1f, 1.0f, 1.0f), PxVec3(0.0f), enableLinearCCD, enableSpeculativeCCD); if(gRaycastCCD) registerForRaycastCCD(actor2); } // Create a scenario that requires linear CCD: a fast moving sphere moving towards a box stack. { PxRigidDynamic* actor = createDynamic(PxTransform(PxVec3(0.0f, 18.0f, 100.0f)), PxSphereGeometry(2.0f), PxVec3(0.0f, 0.0f, -1000.0f), enableLinearCCD, enableSpeculativeCCD); if(gRaycastCCD) registerForRaycastCCD(actor); createStack(PxTransform(PxVec3(0, 0, stackZ)), 10, 2.0f, enableLinearCCD, enableSpeculativeCCD); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); } PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F4 to select a scenario."); switch(PxU32(gScenario)) { case 0: { Snippets::print("Current scenario: linear CCD"); }break; case 1: { Snippets::print("Current scenario: angular CCD"); }break; case 2: { Snippets::print("Current scenario: linear + angular CCD"); }break; case 3: { Snippets::print("Current scenario: raycast CCD"); }break; case 4: { Snippets::print("Current scenario: no CCD"); }break; } #endif } void initPhysics(bool /*interactive*/) { printf("CCD snippet. Use these keys:\n"); printf(" P - enable/disable pause\n"); printf(" O - step simulation for one frame\n"); printf(" R - reset scene\n"); printf(" F1 to F4 - select scenes with different CCD algorithms\n"); printf(" F1 - Using linear CCD\n"); printf(" F2 - Using speculative/angular CCD\n"); printf(" F3 - Using full CCD (linear+angular)\n"); printf(" F4 - Using raycast CCD\n"); printf(" F5 - Using no CCD\n"); printf("\n"); gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); const PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.25f); initScene(); } void stepPhysics(bool /*interactive*/) { if (gPause && !gOneFrame) return; gOneFrame = false; gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); // Simply call this after fetchResults to perform CCD raycasts. if(gRaycastCCD) gRaycastCCD->doRaycastCCD(true); } static void releaseScene() { PX_RELEASE(gScene); PX_DELETE(gRaycastCCD); } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCCD done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key == 'p' || key == 'P') gPause = !gPause; if(key == 'o' || key == 'O') { gPause = true; gOneFrame = true; } if(gScene) { if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); } } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,270
C++
29.90932
185
0.721027
NVIDIA-Omniverse/PhysX/physx/snippets/snippetspatialtendon/SnippetSpatialTendonRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern PxRigidStatic** getAttachments(); extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 attachmentColor(0.25f, 1.0f, 0.5f); const PxVec3 tendonColor(0.8f); const PxVec3 dynLinkColor(1.0f, 0.5f, 0.25f); const PxVec3 baseLinkColor(0.5f, 0.25f, 1.0f); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbArticulations = scene->getNbArticulations(); for(PxU32 i = 0; i < nbArticulations; i++) { PxArticulationReducedCoordinate* articulation; scene->getArticulations(&articulation, 1, i); const PxU32 nbLinks = articulation->getNbLinks(); std::vector<PxArticulationLink*> links(nbLinks); articulation->getLinks(&links[0], nbLinks); const PxU32 numLinks = static_cast<PxU32>(links.size()); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[0]), 1, true, baseLinkColor); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[1]), numLinks - 1, true, dynLinkColor); } // render attachments and tendon connecting the attachments: Snippets::renderActors(reinterpret_cast<PxRigidActor**>(getAttachments()), 6, true, attachmentColor, NULL, false, false); Snippets::DrawLine(getAttachments()[0]->getGlobalPose().p, getAttachments()[1]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[0]->getGlobalPose().p, getAttachments()[2]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[3]->getGlobalPose().p, getAttachments()[4]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[3]->getGlobalPose().p, getAttachments()[5]->getGlobalPose().p, tendonColor); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { const PxVec3 camEye(0.0f, 4.3f, 5.2f); const PxVec3 camDir(0.0f, -0.27f, -1.0f); sCamera = new Snippets::Camera(camEye, camDir); Snippets::setupDefault("PhysX Snippet Articulation Spatial Tendon", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
4,077
C++
37.471698
122
0.753986
NVIDIA-Omniverse/PhysX/physx/snippets/snippetspatialtendon/SnippetSpatialTendon.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. // ***************************************************************************************** // This snippet demonstrates the use of a spatial tendon to actuate a symmetric articulation // ***************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulations[2] = { NULL }; static const PxReal gGravity = 9.81f; static const PxReal gLinkHalfLength = 0.5f; PxRigidStatic** getAttachments() { static PxRigidStatic* attachments[6] = { NULL }; return attachments; } static void createSpatialTendonArticulation(PxArticulationReducedCoordinate* articulation, PxRigidStatic** attachmentRigidStatics, const PxVec3 offset) { // link geometry and density: const PxVec3 linkExtents(gLinkHalfLength, 0.05f, 0.05f); const PxBoxGeometry linkGeom = PxBoxGeometry(linkExtents); const PxReal density = 1000.0f; articulation->setArticulationFlags(PxArticulationFlag::eFIX_BASE); articulation->setSolverIterationCounts(10, 1); PxTransform pose = PxTransform(offset, PxQuat(PxIdentity)); pose.p.y += 3.0f; PxArticulationLink* baseLink = articulation->createLink(NULL, pose); PxRigidActorExt::createExclusiveShape(*baseLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*baseLink, density); pose.p.x -= linkExtents.x * 2.0f; PxArticulationLink* leftLink = articulation->createLink(baseLink, pose); PxRigidActorExt::createExclusiveShape(*leftLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, density); pose.p.x += linkExtents.x * 4.0f; PxArticulationLink* rightLink = articulation->createLink(baseLink, pose); PxRigidActorExt::createExclusiveShape(*rightLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, density); // setup revolute joints: { PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); if(joint) { PxVec3 parentOffset(-linkExtents.x, 0.0f, 0.0f); PxVec3 childOffset(linkExtents.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } { PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); if(joint) { PxVec3 parentOffset(linkExtents.x, 0.0f, 0.0f); PxVec3 childOffset(-linkExtents.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } // tendon stiffness sizing: // scale articulation geometry: // r: root attachment on left moving link // a: attachment on fixed-base link // l: leaf attachment on right moving link // o: revolute joint // a // // ----r----o---------o----l---- // The root and leaf attachment are at the center of mass of the moving links. // The attachment on the fixed-base link is a link halfLength above the link. // Therefore, the (rest)length of the tendon r-a-l when both joints are at zero is: // 2 * sqrt((2 * gLinkHalfLength)^2 + gLinkHalfLength^2) = 2 * gLinkHalfLength * sqrt(5) const PxReal restLength = 2.0f * gLinkHalfLength * PxSqrt(5.0f); // The goal is to have the revolute joints deviate just a few degrees from the horizontal // and we compute the length of the tendon at that angle: const PxReal deviationAngle = 3.0f * PxPi / 180.0f; // Distances from the base-link attachment to the root and leaf attachments const PxReal verticalDistance = gLinkHalfLength * (1.0f + PxSin(deviationAngle)); const PxReal horizontalDistance = gLinkHalfLength * (1.0f + PxCos(deviationAngle)); const PxReal deviatedLength = 2.0f * PxSqrt(verticalDistance * verticalDistance + horizontalDistance * horizontalDistance); // At rest, the force on the leaf attachment is (deviatedLength - restLength) * tendonStiffness. // This force needs to be equal to the gravity force acting on the link. An equal and opposing // (in the direction of the tendon) force acts on the root link and will hold that link up. // In order to calculate the tendon stiffness that produces that force, we consider the forces // and attachment geometry at zero joint angles. const PxReal linkMass = baseLink->getMass(); const PxReal gravityForce = gGravity * linkMass; // Project onto tendon at rest length / with joints at zero angle const PxReal tendonForce = gravityForce * PxSqrt(5.0f); // gravityForce * 0.5f * restLength / halfLength // and compute stiffness to get tendon force at deviated length to hold the link: const PxReal tendonStiffness = tendonForce / (deviatedLength - restLength); const PxReal tendonDamping = 0.3f * tendonStiffness; PxArticulationSpatialTendon* tendon = articulation->createSpatialTendon(); tendon->setStiffness(tendonStiffness); tendon->setDamping(tendonDamping); PxArticulationAttachment* rootAttachment = tendon->createAttachment(NULL, 1.0f, PxVec3(0.0f), leftLink); PxArticulationAttachment* baseAttachment = tendon->createAttachment(rootAttachment, 1.0f, PxVec3(0.0f, gLinkHalfLength, 0.0f), baseLink); PxArticulationAttachment* leafAttachment = tendon->createAttachment(baseAttachment, 1.0f, PxVec3(0.0f), rightLink); leafAttachment->setRestLength(restLength); // create attachment render shapes attachmentRigidStatics[0] = gPhysics->createRigidStatic(baseLink->getGlobalPose() * PxTransform(PxVec3(0.0f, gLinkHalfLength, 0.0f), PxQuat(PxIdentity))); attachmentRigidStatics[1] = gPhysics->createRigidStatic(leftLink->getGlobalPose()); attachmentRigidStatics[2] = gPhysics->createRigidStatic(rightLink->getGlobalPose()); PxSphereGeometry attachmentGeom(linkExtents.y * 1.5f); // slightly bigger than links to see the attachment on the moving links PxShape* attachmentShape = gPhysics->createShape(attachmentGeom, *gMaterial, false, PxShapeFlags(0)); for(PxU32 i = 0; i < 3; ++i) { PxRigidStatic* attachment = attachmentRigidStatics[i]; attachment->setActorFlag(PxActorFlag::eDISABLE_SIMULATION, true); // attachments are viz only attachment->attachShape(*attachmentShape); } // add articulation to scene: gScene->addArticulation(*articulation); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -gGravity, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); gArticulations[0] = gPhysics->createArticulationReducedCoordinate(); createSpatialTendonArticulation(gArticulations[0], getAttachments(), PxVec3(0.0f)); gArticulations[1] = gPhysics->createArticulationReducedCoordinate(); createSpatialTendonArticulation(gArticulations[1], &getAttachments()[3], PxVec3(0.0f, 0.0f, 2.0f)); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; static PxReal time = 0.0f; // update articulation that actuates via tendon-length offset: { const PxReal amplitude = 0.3f; // move at 0.25 Hz, and offset sinusoid by an amplitude const PxReal offset = amplitude * (1.0f + PxSin(time * PxTwoPi * 0.25f - PxPiDivTwo)); PxArticulationSpatialTendon* tendon = NULL; gArticulations[0]->getSpatialTendons(&tendon, 1, 0); tendon->setOffset(offset); PxArticulationLink* links[3]; gArticulations[0]->getLinks(links, 3, 0); getAttachments()[1]->setGlobalPose(links[1]->getGlobalPose()); getAttachments()[2]->setGlobalPose(links[2]->getGlobalPose()); } // update articulation that actuates via base link attachment relative pose { const PxReal amplitude = 0.2f; // move at 0.25 Hz, and offset sinusoid by an amplitude const PxReal offset = gLinkHalfLength + amplitude * (1.0f + PxSin(time * PxTwoPi * 0.25f - PxPiDivTwo)); PxArticulationSpatialTendon* tendon = NULL; gArticulations[1]->getSpatialTendons(&tendon, 1, 0); PxArticulationAttachment* baseAttachment = NULL; tendon->getAttachments(&baseAttachment, 1, 1); baseAttachment->setRelativeOffset(PxVec3(0.f, offset, 0.f)); gArticulations[1]->wakeUp(); // wake up articulation (relative offset setting does not wake) PxArticulationLink* links[3]; gArticulations[1]->getLinks(links, 3, 0); PxTransform attachmentPose = links[0]->getGlobalPose(); attachmentPose.p.y += offset; getAttachments()[3]->setGlobalPose(attachmentPose); getAttachments()[4]->setGlobalPose(links[1]->getGlobalPose()); getAttachments()[5]->setGlobalPose(links[2]->getGlobalPose()); } gScene->simulate(dt); gScene->fetchResults(true); time += dt; } void cleanupPhysics(bool /*interactive*/) { gArticulations[0]->release(); gArticulations[1]->release(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetSpatialTendon done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,480
C++
43.575
155
0.744551
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTireVehicle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" #include "CustomTire.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a custom component for the tire model. // //See BaseVehicle for more details on the snippet code design. // class CustomTireVehicle : public DirectDriveVehicle , public CustomTireComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForCustomTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const CustomTireParams>& tireParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; actuationStates.setData(mBaseState.actuationStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); tireParams.setData(mTireParamsList); roadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); wheelRigidBody1DStates.setData(mBaseState.wheelRigidBody1dStates); tireGripStates.setData(mBaseState.tireGripStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); tireSlipStates.setData(mBaseState.tireSlipStates); tireCamberAngleStates.setData(mBaseState.tireCamberAngleStates); tireStickyStates.setData(mBaseState.tireStickyStates); tireForces.setData(mBaseState.tireForces); } //Parameters and states of the vehicle's custom tire. CustomTireParams mCustomTireParams[2]; //One shared parameter set for front and one for rear wheels. CustomTireParams* mTireParamsList[4]; }; }//namespace snippetvehicle2
5,094
C
45.318181
137
0.817236
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/VehicleMFTireData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VEHICLE_MF_TIRE_DATA_H #define VEHICLE_MF_TIRE_DATA_H #include "foundation/Px.h" #include "foundation/PxMath.h" #include "foundation/PxFlags.h" namespace physx { // requirement: has to return 0 for input 0 template<typename TFloat> PX_FORCE_INLINE PxI32 mfSignum(const TFloat v) { // note: -0.0 returns 0, so sign is lost. +-NaN not covered return (TFloat(0.0) < v) - (v < TFloat(0.0)); } /** \brief Parameters for the Magic Formula Tire Model shared by various components of the model. \note Contains derived parameters that need to be set as well before the model can be evaluated. The helper method mfTireComputeDerivedSharedParams() can be used to compute those parameters. */ template<typename TFloat> struct MFTireSharedParams { TFloat r0; /// wheel radius at no load (SI unit would be metre [m]) TFloat v0; /// reference velocity [m/s] (for normalization. Usually the speed at which measurements were taken, often /// 16.7m/s, i.e., 60km/h are used. SI unit would be metres per second [m/s]) TFloat fz0; /// nominal vertical load (for normalization. SI unit would be Newton [N]). Make sure to call /// mfTireComputeDerivedSharedParams() after changing this parameter. TFloat pi0; /// nominal inflation pressure (for normalization. SI unit would be Pascal [Pa]) TFloat epsilonV; /// small value to add to velocity at contact patch when dividing (to avoid division /// by 0 when vehicle is not moving) TFloat slipReductionLowVelocity; /// at low velocities the model is prone to show large oscillation. Scaling down the slip /// in such scenarios will reduce the oscillation. This parameter defines a threshold for /// the longitudinal velocity below which the divisor for the slip computation will be /// interpolated between the actual longitudinal velocity and the specified threshold. /// At 0 longitudinal velocity, slipReductionLowVelocity will be used as divisor. With /// growing longitudinal velocity, the interpolation weight for slipReductionLowVelocity /// will decrease fast (quadratic) and will show no effect for velocities above the threshold /// anymore. TFloat lambdaFz0; /// user scaling factor for nominal load. Make sure to call mfTireComputeDerivedSharedParams() after /// changing this parameter. TFloat lambdaK_alpha; /// user scaling factor for cornering stiffness TFloat aMu; /// parameter for degressive friction factor computation. Vertical shifts of the force curves /// should vanish slower when friction coefficients go to 0: (aMu * lambdaMu) / (1 + (aMu - 1) * lambdaMu). /// Choose 10 as a good default. Make sure to call mfTireComputeDerivedSharedParams() after changing this parameter. TFloat zeta0; /// scaling factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. TFloat zeta2; /// scaling factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. // derived parameters TFloat recipFz0; /// 1 / fz0. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat fz0Scaled; /// fz0 * lambdaFz0. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat recipFz0Scaled; /// 1 / fz0Scaled. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat aMuMinus1; /// aMu - 1. mfTireComputeDerivedSharedParams() can be used to compute this value. }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeDerivedSharedParams(MFTireSharedParams<TFloat>& sharedParams) { sharedParams.recipFz0 = TFloat(1.0) / sharedParams.fz0; sharedParams.fz0Scaled = sharedParams.fz0 * sharedParams.lambdaFz0; sharedParams.recipFz0Scaled = TFloat(1.0) / sharedParams.fz0Scaled; sharedParams.aMuMinus1 = sharedParams.aMu - TFloat(1.0); } template<typename TFloat> struct MFTireVolatileSharedParams { // gamma: camber angle // Fz: vertical load // Fz0Scaled: nominal vertical load (scaled by user scaling factor lambdaFz0) // pi: inflation pressure // pi0: nominal inflation pressure TFloat gamma; // camber angle (in radians) TFloat gammaSqr; // gamma^2 TFloat sinGamma; // sin(gamma) TFloat sinGammaAbs; // |sin(gamma)| TFloat sinGammaSqr; // sin(gamma)^2 TFloat fzNormalized; // Fz / Fz0 TFloat fzNormalizedWithScale; // Fz / Fz0Scaled TFloat dFz; // normalized change in vertical load: (Fz - Fz0Scaled) / Fz0Scaled TFloat dFzSqr; // dFz^2 TFloat dpi; // normalized inflation pressure change: (pi - pi0) / pi0 TFloat dpiSqr; // dpi^2 TFloat lambdaMu_longitudinal; /// scaling factor for longitudinal friction mu term and thus peak value. TFloat lambdaMu_lateral; /// scaling factor for lateral friction mu term and thus peak value. }; template<typename TConfig> PX_FORCE_INLINE void mfTireComputeVolatileSharedParams(const typename TConfig::Float gamma, const typename TConfig::Float fz, const typename TConfig::Float lambdaMu_longitudinal, const typename TConfig::Float lambdaMu_lateral, const typename TConfig::Float pi, const MFTireSharedParams<typename TConfig::Float>& sharedParams, MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { if (TConfig::supportCamber) { volatileSharedParams.gamma = gamma; volatileSharedParams.gammaSqr = gamma * gamma; volatileSharedParams.sinGamma = PxSin(gamma); volatileSharedParams.sinGammaAbs = PxAbs(volatileSharedParams.sinGamma); volatileSharedParams.sinGammaSqr = volatileSharedParams.sinGamma * volatileSharedParams.sinGamma; } volatileSharedParams.fzNormalized = fz * sharedParams.recipFz0; volatileSharedParams.fzNormalizedWithScale = fz * sharedParams.recipFz0Scaled; volatileSharedParams.dFz = (fz - sharedParams.fz0Scaled) * sharedParams.recipFz0Scaled; volatileSharedParams.dFzSqr = volatileSharedParams.dFz * volatileSharedParams.dFz; volatileSharedParams.lambdaMu_longitudinal = lambdaMu_longitudinal; volatileSharedParams.lambdaMu_lateral = lambdaMu_lateral; if (TConfig::supportInflationPressure) { volatileSharedParams.dpi = (pi - sharedParams.pi0) / sharedParams.pi0; volatileSharedParams.dpiSqr = volatileSharedParams.dpi * volatileSharedParams.dpi; } } template<typename TFloat> struct MFTireLongitudinalForcePureParams { /** @name magic formula: B (through longitudinal slip stiffness K) */ /**@{*/ TFloat pK1; /// longitudinal slip stiffness (per load unit) Guidance: for many tires /// (almost) linearly dependent on the vertical force. Typically, in the /// range of 14 to 18. May be much higher for racing tires. TFloat pK2; /// variation of slip stiffness (per load unit) with load change TFloat pK3; /// exponential variation of slip stiffness with load change TFloat pp1; /// variation of slip stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat pp2; /// variation of slip stiffness with inflation pressure change squared /// (set to 0 to ignore effect) TFloat lambdaK; /// user scaling factor for slip stiffness TFloat epsilon; /// small value to avoid division by 0 if load is 0. The scale of the values /// the epsilon gets added to is similar to the scale of the longitudinal force. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat pC1; /// shape factor. Guidance: value has to be larger or equal to 1, for example, 1.6 /// is a fair starting point. TFloat lambdaC; /// user scaling factor for shape factor /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat pD1; /// friction mu term (per load unit). Guidance: for highly loaded tires /// the value is below 1, for example around 0.8 on a dry surface. High /// performance tires on racing cars may reach 1.5 or even 2.0 in extreme /// cases. TFloat pD2; /// variation of friction mu term (per load unit) with load change. /// Guidance: normally below 0 (typically between -0.1 and 0.0). Generally, /// pD2 is larger than the counterpart in MFTireLateralForcePureParams. TFloat pD3; /// variation of friction mu term with camber angle squared /// (set to 0 to ignore effect) TFloat pp3; /// variation of friction mu term with inflation pressure change /// (set to 0 to ignore effect) TFloat pp4; /// variation of friction mu term with inflation pressure change squared /// (set to 0 to ignore effect) //TFloat lambdaMu; // user scaling factor for friction mu term (and thus peak value). // (see MFTireVolatileSharedParams::lambdaMu_longitudinal) TFloat zeta1; /// scaling factor for friction mu term to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat pE1; /// curvature factor. Guidance: value has to be smaller or equal to 1. An /// increasing negative value will make the curve more peaky. 0 is a /// fair starting point. TFloat pE2; /// variation of curvature factor with load change TFloat pE3; /// variation of curvature factor with load change squared TFloat pE4; /// scaling factor for curvature factor depending on signum /// of shifted longitudinal slip ratio (to create asymmetry under drive/brake /// torque: 1.0 - pE4*sgn(slipRatioShifted). No effect when no slip) TFloat lambdaE; /// user scaling factor for curvature factor /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat pH1; /// horizontal shift at nominal load TFloat pH2; /// variation of horizontal shift with load change TFloat lambdaH; /// user scaling factor for horizontal shift /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat pV1; /// vertical shift (per load unit) TFloat pV2; /// variation of vertical shift (per load unit) with load change TFloat lambdaV; /// user scaling factor for vertical shift //TFloat lambdaMu; // user scaling factor for vertical shift (peak friction coefficient). See magic formula: D //TFloat zeta1; // scaling factor for vertical shift to take turn slip into account. See magic formula: D /**@}*/ }; template<typename TFloat> struct MFTireLongitudinalForceCombinedParams { /** @name magic formula: B */ /**@{*/ TFloat rB1; /// curvature factor at force reduction peak. Guidance: 8.3 may be used as a starting point. TFloat rB2; /// variation of curvature factor at force reduction peak with longitudinal slip ratio. /// Guidance: 5.0 may be used as a starting point. TFloat rB3; /// variation of curvature factor at force reduction peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaAlpha; /// user scaling factor for influence of lateral slip angle alpha on longitudinal force /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat rC1; /// shape factor. Guidance: 0.9 may be used as a starting point. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat rE1; /// long range falloff at nominal load TFloat rE2; /// variation of long range falloff with load change /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat rH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. /**@}*/ }; template<typename TFloat> struct MFTireLateralForcePureParams { /** @name magic formula: B (through cornering stiffness K_alpha) */ /**@{*/ TFloat pK1; /// maximum cornering stiffness (per load unit) Guidance: values between /// 10 and 20 can be expected (or higher for racing tires). Note: beware of /// the sign when copying values from data sources. If the ISO sign /// convention is used for the tire model, negative values will be seen. TFloat pK2; /// scaling factor for load at which cornering stiffness reaches maximum. /// Guidance: typically, in a range of 1.5 to 3. TFloat pK3; /// variation of cornering stiffness with sine of camber angle /// (set to 0 to ignore effect) TFloat pK4; /// shape factor to control limit and thus shape of stiffness curve /// Guidance: typical value is 2 (especially, if camber angle is 0). TFloat pK5; /// scaling factor (depending on squared sine of camber angle) for load at which /// cornering stiffness reaches maximum /// (set to 0 to ignore effect) TFloat pp1; /// variation of cornering stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat pp2; /// scaling factor (depending on inflation pressure change) for load at which /// cornering stiffness reaches maximum /// (set to 0 to ignore effect) //TFloat lambdaK_alpha; // user scaling factor for cornering stiffness (see MFTireSharedParams::lambdaK_alpha) TFloat epsilon; /// small value to avoid division by 0 if load is 0. The scale of the values /// the epsilon gets added to is similar to the scale of the lareral force. TFloat zeta3; /// scaling factor for cornering stiffness to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat pC1; /// shape factor. Guidance: value has to be larger or equal to 1, for example, 1.3 /// is a fair starting point. TFloat lambdaC; /// user scaling factor for shape factor /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat pD1; /// friction mu term (per load unit). Guidance: for highly loaded tires /// the value is below 1, for example around 0.8 on a dry surface. High /// performance tires on racing cars may reach 1.5 or even 2.0 in extreme /// cases. TFloat pD2; /// variation of friction mu term (per load unit) with load change. /// Guidance: normally below 0 (typically between -0.1 and 0.0). Generally, /// pD2 is smaller than the counterpart in MFTireLongitudinalForcePureParams. TFloat pD3; /// variation of friction mu term with squared sine of camber angle /// (set to 0 to ignore effect) TFloat pp3; /// variation of friction mu term with inflation pressure change /// (set to 0 to ignore effect) TFloat pp4; /// variation of friction mu term with inflation pressure change squared /// (set to 0 to ignore effect) //TFloat lambdaMu; // user scaling factor for friction mu term (and thus peak value). // (see MFTireVolatileSharedParams::lambdaMu_lateral) //TFloat zeta2; // scaling factor for friction mu term to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat pE1; /// curvature factor. Guidance: value has to be smaller or equal to 1. An /// increasing negative value will make the curve more peaky. 0 is a /// fair starting point. TFloat pE2; /// variation of curvature factor with load change TFloat pE3; /// scaling factor for curvature factor depending on signum /// of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip). /// Set to 0 for a symmetric tire. TFloat pE4; /// variation of curvature factor with sine of camber angle and signum /// of shifted slip angle. /// (set to 0 to ignore effect) TFloat pE5; /// variation of curvature factor with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaE; /// user scaling factor for curvature factor /**@}*/ /** @name magic formula: Sh (with a camber stiffness term K_gamma) */ /**@{*/ TFloat pH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. TFloat pH2; /// variation of horizontal shift with load change. Set to 0 for a symmetric tire. TFloat pK6; /// camber stiffness (per load unit) /// (set to 0 to ignore effect) TFloat pK7; /// variation of camber stiffness (per load unit) with load change /// (set to 0 to ignore effect) TFloat pp5; /// variation of camber stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat lambdaH; /// user scaling factor for horizontal shift //TFloat lambdaK_gamma; // user scaling factor for horizontal shift of camber stiffness term // (no effect if camber angle is 0). // See magic formula: Sv TFloat epsilonK; /// small value to avoid division by 0 in case cornering stiffness is 0 /// (due to load being 0, for example). The scale of the values the /// epsilon gets added to is similar to the scale of the lareral force /// multiplied by the slope/stiffness when slip angle is approaching 0. //TFloat zeta0; // scaling factor for camber stiffness term to take turn slip into account. // See MFTireSharedParams::zeta0. TFloat zeta4; /// horizontal shift term to take turn slip and camber into account. /// If path radius is large and camber small, it can be set to 1 (since 1 gets /// subtracted this will result in a 0 term). /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat pV1; /// vertical shift (per load unit). Set to 0 for a symmetric tire. TFloat pV2; /// variation of vertical shift (per load unit) with load change. Set to 0 for a symmetric tire. TFloat pV3; /// vertical shift (per load unit) depending on sine of camber angle /// (set to 0 to ignore effect) TFloat pV4; /// variation of vertical shift (per load unit) with load change depending on sine /// of camber angle (set to 0 to ignore effect) TFloat lambdaV; /// user scaling factor for vertical shift TFloat lambdaK_gamma; /// user scaling factor for vertical shift depending on sine of camber angle //TFloat lambdaMu; // user scaling factor for vertical shift (peak friction coefficient). See magic formula: D //TFloat zeta2; // scaling factor for vertical shift to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ }; template<typename TFloat> struct MFTireLateralForceCombinedParams { /** @name magic formula: B */ /**@{*/ TFloat rB1; /// curvature factor at force reduction peak. Guidance: 4.9 may be used as a starting point. TFloat rB2; /// variation of curvature factor at force reduction peak with lateral slip /// Guidance: 2.2 may be used as a starting point. TFloat rB3; /// shift term for lateral slip. rB2 gets applied to shifted slip. Set to 0 for a symmetric tire. TFloat rB4; /// variation of curvature factor at force reduction peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaKappa; /// user scaling factor for influence of longitudinal slip ratio kappa on lateral force /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat rC1; /// shape factor. Guidance: 1.0 may be used as a starting point. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat rE1; /// long range falloff at nominal load TFloat rE2; /// variation of long range falloff with load change /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat rH1; /// horizontal shift at nominal load TFloat rH2; /// variation of horizontal shift with load change /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat rV1; /// vertical shift (per load unit). Set to 0 for a symmetric tire. TFloat rV2; /// variation of vertical shift (per load unit) with load change. Set to 0 for a symmetric tire. TFloat rV3; /// variation of vertical shift (per load unit) with sine of camber angle /// (set to 0 to ignore effect) TFloat rV4; /// variation of vertical shift (per load unit) with lateral slip angle TFloat rV5; /// variation of vertical shift (per load unit) with longitudinal slip ratio TFloat rV6; /// variation of vertical shift (per load unit) with arctan of longitudinal slip ratio TFloat lambdaV; /// user scaling factor for vertical shift //TFloat zeta2; // scaling factor for vertical shift to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ }; template<typename TFloat> struct MFTireAligningTorqueVolatileSharedParams { // alpha: slip angle // Vcx: longitudinal velocity at contact patch // Vc: velocity at contact patch (longitudinal and lateral combined) TFloat cosAlpha; // cos(slip angle) = Vcx / (Vc + epsilon) (signed value of Vcx allows to support backwards running) TFloat signumVc_longitudinal; // signum of longitudinal velocity at contact patch }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeAligningTorqueVolatileSharedParams(const TFloat vc, const TFloat vc_longitudinal, const TFloat epsilon, MFTireAligningTorqueVolatileSharedParams<TFloat>& volatileSharedParams) { volatileSharedParams.cosAlpha = vc_longitudinal / (vc + epsilon); volatileSharedParams.signumVc_longitudinal = static_cast<TFloat>(mfSignum(vc_longitudinal)); } template<typename TFloat> struct MFTireAligningTorquePurePneumaticTrailParams { /** @name magic formula: B */ /**@{*/ TFloat qB1; /// curvature factor at pneumatic trail peak (at nominal load) TFloat qB2; /// variation of curvature factor at pneumatic trail peak with load change TFloat qB3; /// variation of curvature factor at pneumatic trail peak with load change squared TFloat qB5; /// variation of curvature factor at pneumatic trail peak with sine of camber angle /// (set to 0 to ignore effect) TFloat qB6; /// variation of curvature factor at pneumatic trail peak with squared sine of camber angle /// (set to 0 to ignore effect) //TFloat lambdaK_alpha; // user scaling factor for curvature factor at pneumatic trail peak // (see MFTireSharedParams::lambdaK_alpha) //TFloat lambdaMu; // inverse user scaling factor for curvature factor at pneumatic trail peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat qC1; /// shape factor (has to be greater than 0) /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat qD1; /// pneumatic trail peak (per normalized load-torque unit) TFloat qD2; /// variation of pneumatic trail peak (per normalized load-torque unit) with load change TFloat qD3; /// variation of pneumatic trail peak with sine of camber angle /// (set to 0 to ignore effect). Set to 0 for a symmetric tire. TFloat qD4; /// variation of pneumatic trail peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat pp1; /// variation of pneumatic trail peak with inflation pressure change /// (set to 0 to ignore effect) TFloat lambdaT; /// user scaling factor for pneumatic trail peak TFloat zeta5; /// scaling factor for pneumatic trail peak to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat qE1; /// long range falloff at nominal load TFloat qE2; /// variation of long range falloff with load change TFloat qE3; /// variation of long range falloff with load change squared TFloat qE4; /// scaling factor for long range falloff depending on sign /// of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip). /// Set to 0 for a symmetric tire. TFloat qE5; /// scaling factor for long range falloff depending on sine of camber /// angle and sign of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip. /// Set to 0 to ignore effect) /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat qH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. TFloat qH2; /// variation of horizontal shift with load change. Set to 0 for a symmetric tire. TFloat qH3; /// horizontal shift at nominal load depending on sine of camber angle /// (set to 0 to ignore effect) TFloat qH4; /// variation of horizontal shift with load change depending on sine of camber angle /// (set to 0 to ignore effect) /**@}*/ }; template<typename TFloat> struct MFTireAligningTorquePureResidualTorqueParams { /** @name magic formula: B */ /**@{*/ TFloat qB9; /// curvature factor at residual torque peak TFloat qB10; /// curvature factor at residual torque peak (multiplier for B*C term of lateral force under pure slip) //TFloat lambdaK_alpha; // user scaling factor for curvature factor at residual torque peak // (see MFTireSharedParams::lambdaK_alpha) //TFloat lambdaMu; // inverse user scaling factor for curvature factor at residual torque peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) TFloat zeta6; /// scaling factor for curvature factor at residual torque peak to take turn slip /// into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat zeta7; /// shape factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat qD6; /// residual torque peak (per load-torque unit). Set to 0 for a symmetric tire. TFloat qD7; /// variation of residual torque peak (per load-torque unit) with load change. /// Set to 0 for a symmetric tire. TFloat qD8; /// residual torque peak (per load-torque unit) depending on sine of camber angle /// (set to 0 to ignore effect) TFloat qD9; /// variation of residual torque peak (per load-torque unit) with load /// change and depending on sine of camber angle (set to 0 to ignore effect) TFloat qD10; /// residual torque peak (per load-torque unit) depending on signed square of /// sine of camber angle (set to 0 to ignore effect) TFloat qD11; /// variation of residual torque peak (per load-torque unit) with load /// change and depending on signed square of sine of camber angle /// (set to 0 to ignore effect) TFloat pp2; /// variation of residual torque peak with inflation pressure change and depending /// on sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaR; /// user scaling factor for residual torque peak TFloat lambdaK_gamma; /// user scaling factor for residual torque peak depending on sine of camber angle //TFloat lambdaMu; // user scaling factor for residual torque peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) //TFloat zeta0; // scaling factor for residual torque peak to take turn slip into account. // See MFTireSharedParams::zeta0. //TFloat zeta2; // scaling factor for residual torque peak to take turn slip into account. // See MFTireSharedParams::zeta2. TFloat zeta8; /// additional term for residual torque peak to take turn slip into account. /// If path radius is large and camber small, it can be set to 1 (since 1 gets /// subtracted this will result in a 0 term). /**@}*/ }; template<typename TFloat> struct MFTireAligningTorqueCombinedParams { TFloat sS1; /// effect (per radius unit) of longitudinal force on aligning torque. Set to 0 for a symmetric tire. TFloat sS2; /// effect (per radius unit) of longitudinal force on aligning torque with lateral force TFloat sS3; /// effect (per radius unit) of longitudinal force on aligning torque with sine of camber angle TFloat sS4; /// effect (per radius unit) of longitudinal force on aligning torque with sine of camber angle and load change TFloat lambdaS; /// user scaling factor for effect of longitudinal force on aligning torque }; template<typename TFloat> struct MFTireFreeRotatingRadiusParams { TFloat qre0; /// scaling factor for unloaded tire radius. Guidance: set to 1 if no adaptation to measurements are needed. TFloat qV1; /// increase of radius (per length unit) with normalized velocity squared (the tire radius grows /// due to centrifugal force) }; /** \brief Parameters for the Magic Formula Tire Model related to vertical tire stiffness. \note Contains derived parameters that need to be set as well before the model can be evaluated. The helper method mfTireComputeDerivedVerticalTireStiffnessParams() can be used to compute those parameters. */ template<typename TFloat> struct MFTireVerticalStiffnessParams { TFloat qF1; /// vertical tire stiffness (per load unit and normalized tire deflection (deflection / unloaded radius)). /// If qF2 is set to 0 and the vertical tire stiffness c0 is known, qF1 can be computed as c0 * r0 / F0 /// (r0: unloaded tire radius, F0: nominal tire load). TFloat qF2; /// vertical tire stiffness (per load unit and normalized tire deflection squared) TFloat ppF1; /// variation of vertical tire stiffness with inflation pressure change /// (set to 0 to ignore effect). Guidance: suggested value range is between 0.7 and 0.9. TFloat lambdaC; /// user scaling factor for vertical tire stiffness. // derived parameters TFloat c0; /// vertical tire stiffness at nominal vertical load, nominal inflation pressure, no tangential forces and /// zero forward velocity. mfTireComputeDerivedVerticalTireStiffnessParams() can be used to compute the value. }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeDerivedVerticalTireStiffnessParams(const TFloat r0, const TFloat fz0, MFTireVerticalStiffnessParams<TFloat>& params) { params.c0 = params.lambdaC * (fz0 / r0) * PxSqrt((params.qF1 * params.qF1) + (TFloat(4.0) * params.qF2)); } template<typename TFloat> struct MFTireEffectiveRollingRadiusParams { TFloat Freff; /// tire compression force (per load unit), linear part. Guidance: for radial tires a value /// around 0.01 is suggested, for bias ply tires a value around 0.333. TFloat Dreff; /// scaling factor for tire compression force, non-linear part. Guidance: for radial tires /// a value around 0.24 is suggested, for bias ply tires a value of 0. TFloat Breff; /// gradient of tire compression force, non-linear part. Guidance: for radial tires a value /// around 8 is suggested, for bias ply tires a value of 0. }; template<typename TFloat> struct MFTireNormalLoadParams { TFloat qV2; /// variation of normal load (per load unit) with normalized longitudinal velocity from tire rotation TFloat qFc_longitudinal; /// decrease of normal load (per load unit) with normalized longitudinal force squared. /// Can be considered optional (set to 0) for passenger car tires but should be considered for racing /// tires. TFloat qFc_lateral; /// decrease of normal load (per load unit) with normalized lateral force squared. /// Can be considered optional (set to 0) for passenger car tires but should be considered for racing /// tires. //TFloat qF1; // see MFTireVerticalStiffnessParams::qF1 //TFloat qF2; // see MFTireVerticalStiffnessParams::qF2 TFloat qF3; /// vertical tire stiffness (per load unit and normalized tire deflection (deflection / unloaded radius)) /// depending on camber angle squared (set to 0 to ignore effect) //TFloat ppF1; // see MFTireVerticalStiffnessParams::ppF1 }; struct MFTireDataFlag { enum Enum { eALIGNING_MOMENT = 1 << 0 /// Compute the aligning moment of the tire. }; }; template<typename TFloat> struct MFTireDataT { MFTireDataT() : flags(0) { } MFTireSharedParams<TFloat> sharedParams; MFTireFreeRotatingRadiusParams<TFloat> freeRotatingRadiusParams; MFTireVerticalStiffnessParams<TFloat> verticalStiffnessParams; MFTireEffectiveRollingRadiusParams<TFloat> effectiveRollingRadiusParams; MFTireNormalLoadParams<TFloat> normalLoadParams; MFTireLongitudinalForcePureParams<TFloat> longitudinalForcePureParams; MFTireLongitudinalForceCombinedParams<TFloat> longitudinalForceCombinedParams; MFTireLateralForcePureParams<TFloat> lateralForcePureParams; MFTireLateralForceCombinedParams<TFloat> lateralForceCombinedParams; MFTireAligningTorquePureResidualTorqueParams<TFloat> aligningTorquePureResidualTorqueParams; MFTireAligningTorquePurePneumaticTrailParams<TFloat> aligningTorquePurePneumaticTrailParams; MFTireAligningTorqueCombinedParams<TFloat> aligningTorqueCombinedParams; PxFlags<MFTireDataFlag::Enum, PxU32> flags; }; } // namespace physx #endif //VEHICLE_MF_TIRE_DATA_H
34,801
C
48.788269
140
0.698514
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/VehicleMFTire.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VEHICLE_MF_TIRE_H #define VEHICLE_MF_TIRE_H #include "foundation/Px.h" #include "foundation/PxAssert.h" #include "foundation/PxMath.h" #include "VehicleMFTireData.h" namespace physx { template<typename TFloat> struct MFTireOverturningCoupleParams { TFloat qS1; /// overturning couple (per load-torque unit). Set to 0 for a symmetric tire. TFloat qS2; /// variation of overturning couple (per load-torque unit) with camber angle /// (set to 0 to ignore effect) TFloat qS3; /// variation of overturning couple (per load-torque unit) with normalized lateral force TFloat qS4; /// peak of sine * cosine type contribution TFloat qS5; /// shape factor of cosine type contribution depending on normalized load TFloat qS6; /// curvature factor of cosine type contribution depending on normalized load TFloat qS7; /// horizontal shift of sine type contribution depending on camber angle /// (set to 0 to ignore effect) TFloat qS8; /// shape factor of sine type contribution depending on normalized lateral force TFloat qS9; /// stiffness factor of sine type contribution depending on normalized lateral force TFloat qS10; /// shape factor of arctan type contribution depending on normalized load /// and camber angle /// (set to 0 to ignore effect) TFloat qS11; /// stiffness factor of arctan type contribution depending on normalized load /// and camber angle /// (set to 0 to ignore effect) TFloat ppM1; /// variation of camber angle dependent overturning couple with inflation pressure change /// (set to 0 to ignore effect) /// (no effect if camber angle is 0) TFloat lambdaVM; /// user scaling factor for overturning couple coefficient TFloat lambdaM; /// user scaling factor for overturning couple }; template<typename TFloat> struct MFTireRollingResistanceMomentParams { TFloat qS1; /// rolling resistance moment (per load-torque unit) TFloat qS2; /// variation of rolling resistance moment with normalized longitudinal force TFloat qS3; /// variation of rolling resistance moment with normalized longitudinal velocity TFloat qS4; /// variation of rolling resistance moment with normalized longitudinal velocity to the power of 4 TFloat qS5; /// variation of rolling resistance moment with camber angle squared /// (set to 0 to ignore effect) TFloat qS6; /// variation of rolling resistance moment with camber angle squared and normalized load /// (set to 0 to ignore effect) TFloat qS7; /// variation of rolling resistance moment with normalized load to the power of qS7 TFloat qS8; /// variation of rolling resistance moment with normalized inflation pressure to the power of qS8 /// (set to 0 to ignore effect) TFloat lambdaM; /// user scaling factor for rolling resistance moment }; //#define MF_ARCTAN(x) PxAtan(x) #define MF_ARCTAN(x) mfApproximateArctan(x) // more than 10% speedup could be seen template <typename TFloat> PX_FORCE_INLINE TFloat mfApproximateArctan(TFloat x) { const TFloat absX = PxAbs(x); const TFloat a = TFloat(1.1); const TFloat b = TFloat(1.6); const TFloat nom = x * ( TFloat(1.0) + (a * absX) ); const TFloat denom = TFloat(1.0) + ( (TFloat(2.0)/TFloat(PxPi)) * ((b*absX) + (a*x*x)) ); const TFloat result = nom / denom; return result; } PX_FORCE_INLINE PxF32 mfExp(PxF32 x) { return PxExp(x); } PX_FORCE_INLINE PxF64 mfExp(PxF64 x) { return exp(x); } PX_FORCE_INLINE PxF32 mfPow(PxF32 base, PxF32 exponent) { return PxPow(base, exponent); } PX_FORCE_INLINE PxF64 mfPow(PxF64 base, PxF64 exponent) { return pow(base, exponent); } template<typename TFloat> TFloat mfMagicFormulaSine(const TFloat x, const TFloat B, const TFloat C,const TFloat D, const TFloat E) { // // Magic Formula (sine version) // // y(x) = D * sin[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // y // ^ // | // | / // | / // | / // | / __________ // | / ____/ ^ \_____________ // | / ___/ | \_____________________________________ y(x) // | / __/ | // | /_/ | // | / | // | / | // | / | D // | / | // | / | // | / | // | /--- arctan(B*C*D) | // | / \ | // |/ | v // ------------/---------------------------------------------------------------------------------------------> x // /| // / | // / | // / | // // ---------------------------------------------------------------------------------------------------------------- // B: stiffness factor (tune slope at the origin) // ---------------------------------------------------------------------------------------------------------------- // C: shape factor (controls limits and thus general shape of the curve) // ---------------------------------------------------------------------------------------------------------------- // D: peak value (for C >= 1) // ---------------------------------------------------------------------------------------------------------------- // E: curvature factor (controls curvature at peak and horizontal position of peak) // ---------------------------------------------------------------------------------------------------------------- // const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat Dpart = D * PxSin(Cpart); return Dpart; } template<typename TFloat> TFloat mfMagicFormulaCosine(const TFloat x, const TFloat B, const TFloat C,const TFloat D, const TFloat E) { /* // Magic Formula (cosine version) // // y(x) = D * cos[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // y // ^ // | // | // ____|____ // ____/ ^ \____ // ___/ | \___ y(x) // __/ | \__ // _/ | \_ // / | D \ // _/ | \_ // __/ | \__ // ___/ | \___ // ____/ v \____ // ---_____/-------------------------------------------------------------------\_____------------------------> x ^ // __/ | ^ \______ | -ya // | | \_____________ v // | x0 -------------- // | // | // // ---------------------------------------------------------------------------------------------------------------- // B: curvature factor (controls curvature at peak) // ---------------------------------------------------------------------------------------------------------------- // C: shape factor (controls limit ya and thus general shape of the curve) // ---------------------------------------------------------------------------------------------------------------- // D: peak value (for C >= 1) // ---------------------------------------------------------------------------------------------------------------- // E: controls shape at larger values and controls location x0 of intersection with x-axis // ---------------------------------------------------------------------------------------------------------------- */ const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat Dpart = D * PxCos(Cpart); return Dpart; } template<typename TFloat> TFloat mfMagicFormulaCosineNoD(const TFloat x, const TFloat B, const TFloat C,const TFloat E) { // // Magic Formula (cosine version without D factor) // // y(x) = cos[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // see magicFormulaCosine() for some information // const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat result = PxCos(Cpart); return result; } template<typename TFloat> TFloat mfMagicFormulaCosineNoE(const TFloat x, const TFloat B, const TFloat C,const TFloat D) { // // Magic Formula (cosine version without E factor) // // y(x) = D * cos[ C * arctan{ B*x } ] // // see magicFormulaCosine() for some information // const TFloat Bpart = B * x; const TFloat Cpart = C * MF_ARCTAN( Bpart ); const TFloat Dpart = D * PxCos(Cpart); return Dpart; } // Vertical shifts of the longitudinal/lateral force curves should vanish slower when friction coefficients go to 0 template<typename TFloat> PX_FORCE_INLINE TFloat mfTireDegressiveFriction(const TFloat lambdaMu, const TFloat aMu, const TFloat aMuMinus1) { const TFloat lambdaMuDegressive = (aMu * lambdaMu) / ( TFloat(1.0) + (aMuMinus1 * lambdaMu) ); return lambdaMuDegressive; } /** \brief Longitudinal force at pure longitudinal slip \note Ignores interdependency with lateral force (in other words, tire rolling on a straight line with no slip angle [alpha = 0]) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load. fz >= 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] sharedParams Model parameters not just used for longitudinal force \param[in] volatileSharedParams Model parameters not just used for longitudinal force \param[out] K_kappa Magic formula longitudinal slip stiffness factor K \return Longitudinal force. */ template<typename TConfig> typename TConfig::Float mfTireLongitudinalForcePure(const typename TConfig::Float kappa, const typename TConfig::Float fz, const MFTireLongitudinalForcePureParams<typename TConfig::Float>& params, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& K_kappa) { typedef typename TConfig::Float TFloat; // magic formula: // x: longitudinal slip ratio (kappa) // y(x): longitudinal force // // magic formula: Sh; horizontal shift // const TFloat Sh = ( params.pH1 + (params.pH2 * volatileSharedParams.dFz) ) * params.lambdaH; // // magic formula: Sv; vertical shift // const TFloat lambdaMuDegressive = mfTireDegressiveFriction(volatileSharedParams.lambdaMu_longitudinal, sharedParams.aMu, sharedParams.aMuMinus1); TFloat Sv = fz * ( params.pV1 + (params.pV2 * volatileSharedParams.dFz) ) * params.lambdaV * lambdaMuDegressive; if (TConfig::supportTurnSlip) Sv *= params.zeta1; // // // const TFloat kappaShifted = kappa + Sh; // // magic formula: C; shape factor // const TFloat C = params.pC1 * params.lambdaC; PX_ASSERT(C > TFloat(0.0)); // // magic formula: D; peak value // TFloat mu = (params.pD1 + (params.pD2 * volatileSharedParams.dFz)) * volatileSharedParams.lambdaMu_longitudinal; if (TConfig::supportCamber) { const TFloat mu_camberFactor = TFloat(1.0) - (params.pD3 * volatileSharedParams.gammaSqr); mu *= mu_camberFactor; } if (TConfig::supportInflationPressure) { const TFloat mu_inflationPressureFactor = TFloat(1.0) + (params.pp3 * volatileSharedParams.dpi) + (params.pp4 * volatileSharedParams.dpiSqr); mu *= mu_inflationPressureFactor; } TFloat D = mu * fz; if (TConfig::supportTurnSlip) D *= params.zeta1; PX_ASSERT(D >= TFloat(0.0)); // // magic formula: E; curvature factor // const TFloat E = ( params.pE1 + (params.pE2*volatileSharedParams.dFz) + (params.pE3*volatileSharedParams.dFzSqr) ) * ( TFloat(1.0) - (params.pE4*mfSignum(kappaShifted)) ) * params.lambdaE; PX_ASSERT(E <= TFloat(1.0)); // // longitudinal slip stiffness // TFloat K = fz * (params.pK1 + (params.pK2 * volatileSharedParams.dFz)) * mfExp(params.pK3 * volatileSharedParams.dFz) * params.lambdaK; if (TConfig::supportInflationPressure) { const TFloat K_inflationPressureFactor = TFloat(1.0) + (params.pp1 * volatileSharedParams.dpi) + (params.pp2 * volatileSharedParams.dpiSqr); K *= K_inflationPressureFactor; } K_kappa = K; // // magic formula: B; stiffness factor // const TFloat B = K / ((C*D) + params.epsilon); // // resulting force // const TFloat F = mfMagicFormulaSine(kappaShifted, B, C, D, E) + Sv; return F; } /** \brief Longitudinal force with combined slip \note Includes the interdependency with lateral force \param[in] kappa Longitudinal slip ratio. \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fx0 The longitudinal force at pure longitudinal slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for longitudinal force \return Longitudinal force. @see mfTireLongitudinalForcePure() */ template<typename TConfig> typename TConfig::Float mfTireLongitudinalForceCombined(const typename TConfig::Float kappa, const typename TConfig::Float tanAlpha, const typename TConfig::Float fx0, const MFTireLongitudinalForceCombinedParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = params.rH1; // // // const TFloat tanAlphaShifted = tanAlpha + Sh; // // magic formula: B; curvature factor // TFloat B = params.rB1; if (TConfig::supportCamber) { const TFloat B_term_camber = params.rB3 * volatileSharedParams.sinGammaSqr; B += B_term_camber; } const TFloat B_cosFactor = PxCos(MF_ARCTAN(params.rB2 * kappa)); B *= B_cosFactor * params.lambdaAlpha; PX_ASSERT(B > TFloat(0.0)); // // magic formula: C; shape factor // const TFloat C = params.rC1; // // magic formula: E; // const TFloat E = params.rE1 + (params.rE2*volatileSharedParams.dFz); PX_ASSERT(E <= TFloat(1.0)); // // resulting force // const TFloat G0 = mfMagicFormulaCosineNoD(Sh, B, C, E); PX_ASSERT(G0 > TFloat(0.0)); const TFloat G = mfMagicFormulaCosineNoD(tanAlphaShifted, B, C, E) / G0; PX_ASSERT(G > TFloat(0.0)); const TFloat F = G * fx0; return F; } /** \brief Lateral force at pure lateral/side slip \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fz Vertical load (force). fz >= 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] sharedParams Model parameters not just used for lateral force \param[in] volatileSharedParams Model parameters not just used for lateral force \param[in,out] fy0NoCamberNoTurnSlip If not NULL, the lateral force discarding camber and turn slip (basically, the resulting force if both were 0) will be written to the pointer target. \param[out] B_out Magic formula stiffnes factor B \param[out] C_out Magic formula shape factor C \param[out] K_alpha_withEpsilon_out Magic formula cornering stiffness factor K with a small epsilon added to avoid divison by 0. \param[out] Sh_out Magic formula horizontal shift Sh \param[out] Sv_out Magic formula vertical shift Sv \param[out] mu_zeta2_out The friction factor multiplied by MFTireSharedParams::zeta2. Will be needed when computing the lateral force with combined slip. \return Lateral force. */ template<typename TConfig> typename TConfig::Float mfTireLateralForcePure(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const MFTireLateralForcePureParams<typename TConfig::Float>& params, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float* fy0NoCamberNoTurnSlip, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& K_alpha_withEpsilon_out, typename TConfig::Float& Sh_out, typename TConfig::Float& Sv_out, typename TConfig::Float& mu_zeta2_out) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): lateral force // // magic formula: Sv; vertical shift // const TFloat lambdaMuDegressive = mfTireDegressiveFriction(volatileSharedParams.lambdaMu_lateral, sharedParams.aMu, sharedParams.aMuMinus1); const TFloat fz_x_lambdaMuDegressive = fz * lambdaMuDegressive; const TFloat Sv_term_noCamber_noTurnSlip = fz_x_lambdaMuDegressive * ( params.pV1 + (params.pV2 * volatileSharedParams.dFz) ) * params.lambdaV; TFloat Sv = Sv_term_noCamber_noTurnSlip; if (TConfig::supportTurnSlip) { Sv *= sharedParams.zeta2; } TFloat Sv_term_camber; if (TConfig::supportCamber) { Sv_term_camber = fz_x_lambdaMuDegressive * ( params.pV3 + (params.pV4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma * params.lambdaK_gamma; if (TConfig::supportTurnSlip) { Sv_term_camber *= sharedParams.zeta2; } Sv += Sv_term_camber; } // note: fz_x_lambdaMuDegressive and zeta2 are not pulled out because Sv_term_camber // is needed for Sh computation and Sv_term_noCamber_noTurnSlip for lateralForceNoCamberNoTurnSlip Sv_out = Sv; // // cornering stiffness // const TFloat corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip = params.pK1 * sharedParams.fz0Scaled * sharedParams.lambdaK_alpha; TFloat corneringStiffnessPeak = corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip; if (TConfig::supportCamber) { const TFloat corneringStiffnessPeak_camberFactor = TFloat(1.0) - (params.pK3 * volatileSharedParams.sinGammaAbs); corneringStiffnessPeak *= corneringStiffnessPeak_camberFactor; } if (TConfig::supportTurnSlip) { corneringStiffnessPeak *= params.zeta3; } TFloat corneringStiffnessPeak_inflationPressureFactor; if (TConfig::supportInflationPressure) { corneringStiffnessPeak_inflationPressureFactor = TFloat(1.0) + (params.pp1 * volatileSharedParams.dpi); corneringStiffnessPeak *= corneringStiffnessPeak_inflationPressureFactor; } const TFloat loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber = params.pK2; TFloat loadAtCorneringStiffnessPeak = loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber; if (TConfig::supportCamber) { const TFloat loadAtCorneringStiffnessPeak_term_camber = params.pK5 * volatileSharedParams.sinGammaSqr; loadAtCorneringStiffnessPeak += loadAtCorneringStiffnessPeak_term_camber; } TFloat loadAtCorneringStiffnessPeak_inflationPressureFactor; if (TConfig::supportInflationPressure) { loadAtCorneringStiffnessPeak_inflationPressureFactor = TFloat(1.0) + (params.pp2 * volatileSharedParams.dpi); loadAtCorneringStiffnessPeak *= loadAtCorneringStiffnessPeak_inflationPressureFactor; } const TFloat K_alpha = corneringStiffnessPeak * PxSin( params.pK4 * MF_ARCTAN(volatileSharedParams.fzNormalizedWithScale / loadAtCorneringStiffnessPeak) ); const TFloat K_alpha_withEpsilon = K_alpha + params.epsilonK; K_alpha_withEpsilon_out = K_alpha_withEpsilon; // // magic formula: Sh; horizontal shift // const TFloat Sh_term_noCamber_noTurnSlip = ( params.pH1 + (params.pH2 * volatileSharedParams.dFz) ) * params.lambdaH; TFloat Sh = Sh_term_noCamber_noTurnSlip; if (TConfig::supportCamber) { TFloat K_gamma = fz * ( params.pK6 + (params.pK7 * volatileSharedParams.dFz) ) * params.lambdaK_gamma; if (TConfig::supportInflationPressure) { const TFloat K_gamma_inflationPressureFactor = TFloat(1.0) + (params.pp5 * volatileSharedParams.dpi); K_gamma *= K_gamma_inflationPressureFactor; } TFloat Sh_term_camber = ( (K_gamma * volatileSharedParams.sinGamma) - Sv_term_camber ) / K_alpha_withEpsilon; if (TConfig::supportTurnSlip) { Sh_term_camber *= sharedParams.zeta0; } Sh += Sh_term_camber; } if (TConfig::supportTurnSlip) { Sh += params.zeta4 - TFloat(1.0); } Sh_out = Sh; // // // const TFloat tanAlphaShifted = tanAlpha + Sh; // // magic formula: C; shape factor // const TFloat C = params.pC1 * params.lambdaC; PX_ASSERT(C > TFloat(0.0)); C_out = C; // // magic formula: D; peak value // TFloat mu_noCamber_noTurnSlip = (params.pD1 + (params.pD2 * volatileSharedParams.dFz)) * volatileSharedParams.lambdaMu_lateral; if (TConfig::supportInflationPressure) { const TFloat mu_inflationPressureFactor = TFloat(1.0) + (params.pp3 * volatileSharedParams.dpi) + (params.pp4 * volatileSharedParams.dpiSqr); mu_noCamber_noTurnSlip *= mu_inflationPressureFactor; } TFloat mu = mu_noCamber_noTurnSlip; if (TConfig::supportCamber) { const TFloat mu_camberFactor = TFloat(1.0) - (params.pD3 * volatileSharedParams.sinGammaSqr); mu *= mu_camberFactor; } if (TConfig::supportTurnSlip) { mu *= sharedParams.zeta2; } mu_zeta2_out = mu; const TFloat D = mu * fz; PX_ASSERT(D >= TFloat(0.0)); // // magic formula: E; curvature factor // const TFloat E_noCamber_noSignum = ( params.pE1 + (params.pE2*volatileSharedParams.dFz) ) * params.lambdaE; TFloat E = E_noCamber_noSignum; if (TConfig::supportCamber) { const TFloat E_camberFactor = TFloat(1.0) - ( (params.pE3 + (params.pE4 * volatileSharedParams.sinGamma)) * mfSignum(tanAlphaShifted) ) + (params.pE5 * volatileSharedParams.sinGammaSqr); E *= E_camberFactor; } else { const TFloat E_signumFactor = TFloat(1.0) - ( params.pE3 * mfSignum(tanAlphaShifted) ); E *= E_signumFactor; } PX_ASSERT(E <= TFloat(1.0)); // // magic formula: B; stiffness factor // const TFloat B = K_alpha / ((C*D) + params.epsilon); B_out = B; // // resulting force // const TFloat F = mfMagicFormulaSine(tanAlphaShifted, B, C, D, E) + Sv; if (fy0NoCamberNoTurnSlip) { if (TConfig::supportCamber || TConfig::supportTurnSlip) { const TFloat D_noCamber_noTurnSlip = mu_noCamber_noTurnSlip * fz; PX_ASSERT(D_noCamber_noTurnSlip >= TFloat(0.0)); const TFloat tanAlphaShifted_noCamber_noTurnSlip = tanAlpha + Sh_term_noCamber_noTurnSlip; TFloat corneringStiffnessPeak_noCamber_noTurnSlip = corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip; TFloat loadAtCorneringStiffnessPeak_noCamber = loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber; if (TConfig::supportInflationPressure) { corneringStiffnessPeak_noCamber_noTurnSlip *= corneringStiffnessPeak_inflationPressureFactor; loadAtCorneringStiffnessPeak_noCamber *= loadAtCorneringStiffnessPeak_inflationPressureFactor; } const TFloat K_alpha_noCamber_noTurnSlip = corneringStiffnessPeak_noCamber_noTurnSlip * PxSin( params.pK4 * MF_ARCTAN(volatileSharedParams.fzNormalizedWithScale / loadAtCorneringStiffnessPeak_noCamber) ); const TFloat B_noCamber_noTurnSlip = K_alpha_noCamber_noTurnSlip / ((C*D_noCamber_noTurnSlip) + params.epsilon); const TFloat E_noCamber = E_noCamber_noSignum * ( TFloat(1.0) - (params.pE3 * mfSignum(tanAlphaShifted_noCamber_noTurnSlip)) ); PX_ASSERT(E_noCamber <= TFloat(1.0)); *fy0NoCamberNoTurnSlip = mfMagicFormulaSine(tanAlphaShifted_noCamber_noTurnSlip, B_noCamber_noTurnSlip, C, D_noCamber_noTurnSlip, E_noCamber) + Sv_term_noCamber_noTurnSlip; } else { *fy0NoCamberNoTurnSlip = F; } } return F; } /** \brief Lateral force with combined slip \note Includes the interdependency with longitudinal force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load (force). fz >= 0. \param[in] fy0 The lateral force at pure lateral slip. \param[in] mu_zeta2 The friction factor computed as part of the lateral force at pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for lateral force \param[in,out] fy0WeightNoCamberNoTurnSlip If not NULL, the weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0), will be written to the pointer target. \return Lateral force. @see mfTireLateralForcePure() */ template<typename TConfig> typename TConfig::Float mfTireLateralForceCombined(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappa, const typename TConfig::Float fz, const typename TConfig::Float fy0, const typename TConfig::Float mu_zeta2, const MFTireLateralForceCombinedParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float* fy0WeightNoCamberNoTurnSlip) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = params.rH1 + (params.rH2*volatileSharedParams.dFz); // // magic formula: Sv; vertical shift // TFloat DV = params.rV1 + (params.rV2*volatileSharedParams.dFz); if (TConfig::supportCamber) { const TFloat DV_term_camber = params.rV3 * volatileSharedParams.sinGamma; DV += DV_term_camber; } const TFloat DV_cosFactor = PxCos(MF_ARCTAN(params.rV4 * tanAlpha)); DV *= mu_zeta2 * fz * DV_cosFactor; const TFloat Sv_sinFactor = PxSin(params.rV5 * MF_ARCTAN(params.rV6 * kappa)); const TFloat Sv = DV * Sv_sinFactor * params.lambdaV; // // // const TFloat kappaShifted = kappa + Sh; // // magic formula: B; curvature factor // const TFloat B_term_noCamber = params.rB1; TFloat B = B_term_noCamber; if (TConfig::supportCamber) { const TFloat B_term_camber = params.rB4 * volatileSharedParams.sinGammaSqr; B += B_term_camber; } const TFloat B_cosFactor = PxCos(MF_ARCTAN(params.rB2 * (tanAlpha - params.rB3))); const TFloat B_cosFactor_lambdaKappa = B_cosFactor * params.lambdaKappa; B *= B_cosFactor_lambdaKappa; PX_ASSERT(B > TFloat(0.0)); // // magic formula: C; shape factor // const TFloat C = params.rC1; // // magic formula: E; // const TFloat E = params.rE1 + (params.rE2*volatileSharedParams.dFz); PX_ASSERT(E <= TFloat(1.0)); // // resulting force // const TFloat G0 = mfMagicFormulaCosineNoD(Sh, B, C, E); PX_ASSERT(G0 > TFloat(0.0)); TFloat G = mfMagicFormulaCosineNoD(kappaShifted, B, C, E) / G0; if (G < TFloat(0.0)) { // at very low velocity (or starting from standstill), the longitudinal slip ratio can get // large which can result in negative values G = TFloat(0.0); } const TFloat F = (G * fy0) + Sv; if (fy0WeightNoCamberNoTurnSlip) { if (TConfig::supportCamber || TConfig::supportTurnSlip) { const TFloat B_noCamber = B_term_noCamber * B_cosFactor_lambdaKappa; PX_ASSERT(B_noCamber > TFloat(0.0)); const TFloat G0_noCamber = mfMagicFormulaCosineNoD(Sh, B_noCamber, C, E); PX_ASSERT(G0_noCamber > TFloat(0.0)); TFloat G_noCamber = mfMagicFormulaCosineNoD(kappaShifted, B_noCamber, C, E) / G0_noCamber; if (G_noCamber < TFloat(0.0)) G_noCamber = TFloat(0.0); *fy0WeightNoCamberNoTurnSlip = G_noCamber; } else { *fy0WeightNoCamberNoTurnSlip = G; } } return F; } template<typename TConfig> void mfTireComputeAligningTorquePneumaticTrailIntermediateParams(const typename TConfig::Float tanAlpha, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& tanAlphaShifted_out, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& D_out, typename TConfig::Float& E_out) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // TFloat Sh = params.qH1 + (params.qH2 * volatileSharedParams.dFz); if (TConfig::supportCamber) { const TFloat Sh_term_camber = ( params.qH3 + (params.qH4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma; Sh += Sh_term_camber; } // // // const TFloat tanAlphaShifted = tanAlpha + Sh; tanAlphaShifted_out = tanAlphaShifted; // // magic formula: B; curvature factor // TFloat B = ( params.qB1 + (params.qB2 * volatileSharedParams.dFz) + (params.qB3 * volatileSharedParams.dFzSqr) ) * (sharedParams.lambdaK_alpha / volatileSharedParams.lambdaMu_lateral); if (TConfig::supportCamber) { const TFloat B_camberFactor = TFloat(1.0) + (params.qB5 * volatileSharedParams.sinGammaAbs) + (params.qB6 * volatileSharedParams.sinGammaSqr); B *= B_camberFactor; } PX_ASSERT(B > TFloat(0.0)); B_out = B; // // magic formula: C; shape factor // const TFloat C = params.qC1; PX_ASSERT(C > TFloat(0.0)); C_out = C; // // magic formula: D; peak value // TFloat D = volatileSharedParams.fzNormalizedWithScale * sharedParams.r0 * (params.qD1 + (params.qD2 * volatileSharedParams.dFz)) * params.lambdaT * volatileSharedParamsAligningTorque.signumVc_longitudinal; if (TConfig::supportInflationPressure) { const TFloat D_inflationPressureFactor = TFloat(1.0) - (params.pp1 * volatileSharedParams.dpi); D *= D_inflationPressureFactor; } if (TConfig::supportCamber) { const TFloat D_camberFactor = TFloat(1.0) + (params.qD3 * volatileSharedParams.sinGammaAbs) + (params.qD4 * volatileSharedParams.sinGammaSqr); D *= D_camberFactor; } if (TConfig::supportTurnSlip) { D *= params.zeta5; } D_out = D; // // magic formula: E; // TFloat E = params.qE1 + (params.qE2*volatileSharedParams.dFz) + (params.qE3*volatileSharedParams.dFzSqr); TFloat E_arctanFactor = params.qE4; if (TConfig::supportCamber) { const TFloat E_arctanFactor_term_camber = params.qE5 * volatileSharedParams.sinGamma; E_arctanFactor += E_arctanFactor_term_camber; } E_arctanFactor = TFloat(1.0) + ( E_arctanFactor * (TFloat(2.0) / TFloat(PxPi)) * MF_ARCTAN(B*C*tanAlphaShifted) ); E *= E_arctanFactor; PX_ASSERT(E <= TFloat(1.0)); E_out = E; } /** \brief Aligning torque at pure lateral/side slip (pneumatic trail term) The lateral/side forces act a small distance behind the center of the contact patch. This distance is called the pneumatic trail. The pneumatic trail decreases with increasing slip angle. The pneumatic trail increases with vertical load. The pneumatic trail causes a torque that turns the wheel away from the direction of turn. \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just pneumatic trail term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (pneumatic trail term). */ template<typename TConfig> typename TConfig::Float mfTireAligningTorquePurePneumaticTrail(const typename TConfig::Float tanAlpha, const typename TConfig::Float fy0NoCamberNoTurnSlip, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): pneumatic trail TFloat tanAlphaShifted, B, C, D, E; mfTireComputeAligningTorquePneumaticTrailIntermediateParams<TConfig>(tanAlpha, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D, E); // // pneumatic trail // const TFloat t = mfMagicFormulaCosine(tanAlphaShifted, B, C, D, E) * volatileSharedParamsAligningTorque.cosAlpha; // // resulting torque // const TFloat Mz = -t * fy0NoCamberNoTurnSlip; return Mz; } /** \brief Aligning torque with combined slip (pneumatic trail term) \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappaScaledSquared Longitudinal slip ratio scaled by the ratio of longitudinalStiffness and lateralStiffness and then squared \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] fy0NoCamberNoTurnSlipWeight The weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just pneumatic trail term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (pneumatic trail term). @see mfTireAligningTorquePurePneumaticTrail */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombinedPneumaticTrail(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappaScaledSquared, const typename TConfig::Float fy0NoCamberNoTurnSlip, const typename TConfig::Float fy0NoCamberNoTurnSlipWeight, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): pneumatic trail TFloat tanAlphaShifted, B, C, D, E; mfTireComputeAligningTorquePneumaticTrailIntermediateParams<TConfig>(tanAlpha, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D, E); const TFloat tanAlphaShiftedCombined = PxSqrt( tanAlphaShifted*tanAlphaShifted + kappaScaledSquared ) * mfSignum(tanAlphaShifted); const TFloat fyNoCamberNoTurnSlip = fy0NoCamberNoTurnSlipWeight * fy0NoCamberNoTurnSlip; // // pneumatic trail // const TFloat t = mfMagicFormulaCosine(tanAlphaShiftedCombined, B, C, D, E) * volatileSharedParamsAligningTorque.cosAlpha; // // resulting torque // const TFloat Mz = -t * fyNoCamberNoTurnSlip; return Mz; } template<typename TConfig> void mfTireComputeAligningTorqueResidualTorqueIntermediateParams(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& tanAlphaShifted_out, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& D_out) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = Sh_lateral + ( Sv_lateral / K_alpha_withEpsilon ); // // // tanAlphaShifted_out = tanAlpha + Sh; // // magic formula: B; curvature factor // TFloat B = ( params.qB9 * (sharedParams.lambdaK_alpha / volatileSharedParams.lambdaMu_lateral) ) + ( params.qB10 * B_lateral * C_lateral ); if (TConfig::supportTurnSlip) { B *= params.zeta6; } B_out = B; // // magic formula: C; shape factor // if (TConfig::supportTurnSlip) { C_out = params.zeta7; } else { C_out = TFloat(1.0); } // // magic formula: D; peak value // TFloat D = (params.qD6 + (params.qD7 * volatileSharedParams.dFz)) * params.lambdaR; if (TConfig::supportTurnSlip) { D *= sharedParams.zeta2; } if (TConfig::supportCamber) { TFloat D_term_camber = params.qD8 + (params.qD9 * volatileSharedParams.dFz); if (TConfig::supportInflationPressure) { const TFloat D_term_camber_inflationPressureFactor = TFloat(1.0) + (params.pp2 * volatileSharedParams.dpi); D_term_camber *= D_term_camber_inflationPressureFactor; } D_term_camber += ( params.qD10 + (params.qD11 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGammaAbs; D_term_camber *= volatileSharedParams.sinGamma * params.lambdaK_gamma; if (TConfig::supportTurnSlip) { D_term_camber *= sharedParams.zeta0; } D += D_term_camber; } D *= fz * sharedParams.r0 * volatileSharedParams.lambdaMu_lateral * volatileSharedParamsAligningTorque.signumVc_longitudinal * volatileSharedParamsAligningTorque.cosAlpha; if (TConfig::supportTurnSlip) { D += params.zeta8 - TFloat(1.0); } D_out = D; } /** \brief Aligning torque at pure lateral/side slip (residual torque term) Residual torque is produced by assymetries of the tire and the asymmetrical shape and pressure distribution of the contact patch etc. \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fz Vertical load (force). fz >= 0. \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just residual torque term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (residual torque term). */ template<typename TConfig> typename TConfig::Float mfTireAligningTorquePureResidualTorque(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): residual torque TFloat tanAlphaShifted, B, C, D; mfTireComputeAligningTorqueResidualTorqueIntermediateParams<TConfig>(tanAlpha, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D); // // residual torque // const TFloat Mz = mfMagicFormulaCosineNoE(tanAlphaShifted, B, C, D) * volatileSharedParamsAligningTorque.cosAlpha; return Mz; } /** \brief Aligning torque with combined slip (residual torque term) \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappaScaledSquared Longitudinal slip ratio scaled by the ratio of longitudinalStiffness and lateralStiffness and then squared \param[in] fz Vertical load (force). fz >= 0. \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just residual torque term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (residual torque term). @see mfTireAligningTorquePureResidualTorque() */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombinedResidualTorque(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappaScaledSquared, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): residual torque TFloat tanAlphaShifted, B, C, D; mfTireComputeAligningTorqueResidualTorqueIntermediateParams<TConfig>(tanAlpha, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D); const TFloat tanAlphaShiftedCombined = PxSqrt( tanAlphaShifted*tanAlphaShifted + kappaScaledSquared ) * mfSignum(tanAlphaShifted); // // residual torque // const TFloat Mz = mfMagicFormulaCosineNoE(tanAlphaShiftedCombined, B, C, D) * volatileSharedParamsAligningTorque.cosAlpha; return Mz; } /** \brief Aligning torque with combined longitudinal/lateral slip \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load (force). fz >= 0. \param[in] fx Longitudinal force with combined slip. \param[in] fy Lateral force with combined slip. \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] fy0NoCamberNoTurnSlipWeight The weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0). \param[in] K_kappa Longitudinal slip stiffness in magic formula for longitudinal force under pure longitudinal slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] pneumaticTrailParams The nondimensional model parameters and user scaling factors used for the pneumatic trail term of aligning torque. \param[in] residualTorqueParams The nondimensional model parameters and user scaling factors used for the residual torque term of aligning torque. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque. \param[in] sharedParams Model parameters not just used for aligning torque. \param[in] volatileSharedParams Model parameters not just used for aligning torque. \return Aligning torque. */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombined(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappa, const typename TConfig::Float fz, const typename TConfig::Float fx, const typename TConfig::Float fy, const typename TConfig::Float fy0NoCamberNoTurnSlip, const typename TConfig::Float fy0NoCamberNoTurnSlipWeight, const typename TConfig::Float K_kappa, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& pneumaticTrailParams, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& residualTorqueParams, const MFTireAligningTorqueCombinedParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; const TFloat kappaScaled = kappa * (K_kappa / K_alpha_withEpsilon); const TFloat kappaScaledSquared = kappaScaled * kappaScaled; const TFloat Mzp = mfTireAligningTorqueCombinedPneumaticTrail<TConfig>(tanAlpha, kappaScaledSquared, fy0NoCamberNoTurnSlip, fy0NoCamberNoTurnSlipWeight, pneumaticTrailParams, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams); const TFloat Mzr = mfTireAligningTorqueCombinedResidualTorque<TConfig>(tanAlpha, kappaScaledSquared, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, residualTorqueParams, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams); TFloat s = params.sS1 + ( params.sS2 * (fy * sharedParams.recipFz0Scaled) ); if (TConfig::supportCamber) { const TFloat s_term_camber = ( params.sS3 + (params.sS4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma; s += s_term_camber; } s *= sharedParams.r0 * params.lambdaS; const TFloat Mz = Mzp + Mzr + (s * fx); return Mz; } /** \brief Overturning couple \param[in] fz Vertical load (force). fz >= 0. \param[in] r0 Tire radius under no load. \param[in] fyNormalized Normalized lateral force (fy/fz0, fz0=nominal vertical load). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for overturning couple \return Overturning couple (torque). */ template<typename TConfig> typename TConfig::Float mfTireOverturningCouple(const typename TConfig::Float fz, const typename TConfig::Float r0, const typename TConfig::Float fyNormalized, const MFTireOverturningCoupleParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; TFloat Mx = params.qS1 * params.lambdaVM; if (TConfig::supportCamber) { TFloat Mx_term_camber = params.qS2 * volatileSharedParams.gamma; if (TConfig::supportInflationPressure) { const TFloat Mx_term_camber_inflationPressureFactor = TFloat(1.0) + (params.ppM1 * volatileSharedParams.dpi); Mx_term_camber *= Mx_term_camber_inflationPressureFactor; } Mx -= Mx_term_camber; } const TFloat Mx_term_lateral = params.qS3 * fyNormalized; Mx += Mx_term_lateral; const TFloat atanLoad = MF_ARCTAN(params.qS6 * volatileSharedParams.fzNormalized); const TFloat Mx_cosFactor = PxCos(params.qS5 * atanLoad * atanLoad); TFloat Mx_sinFactor = params.qS8 * MF_ARCTAN(params.qS9 * fyNormalized); if (TConfig::supportCamber) { const TFloat Mx_sinFactor_term_camber = params.qS7 * volatileSharedParams.gamma; Mx_sinFactor += Mx_sinFactor_term_camber; } Mx_sinFactor = PxSin(Mx_sinFactor); Mx += params.qS4 * Mx_cosFactor * Mx_sinFactor; if (TConfig::supportCamber) { const TFloat Mx_term_atan = params.qS10 * MF_ARCTAN(params.qS11 * volatileSharedParams.fzNormalized) * volatileSharedParams.gamma; Mx += Mx_term_atan; } Mx *= fz * r0 * params.lambdaM; return Mx; } /** \brief Rolling resistance moment Deformation of the wheel and the road surface usually results in a loss of energy as some of the deformation remains (not fully elastic). Furthermore, slippage between wheel and surface dissipates energy too. The rolling resistance moment models the force that will make a free rolling wheel stop. Note that similar to sliding friction, rolling resistance is often expressed as a coefficient times the normal force (but is generally much smaller than the coefficient of sliding friction). \param[in] fz Vertical load (force). fz >= 0. \param[in] r0 Tire radius under no load. \param[in] fxNormalized Normalized longitudinal force (fx/fz0, fz0=nominal vertical load). \param[in] vxNormalized Normalized longitudinal velocity (vx/v0, v0=reference velocity). \param[in] piNormalized Normalized tire inflation pressure (pi/pi0, pi0=nominal tire inflation pressure). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for rolling resistance moment \return Rolling resistance moment. */ template<typename TConfig> typename TConfig::Float mfTireRollingResistanceMoment(const typename TConfig::Float fz, const typename TConfig::Float r0, const typename TConfig::Float fxNormalized, const typename TConfig::Float vxNormalized, const typename TConfig::Float piNormalized, const MFTireRollingResistanceMomentParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // // rolling resistance force Fr: // // Fr = cr * Fn // // cr: rolling resistance coefficient // Fn: normal force // // Given a drive/break moment Md, part of Md will flow into the longitudinal force and a part into the // rolling resistance moment: // // Md = My + Fx*Rl // // My: rolling resistance moment My (with respect to contact patch) // Fx: longitudinal force at contact patch // Rl: loaded wheel radius // // The rolling resistance moment My can be derived from this: // // My = Fr*Re + Fx*(Re-Rl) // = (Fr+Fx)*Re - Fx*Rl // // Re: effective rolling radius of wheel // const TFloat absVxNormalized = PxAbs(vxNormalized); const TFloat vxNormalizedSqr = absVxNormalized * absVxNormalized; const TFloat vxNormalizedPow4 = vxNormalizedSqr * vxNormalizedSqr; TFloat My = params.qS1 + (params.qS2 * fxNormalized) + (params.qS3 * absVxNormalized) + (params.qS4 * vxNormalizedPow4); if (TConfig::supportCamber) { const TFloat My_term_camber = ( params.qS5 + (params.qS6 * volatileSharedParams.fzNormalized) ) * volatileSharedParams.gammaSqr; My += My_term_camber; } if (volatileSharedParams.fzNormalized > TFloat(0.0)) { TFloat My_powFactor = mfPow(volatileSharedParams.fzNormalized, params.qS7); if (TConfig::supportInflationPressure) { if (piNormalized > TFloat(0.0)) { const TFloat My_powFactor_inflationPressureFactor = mfPow(piNormalized, params.qS8); My_powFactor *= My_powFactor_inflationPressureFactor; } else return TFloat(0.0); } My *= My_powFactor; } else return TFloat(0.0); My *= fz * r0 * params.lambdaM; return My; } /** \brief Free radius of rotating tire The free tire radius of the rotating tire when taking centrifugal growth into account. \param[in] r0 Tire radius under no load. \param[in] omega Tire angular velocity. \param[in] v0 Reference velocity (for normalization. Usually the speed at which measurements were taken, often 16.7m/s, i.e., 60km/h) \param[in] params The nondimensional model parameters. \param[out] normalizedVelR0 Normalized longitudinal velocity due to rotation at unloaded radius (omega * r0 / v0). \return Free radius of rotating tire. */ template<typename TFloat> PX_FORCE_INLINE TFloat mfTireFreeRotatingRadius(const TFloat r0, const TFloat omega, const TFloat v0, const MFTireFreeRotatingRadiusParams<TFloat>& params, TFloat& normalizedVelR0) { const TFloat normalizedVel = (r0 * omega) / v0; normalizedVelR0 = normalizedVel; const TFloat normalizedVelSqr = normalizedVel * normalizedVel; const TFloat rOmega = r0 * ( params.qre0 + (params.qV1*normalizedVelSqr) ); return rOmega; } /** \brief Vertical tire stiffness \param[in] dpi Normalized inflation pressure change: (pi - pi0) / pi0 (with inflation pressure pi and nominal inflation pressure pi0). \param[in] params The nondimensional and derived model parameters. \return Vertical tire stiffness. */ template<typename TConfig> PX_FORCE_INLINE typename TConfig::Float mfTireVerticalStiffness(const typename TConfig::Float dpi, const MFTireVerticalStiffnessParams<typename TConfig::Float>& params) { typedef typename TConfig::Float TFloat; TFloat c = params.c0; if (TConfig::supportInflationPressure) { const TFloat c_inflationPressureFactor = TFloat(1.0) + (params.ppF1 * dpi); c *= c_inflationPressureFactor; } return c; } /** \brief Effective rolling radius The effective rolling radius (re) is the radius that matches the angular velocity (omega) and the velocity at the contact patch (V) under free rolling conditions (no drive/break torque), i.e., re = V / omega. This radius is bounded by the free tire radius of the rotating tire on one end and the loaded tire radius on the other end. The effective rolling radius changes with the load (fast for low values of load but only marginally at higher load values). \param[in] rOmega The free tire radius of the rotating tire when taking centrifugal growth into account. \param[in] cz Vertical stiffness of the tire. \param[in] fz0 Nominal vertical load (force). fz0 >= 0. \param[in] fzNormalized Normalized vertical load: fz / fz0. fzNormalized >= 0. \param[in] params The nondimensional model parameters. \return Effective rolling radius. */ template<typename TFloat> PX_FORCE_INLINE TFloat mfTireEffectiveRollingRadius(const TFloat rOmega, const TFloat cz, const TFloat fz0, const TFloat fzNormalized, const MFTireEffectiveRollingRadiusParams<TFloat>& params) { // // effective rolling radius // const TFloat B_term = params.Breff * fzNormalized; const TFloat D_term = params.Dreff * MF_ARCTAN(B_term); const TFloat F_term = (params.Freff * fzNormalized) + D_term; const TFloat re = rOmega - (fz0 * (F_term / cz)); return re; } /** \brief Normal load of the tire \param[in] fz0 Nominal vertical load (force). fz0 >= 0. \param[in] normalizedVelR0 Normalized longitudinal velocity due to rotation at unloaded radius (omega * r0 / v0, omega: tire angular velocity, r0: unloaded radius, v0: reference velocity for normalization) \param[in] r0 Tire radius under no load. \param[in] fxNormalized Normalized longitudinal force (fx/fz0). \param[in] fyNormalized Normalized lateral force (fy/fz0). \param[in] gammaSqr Camber angle squared. \param[in] deflection Tire normal deflection (difference between free rolling radius and loaded radius). \param[in] dpi Normalized inflation pressure change: (pi - pi0) / pi0 (with inflation pressure pi and nominal inflation pressure pi0). \param[in] params The nondimensional model parameters. \param[in] verticalStiffnessParams The nondimensional model parameters for vertical tire stiffness. \return Normal load (force) of the tire. */ template<typename TConfig> typename TConfig::Float mfTireNormalLoad(const typename TConfig::Float fz0, const typename TConfig::Float normalizedVelR0, const typename TConfig::Float r0, const typename TConfig::Float fxNormalized, const typename TConfig::Float fyNormalized, const typename TConfig::Float gammaSqr, const typename TConfig::Float deflection, const typename TConfig::Float dpi, const MFTireNormalLoadParams<typename TConfig::Float>& params, const MFTireVerticalStiffnessParams<typename TConfig::Float>& verticalStiffnessParams) { typedef typename TConfig::Float TFloat; const TFloat F_term_vel = params.qV2 * PxAbs(normalizedVelR0); const TFloat F_term_long = params.qFc_longitudinal * fxNormalized; const TFloat F_term_longSqr = F_term_long * F_term_long; const TFloat F_term_lat = params.qFc_lateral * fyNormalized; const TFloat F_term_latSqr = F_term_lat * F_term_lat; TFloat F_term_deflection = verticalStiffnessParams.qF1; if (TConfig::supportCamber) { const TFloat F_term_deflection_term_camber = params.qF3 * gammaSqr; F_term_deflection += F_term_deflection_term_camber; } const TFloat normalizedDeflection = deflection / r0; const TFloat F_deflectionFactor = ( F_term_deflection + (verticalStiffnessParams.qF2 * normalizedDeflection) ) * normalizedDeflection; TFloat F = (TFloat(1.0) + F_term_vel - F_term_longSqr - F_term_latSqr) * F_deflectionFactor; if (TConfig::supportInflationPressure) { const TFloat F_inflationPressureFactor = TFloat(1.0) + (verticalStiffnessParams.ppF1 * dpi); F *= F_inflationPressureFactor; } F *= fz0; return F; } template<typename TConfig> PX_FORCE_INLINE typename TConfig::Float mfTireComputeLoad( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float wheelOmega, const typename TConfig::Float tireDeflection, const typename TConfig::Float gammaSqr, const typename TConfig::Float longTireForce, const typename TConfig::Float latTireForce, const typename TConfig::Float tireInflationPressure) { typedef typename TConfig::Float TFloat; PX_ASSERT(tireDeflection >= TFloat(0.0)); const TFloat longTireForceNormalized = longTireForce * tireData.sharedParams.recipFz0; const TFloat latTireForceNormalized = latTireForce * tireData.sharedParams.recipFz0; const TFloat normalizedVelR0 = (wheelOmega * tireData.sharedParams.r0) / tireData.sharedParams.v0; TFloat dpi; if (TConfig::supportInflationPressure) dpi = (tireInflationPressure - tireData.sharedParams.pi0) / tireData.sharedParams.pi0; else dpi = TFloat(0.0); TFloat tireLoad = mfTireNormalLoad<TConfig>(tireData.sharedParams.fz0, normalizedVelR0, tireData.sharedParams.r0, longTireForceNormalized, latTireForceNormalized, gammaSqr, tireDeflection, dpi, tireData.normalLoadParams, tireData.verticalStiffnessParams); return tireLoad; } template<typename TConfig> PX_FORCE_INLINE void mfTireComputeSlip( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float longVelocity, const typename TConfig::Float latVelocity, const typename TConfig::Float wheelOmega, const typename TConfig::Float tireLoad, const typename TConfig::Float tireInflationPressure, typename TConfig::Float& longSlip, typename TConfig::Float& tanLatSlip, typename TConfig::Float& effectiveRollingRadius) { // // see mfTireComputeForce() for the coordinate system used // typedef typename TConfig::Float TFloat; TFloat dpi; if (TConfig::supportInflationPressure) dpi = (tireInflationPressure - tireData.sharedParams.pi0) / tireData.sharedParams.pi0; else dpi = TFloat(0.0); const TFloat fzNormalized = tireLoad * tireData.sharedParams.recipFz0; TFloat normalizedVelR0; PX_UNUSED(normalizedVelR0); const TFloat rOmega = mfTireFreeRotatingRadius(tireData.sharedParams.r0, wheelOmega, tireData.sharedParams.v0, tireData.freeRotatingRadiusParams, normalizedVelR0); const TFloat vertTireStiffness = mfTireVerticalStiffness<TConfig>(dpi, tireData.verticalStiffnessParams); const TFloat re = mfTireEffectiveRollingRadius(rOmega, vertTireStiffness, tireData.sharedParams.fz0, fzNormalized, tireData.effectiveRollingRadiusParams); effectiveRollingRadius = re; const TFloat absLongVelocityPlusEpsilon = PxAbs(longVelocity) + tireData.sharedParams.epsilonV; const bool isAboveOrEqLongVelThreshold = absLongVelocityPlusEpsilon >= tireData.sharedParams.slipReductionLowVelocity; TFloat absLongVelocityInterpolated; if (isAboveOrEqLongVelThreshold) absLongVelocityInterpolated = absLongVelocityPlusEpsilon; else { // interpolation with a quadratic weight change for the threshold velocity such that the effect reduces // fast with growing velocity. Read section about oscillation further below. const TFloat longVelRatio = absLongVelocityPlusEpsilon / tireData.sharedParams.slipReductionLowVelocity; TFloat interpFactor = TFloat(1.0) - longVelRatio; interpFactor = interpFactor * interpFactor; absLongVelocityInterpolated = (interpFactor * tireData.sharedParams.slipReductionLowVelocity) + ((TFloat(1.0) - interpFactor) * absLongVelocityPlusEpsilon); } // // longitudinal slip ratio (kappa): // // kappa = - (Vsx / |Vcx|) // // note: sign is chosen to get positive value under drive torque and negative under break torque // // ---------------------------------------------------------------------------------------------------------------- // Vcx: velocity of wheel contact center, projected onto wheel x-axis (direction wheel is pointing to) // ---------------------------------------------------------------------------------------------------------------- // Vsx: longitudinal slip velocity // = Vcx - (omega * Re) // (difference between the actual velocity at the wheel contact point and the "orbital" velocity from the // wheel rotation) // ----------------------------------------------------------------------------------------------------------- // omega: wheel rotational velocity // ----------------------------------------------------------------------------------------------------------- // Re: effective rolling radius (at free rolling of the tire, no brake/drive torque) // At constant speed with no brake/drive torque, using Re will result in Vsx (and thus kappa) being 0. // ---------------------------------------------------------------------------------------------------------------- // // Problems at low velocities and starting from standstill etc. // - oscillation: // division by small velocity values results in large slip values and thus in large forces. For large // time steps this results in overshooting a stable state. // The applied formulas are for the steady-state only. This will add to the overshooting too. // Furthermore, the algorithm is prone to oscillation at low velocities to begin with. // - zero slip does not mean zero force: // the formulas include shift terms in the function input and output values. That will result in non-zero forces // even if the slip is 0. // // Reducing these problems: // - run at smaller time steps // - artificially lower slip values when the velocity is below a threshold. This is done by replacing the actual Vcx // velocity with an interpolation between the real Vcx and a threshold velocity if Vcx is below the threshold // velocity (for example, if Vcx was 0, the threshold velocity would be used instead). The larger the threshold // velocity, the less oscillation is observed at the cost of affecting the simulation behavior at normal speeds. // const TFloat longSlipVelocityNeg = (wheelOmega * re) - longVelocity; // = -Vsx const TFloat longSlipRatio = longSlipVelocityNeg / absLongVelocityInterpolated; longSlip = longSlipRatio; // // lateral slip angle (alpha): // // alpha = arctan(-Vcy / |Vcx|) // // note: sign is chosen to get positive force value if the slip is positive // // ---------------------------------------------------------------------------------------------------------------- // Vcx: velocity of wheel contact center, projected onto wheel x-axis (direction wheel is pointing to) // ---------------------------------------------------------------------------------------------------------------- // Vcy: velocity of wheel contact center, projected onto wheel y-axis (direction pointing to the side of the wheel, // that is, perpendicular to x-axis mentioned above) // ---------------------------------------------------------------------------------------------------------------- // const TFloat tanSlipAngle = (-latVelocity) / absLongVelocityInterpolated; tanLatSlip = tanSlipAngle; } template<typename TConfig> PX_FORCE_INLINE void mfTireComputeForce( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float tireFriction, const typename TConfig::Float longSlip, const typename TConfig::Float tanLatSlip, const typename TConfig::Float camber, const typename TConfig::Float effectiveRollingRadius, const typename TConfig::Float tireLoad, const typename TConfig::Float tireInflationPressure, const typename TConfig::Float longVelocity, const typename TConfig::Float latVelocity, typename TConfig::Float& wheelTorque, typename TConfig::Float& tireLongForce, typename TConfig::Float& tireLatForce, typename TConfig::Float& tireAlignMoment) { typedef typename TConfig::Float TFloat; PX_ASSERT(tireFriction > 0); PX_ASSERT(tireLoad >= 0); wheelTorque = TFloat(0.0); tireLongForce = TFloat(0.0); tireLatForce = TFloat(0.0); tireAlignMoment = TFloat(0.0); /* // Magic Formula Tire Model // // Implementation follows pretty closely the description in the book: // Tire and Vehicle Dynamics, 3rd Edition, Hans Pacejka // The steady-state model is implemented only. // // General limitations: // - expects rather smooth road surface (surface wavelengths longer than a tire radius) up to frequencies of 8 Hz // (for steady-state model around 1 Hz only) // // // The magic formula (see magicFormulaSine(), magicFormulaCosine()) is used as a basis for describing curves for // longitudinal/lateral force, aligning torque etc. // // // The model uses the following coordinate system for the tire: // // top view: side view: // // // ________________________ __________ // | | ___/ \___ // | ----------------> x __/ \__ // |____________|___________| / \ // | | | // | / \ // | | | // | | ---------------------> x // | \ | / // v | | | // y \__ | __/ // \___ | ___/ // _ _ _ _ _ _ \_____|____/ _ _ _ _ _ _ // | // | // v // z */ MFTireVolatileSharedParams<TFloat> volatileSharedParams; { mfTireComputeVolatileSharedParams<TConfig>(camber, tireLoad, tireFriction, tireFriction, tireInflationPressure, tireData.sharedParams, volatileSharedParams); } // note: even if long slip/lat slip/camber are all zero, the computation takes place as the model can take effects like // conicity etc. into account (thus, forces might not be 0 even if slip and camber are 0) TFloat K_kappa_longitudinal; const TFloat longForcePure = mfTireLongitudinalForcePure<TConfig>(longSlip, tireLoad, tireData.longitudinalForcePureParams, tireData.sharedParams, volatileSharedParams, K_kappa_longitudinal); const TFloat longForceCombined = mfTireLongitudinalForceCombined<TConfig>(longSlip, tanLatSlip, longForcePure, tireData.longitudinalForceCombinedParams, volatileSharedParams); tireLongForce = longForceCombined; TFloat latForcePureNoCamberNoTurnSlip; TFloat latForcePureNoCamberNoTurnSlipWeight; TFloat* latForcePureNoCamberNoTurnSlipPtr; TFloat* latForcePureNoCamberNoTurnSlipWeightPtr; if (tireData.flags & MFTireDataFlag::eALIGNING_MOMENT) { latForcePureNoCamberNoTurnSlipPtr = &latForcePureNoCamberNoTurnSlip; latForcePureNoCamberNoTurnSlipWeightPtr = &latForcePureNoCamberNoTurnSlipWeight; } else { latForcePureNoCamberNoTurnSlipPtr = NULL; latForcePureNoCamberNoTurnSlipWeightPtr = NULL; } TFloat B_lateral, C_lateral, K_alpha_withEpsilon_lateral, Sh_lateral, Sv_lateral, mu_zeta2; const TFloat latForcePure = mfTireLateralForcePure<TConfig>(tanLatSlip, tireLoad, tireData.lateralForcePureParams, tireData.sharedParams, volatileSharedParams, latForcePureNoCamberNoTurnSlipPtr, B_lateral, C_lateral, K_alpha_withEpsilon_lateral, Sh_lateral, Sv_lateral, mu_zeta2); const TFloat latForceCombined = mfTireLateralForceCombined<TConfig>(tanLatSlip, longSlip, tireLoad, latForcePure, mu_zeta2, tireData.lateralForceCombinedParams, volatileSharedParams, latForcePureNoCamberNoTurnSlipWeightPtr); tireLatForce = latForceCombined; if (tireData.flags & MFTireDataFlag::eALIGNING_MOMENT) { MFTireAligningTorqueVolatileSharedParams<TFloat> aligningTorqueVolatileSharedParams; const TFloat combinedVelocity = PxSqrt((longVelocity*longVelocity) + (latVelocity*latVelocity)); mfTireComputeAligningTorqueVolatileSharedParams(combinedVelocity, longVelocity, tireData.sharedParams.epsilonV, aligningTorqueVolatileSharedParams); const TFloat aligningTorque = mfTireAligningTorqueCombined<TConfig>(tanLatSlip, longSlip, tireLoad, longForceCombined, latForceCombined, *latForcePureNoCamberNoTurnSlipPtr, *latForcePureNoCamberNoTurnSlipWeightPtr, K_kappa_longitudinal, K_alpha_withEpsilon_lateral, B_lateral, C_lateral, Sh_lateral, Sv_lateral, tireData.aligningTorquePurePneumaticTrailParams, tireData.aligningTorquePureResidualTorqueParams, tireData.aligningTorqueCombinedParams, aligningTorqueVolatileSharedParams, tireData.sharedParams, volatileSharedParams); tireAlignMoment = aligningTorque; } wheelTorque = -tireLongForce * effectiveRollingRadius; } #if !PX_DOXYGEN } // namespace physx #endif #endif //VEHICLE_MF_TIRE_H
75,720
C
41.587739
209
0.69617
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTire.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "VehicleMFTireData.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; /** \brief Struct to configure the templated functions of the Magic Formula Tire Model. A typedef named "Float" declares the floating point type to use (to configure for 32bit or 64bit precision). Some static boolean members allow to enable/disable code at compile time depending on the desired feature set and complexity. */ struct MFTireConfig { typedef PxF32 Float; static const bool supportInflationPressure = false; //PhysX vehicles do not model inflation pressure (nore can it be derived/estimated //from the PhysX state values). static const bool supportCamber = true; static const bool supportTurnSlip = false; //Turn slip effects will be ignored (same as having all parameters named "zeta..." set to 1). }; typedef MFTireDataT<MFTireConfig::Float> MFTireData; /** \brief Custom method to compute tire grip values. \note If the suspension cannot place the wheel on the ground, the tire load and friction will be 0. \param[in] isWheelOnGround True if the wheel is touching the ground. \param[in] unfilteredLoad The force pushing the tire to the ground. \param[in] restLoad The nominal vertical load of the tire (the expected load at rest). \param[in] maxNormalizedLoad The maximum normalized load (load / restLoad). Values above will result in the load being clamped. This can avoid instabilities when dealing with discontinuities that generate large load (like the suspension compressing by a large delta for a small simulation timestep). \param[in] friction The friction coefficient to use. \param[out] tireGripState The computed load and friction experienced by the tire. */ void CustomTireGripUpdate( bool isWheelOnGround, PxF32 unfilteredLoad, PxF32 restLoad, PxF32 maxNormalizedLoad, PxF32 friction, PxVehicleTireGripState& tireGripState); /** \brief Custom method to compute tire slip values. \note See MFTireConfig for the configuration this method is defined for. \param[in] tireData The tire parameters of the Magic Formula Tire Model. \param[in] tireSpeedState The velocity at the tire contact point projected along the tire's longitudinal and lateral axes. \param[in] wheelOmega The wheel rotation speed in radians per second. \param[in] tireLoad The force pushing the tire to the ground. \param[out] tireSlipState The computed tire longitudinal and lateral slips. \param[out] effectiveRollingRadius The radius re that matches the angular velocity (omega) and the velocity at the contact patch (V) under free rolling conditions (no drive/break torque), i.e., re = V / omega. This radius is bounded by the free tire radius of the rotating tire on one end and the loaded tire radius on the other end. The effective rolling radius changes with the load (fast for low values of load but only marginally at higher load values). */ void CustomTireSlipsUpdate( const MFTireData& tireData, const PxVehicleTireSpeedState& tireSpeedState, PxF32 wheelOmega, PxF32 tireLoad, PxVehicleTireSlipState& tireSlipState, PxF32& effectiveRollingRadius); /** \brief Custom method to compute the longitudinal and lateral tire forces using the Magic Formula Tire Model. \note See MFTireConfig for the configuration this method is defined for. \note This tire model requires running with a high simulation update rate (1kHz is recommended). \param[in] tireData The tire parameters of the Magic Formula Tire Model. \param[in] tireSlipState The tire longitudinal and lateral slips. \param[in] tireSpeedState The velocity at the tire contact point projected along the tire's longitudinal and lateral axes. \param[in] tireDirectionState The tire's longitudinal and lateral directions in the ground plane. \param[in] tireGripState The load and friction experienced by the tire. \param[in] tireStickyState Description of the sticky state of the tire in the longitudinal and lateral directions. \param[in] bodyPose The world transform of the vehicle body. \param[in] suspensionAttachmentPose The transform of the suspension attachment (in vehicle body space). \param[in] tireForceApplicationPoint The tire force application point (in suspension attachment space). \param[in] camber The camber angle of the tire expressed in radians. \param[in] effectiveRollingRadius The radius under free rolling conditions (see CustomTireSlipsUpdate for details). \param[out] tireForce The computed tire forces in the world frame. */ void CustomTireForcesUpdate( const MFTireData& tireData, const PxVehicleTireSlipState& tireSlipState, const PxVehicleTireSpeedState& tireSpeedState, const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireGripState& tireGripState, const PxVehicleTireStickyState& tireStickyState, const PxTransform& bodyPose, const PxTransform& suspensionAttachmentPose, const PxVec3& tireForceApplicationPoint, PxF32 camber, PxF32 effectiveRollingRadius, PxVehicleTireForce& tireForce); struct CustomTireParams { MFTireData mfTireData; PxReal maxNormalizedLoad; // maximum normalized load (load / restLoad). Values above will be clamped. // Large discontinuities can cause unnaturally large load values which the // Magic Formula Tire Model does not support (for example having the wheel // go from one frame with no ground contact to a highly compressed suspension // in the next frame). }; class CustomTireComponent : public PxVehicleComponent { public: CustomTireComponent() : PxVehicleComponent() {} virtual void getDataForCustomTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const CustomTireParams>& tireParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) = 0; virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) { const PxVehicleAxleDescription* axleDescription; PxVehicleArrayData<const PxReal> steerResponseStates; const PxVehicleRigidBodyState* rigidBodyState; PxVehicleArrayData<const PxVehicleWheelActuationState> actuationStates; PxVehicleArrayData<const PxVehicleWheelParams> wheelParams; PxVehicleArrayData<const PxVehicleSuspensionParams> suspensionParams; PxVehicleArrayData<const CustomTireParams> tireParams; PxVehicleArrayData<const PxVehicleRoadGeometryState> roadGeomStates; PxVehicleArrayData<const PxVehicleSuspensionState> suspensionStates; PxVehicleArrayData<const PxVehicleSuspensionComplianceState> suspensionComplianceStates; PxVehicleArrayData<const PxVehicleSuspensionForce> suspensionForces; PxVehicleArrayData<const PxVehicleWheelRigidBody1dState> wheelRigidBody1DStates; PxVehicleArrayData<PxVehicleTireGripState> tireGripStates; PxVehicleArrayData<PxVehicleTireDirectionState> tireDirectionStates; PxVehicleArrayData<PxVehicleTireSpeedState> tireSpeedStates; PxVehicleArrayData<PxVehicleTireSlipState> tireSlipStates; PxVehicleArrayData<PxVehicleTireCamberAngleState> tireCamberAngleStates; PxVehicleArrayData<PxVehicleTireStickyState> tireStickyStates; PxVehicleArrayData<PxVehicleTireForce> tireForces; getDataForCustomTireComponent(axleDescription, steerResponseStates, rigidBodyState, actuationStates, wheelParams, suspensionParams, tireParams, roadGeomStates, suspensionStates, suspensionComplianceStates, suspensionForces, wheelRigidBody1DStates, tireGripStates, tireDirectionStates, tireSpeedStates, tireSlipStates, tireCamberAngleStates, tireStickyStates, tireForces); for (PxU32 i = 0; i < axleDescription->nbWheels; i++) { const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; const PxReal& steerResponseState = steerResponseStates[wheelId]; const PxVehicleWheelParams& wheelParam = wheelParams[wheelId]; const PxVehicleSuspensionParams& suspensionParam = suspensionParams[wheelId]; const CustomTireParams& tireParam = tireParams[wheelId]; const PxVehicleRoadGeometryState& roadGeomState = roadGeomStates[wheelId]; const PxVehicleSuspensionState& suspensionState = suspensionStates[wheelId]; const PxVehicleSuspensionComplianceState& suspensionComplianceState = suspensionComplianceStates[wheelId]; const PxVehicleWheelRigidBody1dState& wheelRigidBody1dState = wheelRigidBody1DStates[wheelId]; const bool isWheelOnGround = PxVehicleIsWheelOnGround(suspensionState); //Compute the tire slip directions PxVehicleTireDirectionState& tireDirectionState = tireDirectionStates[wheelId]; PxVehicleTireDirsUpdate( suspensionParam, steerResponseState, roadGeomState.plane.n, isWheelOnGround, suspensionComplianceState, *rigidBodyState, context.frame, tireDirectionState); //Compute the rigid body speeds along the tire slip directions. PxVehicleTireSpeedState& tireSpeedState = tireSpeedStates[wheelId]; PxVehicleTireSlipSpeedsUpdate( wheelParam, suspensionParam, steerResponseState, suspensionState, tireDirectionState, *rigidBodyState, roadGeomState, context.frame, tireSpeedState); //Compute grip state PxVehicleTireGripState& tireGripState = tireGripStates[wheelId]; CustomTireGripUpdate( isWheelOnGround, suspensionForces[wheelId].normalForce, PxF32(tireParam.mfTireData.sharedParams.fz0), tireParam.maxNormalizedLoad, roadGeomState.friction, tireGripState); //Compute the tire slip values. PxVehicleTireSlipState& tireSlipState = tireSlipStates[wheelId]; PxF32 effectiveRollingRadius; //Ensure radius is in sync #if PX_ENABLE_ASSERTS // avoid warning about unusued local typedef typedef MFTireConfig::Float TFloat; #endif PX_ASSERT(PxAbs(tireParam.mfTireData.sharedParams.r0 - TFloat(wheelParam.radius)) < (tireParam.mfTireData.sharedParams.r0 * TFloat(0.01))); CustomTireSlipsUpdate( tireParam.mfTireData, tireSpeedState, wheelRigidBody1dState.rotationSpeed, tireGripState.load, tireSlipState, effectiveRollingRadius); //Update the camber angle PxVehicleTireCamberAngleState& tireCamberAngleState = tireCamberAngleStates[wheelId]; PxVehicleTireCamberAnglesUpdate( suspensionParam, steerResponseState, roadGeomState.plane.n, isWheelOnGround, suspensionComplianceState, *rigidBodyState, context.frame, tireCamberAngleState); //Update the tire sticky state // //Note: this should be skipped if tires do not use the sticky feature PxVehicleTireStickyState& tireStickyState = tireStickyStates[wheelId]; PxVehicleTireStickyStateUpdate( *axleDescription, wheelParam, context.tireStickyParams, actuationStates, tireGripState, tireSpeedState, wheelRigidBody1dState, dt, tireStickyState); //If sticky tire is active set the slip values to zero. // //Note: this should be skipped if tires do not use the sticky feature PxVehicleTireSlipsAccountingForStickyStatesUpdate( tireStickyState, tireSlipState); //Compute the tire forces PxVehicleTireForce& tireForce = tireForces[wheelId]; CustomTireForcesUpdate( tireParam.mfTireData, tireSlipState, tireSpeedState, tireDirectionState, tireGripState, tireStickyState, rigidBodyState->pose, suspensionParam.suspensionAttachment, suspensionComplianceState.tireForceAppPoint, tireCamberAngleState.camberAngle, effectiveRollingRadius, tireForce); } return true; } }; }//namespace snippetvehicle2
14,361
C
43.741433
142
0.795766
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTireVehicle.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 "CustomTireVehicle.h" namespace snippetvehicle2 { template<typename TFloat> static void setExampleSharedParams(MFTireSharedParams<TFloat>& sharedParams, const TFloat lengthScale) { sharedParams.r0 = TFloat(0.3135) * lengthScale; // tire radius under no load (base unit is [m]) sharedParams.v0 = TFloat(16.7) * lengthScale; // reference velocity (=60km/h) (base unit is [m/s]) sharedParams.fz0 = TFloat(4000.0) * lengthScale; // nominal load (base unit is [N]) sharedParams.pi0 = TFloat(220000.0) / lengthScale; // nominal inflation pressure (=2.2 bar) (base unit is [Pa]) sharedParams.epsilonV = TFloat(0.01) * lengthScale; sharedParams.slipReductionLowVelocity = TFloat(7.0) * lengthScale; sharedParams.lambdaFz0 = TFloat(1.0); sharedParams.lambdaK_alpha = TFloat(1.0); sharedParams.aMu = TFloat(10.0); sharedParams.zeta0 = TFloat(1.0); sharedParams.zeta2 = TFloat(1.0); mfTireComputeDerivedSharedParams(sharedParams); } template<typename TFloat> static void setExampleLongitudinalForcePureParams(MFTireLongitudinalForcePureParams<TFloat>& longitudinalForcePureParams, const TFloat lengthScale) { longitudinalForcePureParams.pK1 = TFloat(21.687); longitudinalForcePureParams.pK2 = TFloat(13.728); longitudinalForcePureParams.pK3 = TFloat(-0.4098); longitudinalForcePureParams.pp1 = TFloat(-0.3485); longitudinalForcePureParams.pp2 = TFloat(0.37824); longitudinalForcePureParams.lambdaK = TFloat(1.0); longitudinalForcePureParams.epsilon = TFloat(1.0) * lengthScale; //--- longitudinalForcePureParams.pC1 = TFloat(1.579); longitudinalForcePureParams.lambdaC = TFloat(1.0); //--- longitudinalForcePureParams.pD1 = TFloat(1.0422); longitudinalForcePureParams.pD2 = TFloat(-0.08285); longitudinalForcePureParams.pD3 = TFloat(0.0); longitudinalForcePureParams.pp3 = TFloat(-0.09603); longitudinalForcePureParams.pp4 = TFloat(0.06518); //--- longitudinalForcePureParams.pE1 = TFloat(0.11113); longitudinalForcePureParams.pE2 = TFloat(0.3143); longitudinalForcePureParams.pE3 = TFloat(0.0); longitudinalForcePureParams.pE4 = TFloat(0.001719); longitudinalForcePureParams.lambdaE = TFloat(1.0); //--- longitudinalForcePureParams.pH1 = TFloat(2.1615e-4); longitudinalForcePureParams.pH2 = TFloat(0.0011598); longitudinalForcePureParams.lambdaH = TFloat(1.0); //--- longitudinalForcePureParams.pV1 = TFloat(2.0283e-5); longitudinalForcePureParams.pV2 = TFloat(1.0568e-4); longitudinalForcePureParams.lambdaV = TFloat(1.0); longitudinalForcePureParams.zeta1 = TFloat(1.0); } template<typename TFloat> static void setExampleLongitudinalForceCombinedParams(MFTireLongitudinalForceCombinedParams<TFloat>& longitudinalForceCombinedParams) { longitudinalForceCombinedParams.rB1 = TFloat(13.046); longitudinalForceCombinedParams.rB2 = TFloat(9.718); longitudinalForceCombinedParams.rB3 = TFloat(0.0); longitudinalForceCombinedParams.lambdaAlpha = TFloat(1.0); //--- longitudinalForceCombinedParams.rC1 = TFloat(0.9995); //--- longitudinalForceCombinedParams.rE1 = TFloat(-0.4403); longitudinalForceCombinedParams.rE2 = TFloat(-0.4663); //--- longitudinalForceCombinedParams.rH1 = TFloat(-9.968e-5); } template<typename TFloat> static void setExampleLateralForcePureParams(MFTireLateralForcePureParams<TFloat>& lateralForcePureParams, const TFloat lengthScale) { lateralForcePureParams.pK1 = TFloat(15.324); // note: original source uses ISO sign convention and thus the value was negative lateralForcePureParams.pK2 = TFloat(1.715); lateralForcePureParams.pK3 = TFloat(0.3695); lateralForcePureParams.pK4 = TFloat(2.0005); lateralForcePureParams.pK5 = TFloat(0.0); lateralForcePureParams.pp1 = TFloat(-0.6255); lateralForcePureParams.pp2 = TFloat(-0.06523); lateralForcePureParams.epsilon = TFloat(1.0) * lengthScale; lateralForcePureParams.zeta3 = TFloat(1.0); //--- lateralForcePureParams.pC1 = TFloat(1.338); lateralForcePureParams.lambdaC = TFloat(1.0); //--- lateralForcePureParams.pD1 = TFloat(0.8785); lateralForcePureParams.pD2 = TFloat(-0.06452); lateralForcePureParams.pD3 = TFloat(0.0); lateralForcePureParams.pp3 = TFloat(-0.16666); lateralForcePureParams.pp4 = TFloat(0.2811); //--- lateralForcePureParams.pE1 = TFloat(-0.8057); lateralForcePureParams.pE2 = TFloat(-0.6046); lateralForcePureParams.pE3 = TFloat(0.09854); lateralForcePureParams.pE4 = TFloat(-6.697); lateralForcePureParams.pE5 = TFloat(0.0); lateralForcePureParams.lambdaE = TFloat(1.0); //--- lateralForcePureParams.pH1 = TFloat(-0.001806); lateralForcePureParams.pH2 = TFloat(0.00352); lateralForcePureParams.pK6 = TFloat(-0.8987); lateralForcePureParams.pK7 = TFloat(-0.23303); lateralForcePureParams.pp5 = TFloat(0.0); lateralForcePureParams.lambdaH = TFloat(1.0); lateralForcePureParams.epsilonK = TFloat(10.0) * lengthScale; lateralForcePureParams.zeta4 = TFloat(1.0); //--- lateralForcePureParams.pV1 = TFloat(-0.00661); lateralForcePureParams.pV2 = TFloat(0.03592); lateralForcePureParams.pV3 = TFloat(-0.162); lateralForcePureParams.pV4 = TFloat(-0.4864); lateralForcePureParams.lambdaV = TFloat(1.0); lateralForcePureParams.lambdaK_gamma = TFloat(1.0); } template<typename TFloat> static void setExampleLateralForceCombinedParams(MFTireLateralForceCombinedParams<TFloat>& lateralForceCombinedParams) { lateralForceCombinedParams.rB1 = TFloat(10.622); lateralForceCombinedParams.rB2 = TFloat(7.82); lateralForceCombinedParams.rB3 = TFloat(0.002037); lateralForceCombinedParams.rB4 = TFloat(0.0); lateralForceCombinedParams.lambdaKappa = TFloat(1.0); //--- lateralForceCombinedParams.rC1 = TFloat(1.0587); //-- lateralForceCombinedParams.rE1 = TFloat(0.3148); lateralForceCombinedParams.rE2 = TFloat(0.004867); //--- lateralForceCombinedParams.rH1 = TFloat(0.009472); lateralForceCombinedParams.rH2 = TFloat(0.009754); //--- lateralForceCombinedParams.rV1 = TFloat(0.05187); lateralForceCombinedParams.rV2 = TFloat(4.853e-4); lateralForceCombinedParams.rV3 = TFloat(0.0); lateralForceCombinedParams.rV4 = TFloat(94.63); lateralForceCombinedParams.rV5 = TFloat(1.8914); lateralForceCombinedParams.rV6 = TFloat(23.8); lateralForceCombinedParams.lambdaV = TFloat(1.0); } template<typename TFloat> static void setExampleAligningTorquePurePneumaticTrailParams(MFTireAligningTorquePurePneumaticTrailParams<TFloat>& aligningTorquePurePneumaticTrailParams) { aligningTorquePurePneumaticTrailParams.qB1 = TFloat(12.035); aligningTorquePurePneumaticTrailParams.qB2 = TFloat(-1.33); aligningTorquePurePneumaticTrailParams.qB3 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.qB5 = TFloat(-0.14853); aligningTorquePurePneumaticTrailParams.qB6 = TFloat(0.0); //--- aligningTorquePurePneumaticTrailParams.qC1 = TFloat(1.2923); //--- aligningTorquePurePneumaticTrailParams.qD1 = TFloat(0.09068); aligningTorquePurePneumaticTrailParams.qD2 = TFloat(-0.00565); aligningTorquePurePneumaticTrailParams.qD3 = TFloat(0.3778); aligningTorquePurePneumaticTrailParams.qD4 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.pp1 = TFloat(-0.4408); aligningTorquePurePneumaticTrailParams.lambdaT = TFloat(1.0); aligningTorquePurePneumaticTrailParams.zeta5 = TFloat(1.0); //--- aligningTorquePurePneumaticTrailParams.qE1 = TFloat(-1.7924); aligningTorquePurePneumaticTrailParams.qE2 = TFloat(0.8975); aligningTorquePurePneumaticTrailParams.qE3 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.qE4 = TFloat(0.2895); aligningTorquePurePneumaticTrailParams.qE5 = TFloat(-0.6786); //--- aligningTorquePurePneumaticTrailParams.qH1 = TFloat(0.0014333); aligningTorquePurePneumaticTrailParams.qH2 = TFloat(0.0024087); aligningTorquePurePneumaticTrailParams.qH3 = TFloat(0.24973); aligningTorquePurePneumaticTrailParams.qH4 = TFloat(-0.21205); } template<typename TFloat> static void setExampleAligningTorquePureResidualTorqueParams(MFTireAligningTorquePureResidualTorqueParams<TFloat>& aligningTorquePureResidualTorqueParams) { aligningTorquePureResidualTorqueParams.qB9 = TFloat(34.5); aligningTorquePureResidualTorqueParams.qB10 = TFloat(0.0); aligningTorquePureResidualTorqueParams.zeta6 = TFloat(1.0); //--- aligningTorquePureResidualTorqueParams.zeta7 = TFloat(1.0); //--- aligningTorquePureResidualTorqueParams.qD6 = TFloat(0.0017015); aligningTorquePureResidualTorqueParams.qD7 = TFloat(-0.002091); aligningTorquePureResidualTorqueParams.qD8 = TFloat(-0.1428); aligningTorquePureResidualTorqueParams.qD9 = TFloat(0.00915); aligningTorquePureResidualTorqueParams.qD10 = TFloat(0.0); aligningTorquePureResidualTorqueParams.qD11 = TFloat(0.0); aligningTorquePureResidualTorqueParams.pp2 = TFloat(0.0); aligningTorquePureResidualTorqueParams.lambdaR = TFloat(1.0); aligningTorquePureResidualTorqueParams.lambdaK_gamma = TFloat(1.0); aligningTorquePureResidualTorqueParams.zeta8 = TFloat(1.0); } template<typename TFloat> static void setExampleAligningTorqueCombinedParams(MFTireAligningTorqueCombinedParams<TFloat>& aligningTorqueCombinedParams) { aligningTorqueCombinedParams.sS1 = TFloat(0.00918); aligningTorqueCombinedParams.sS2 = TFloat(0.03869); aligningTorqueCombinedParams.sS3 = TFloat(0.0); aligningTorqueCombinedParams.sS4 = TFloat(0.0); aligningTorqueCombinedParams.lambdaS = TFloat(1.0); } //For completeness but not used in this example /*template<typename TFloat> static void setExampleOverturningCoupleParams(MFTireOverturningCoupleParams<TFloat>& overturningCoupleParams) { overturningCoupleParams.qS1 = TFloat(-0.007764); overturningCoupleParams.qS2 = TFloat(1.1915); overturningCoupleParams.qS3 = TFloat(0.013948); overturningCoupleParams.qS4 = TFloat(4.912); overturningCoupleParams.qS5 = TFloat(1.02); overturningCoupleParams.qS6 = TFloat(22.83); overturningCoupleParams.qS7 = TFloat(0.7104); overturningCoupleParams.qS8 = TFloat(-0.023393); overturningCoupleParams.qS9 = TFloat(0.6581); overturningCoupleParams.qS10 = TFloat(0.2824); overturningCoupleParams.qS11 = TFloat(5.349); overturningCoupleParams.ppM1 = TFloat(0.0); overturningCoupleParams.lambdaVM = TFloat(1.0); overturningCoupleParams.lambdaM = TFloat(1.0); } template<typename TFloat> static void setExampleRollingResistanceMomentParams(MFTireRollingResistanceMomentParams<TFloat>& rollingResistanceMomentParams) { rollingResistanceMomentParams.qS1 = TFloat(0.00702); rollingResistanceMomentParams.qS2 = TFloat(0.0); rollingResistanceMomentParams.qS3 = TFloat(0.001515); rollingResistanceMomentParams.qS4 = TFloat(8.514e-5); rollingResistanceMomentParams.qS5 = TFloat(0.0); rollingResistanceMomentParams.qS6 = TFloat(0.0); rollingResistanceMomentParams.qS7 = TFloat(0.9008); rollingResistanceMomentParams.qS8 = TFloat(-0.4089); rollingResistanceMomentParams.lambdaM = TFloat(1.0); }*/ template<typename TFloat> static void setExampleFreeRotatingRadiusParams(MFTireFreeRotatingRadiusParams<TFloat>& freeRotatingRadiusParams) { freeRotatingRadiusParams.qre0 = TFloat(0.9974); freeRotatingRadiusParams.qV1 = TFloat(7.742e-4); } template<typename TFloat> static void setExampleVerticalStiffnessParams(const TFloat r0, const TFloat fz0, MFTireVerticalStiffnessParams<TFloat>& verticalStiffnessParams) { verticalStiffnessParams.qF1 = TFloat(14.435747); verticalStiffnessParams.qF2 = TFloat(15.4); verticalStiffnessParams.ppF1 = TFloat(0.7098); verticalStiffnessParams.lambdaC = TFloat(1.0); mfTireComputeDerivedVerticalTireStiffnessParams(r0, fz0, verticalStiffnessParams); } template<typename TFloat> static void setExampleNormalLoadParams(MFTireNormalLoadParams<TFloat>& normalLoadParams) { normalLoadParams.qV2 = TFloat(0.04667); normalLoadParams.qFc_longitudinal = TFloat(0.0); normalLoadParams.qFc_lateral = TFloat(0.0); normalLoadParams.qF3 = TFloat(0.0); } template<typename TFloat> static void setExampleEffectiveRollingRadiusParams(MFTireEffectiveRollingRadiusParams<TFloat>& effectiveRollingRadiusParams) { effectiveRollingRadiusParams.Freff = TFloat(0.07394); effectiveRollingRadiusParams.Dreff = TFloat(0.25826); effectiveRollingRadiusParams.Breff = TFloat(8.386); } template<typename TFloat> static void setExampleTireData(const TFloat lengthScale, const bool computeAligningMoment, MFTireDataT<TFloat>& tireData) { setExampleSharedParams(tireData.sharedParams, lengthScale); setExampleFreeRotatingRadiusParams(tireData.freeRotatingRadiusParams); setExampleVerticalStiffnessParams(tireData.sharedParams.r0, tireData.sharedParams.fz0, tireData.verticalStiffnessParams); setExampleEffectiveRollingRadiusParams(tireData.effectiveRollingRadiusParams); setExampleNormalLoadParams(tireData.normalLoadParams); setExampleLongitudinalForcePureParams(tireData.longitudinalForcePureParams, lengthScale); setExampleLongitudinalForceCombinedParams(tireData.longitudinalForceCombinedParams); setExampleLateralForcePureParams(tireData.lateralForcePureParams, lengthScale); setExampleLateralForceCombinedParams(tireData.lateralForceCombinedParams); setExampleAligningTorquePurePneumaticTrailParams(tireData.aligningTorquePurePneumaticTrailParams); setExampleAligningTorquePureResidualTorqueParams(tireData.aligningTorquePureResidualTorqueParams); setExampleAligningTorqueCombinedParams(tireData.aligningTorqueCombinedParams); if (computeAligningMoment) tireData.flags |= MFTireDataFlag::eALIGNING_MOMENT; else tireData.flags.clear(MFTireDataFlag::eALIGNING_MOMENT); } //Adjust those parameters that describe lateral asymmetry and as such lead more easily to drift. //Can be useful when using the same dataset for all wheels. template<typename TFloat> static void makeTireSymmetric(MFTireDataT<TFloat>& tireData) { tireData.longitudinalForceCombinedParams.rH1 = TFloat(0.0); tireData.lateralForcePureParams.pE3 = TFloat(0.0); tireData.lateralForcePureParams.pH1 = TFloat(0.0); tireData.lateralForcePureParams.pH2 = TFloat(0.0); tireData.lateralForcePureParams.pV1 = TFloat(0.0); tireData.lateralForcePureParams.pV2 = TFloat(0.0); tireData.lateralForceCombinedParams.rB3 = TFloat(0.0); tireData.lateralForceCombinedParams.rV1 = TFloat(0.0); tireData.lateralForceCombinedParams.rV2 = TFloat(0.0); tireData.aligningTorquePureResidualTorqueParams.qD6 = TFloat(0.0); tireData.aligningTorquePureResidualTorqueParams.qD7 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qD3 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qE4 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qH1 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qH2 = TFloat(0.0); tireData.aligningTorqueCombinedParams.sS1 = TFloat(0.0); } bool CustomTireVehicle::initialize(PxPhysics& physics, const PxCookingParams& cookingParams, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { typedef MFTireConfig::Float TFloat; if (!DirectDriveVehicle::initialize(physics, cookingParams, defaultMaterial, addPhysXBeginEndComponents)) return false; //Set the custom parameters for the vehicle tires. const PxTolerancesScale& tolerancesScale = physics.getTolerancesScale(); const bool computeAligningMoment = false; //Not used in this snippet const PxU32 tireDataParameterSetCount = sizeof(mCustomTireParams) / sizeof(mCustomTireParams[0]); for (PxU32 i = 0; i < tireDataParameterSetCount; i++) { //Note: in this example, the same parameter values are used for all wheels. CustomTireParams& customTireParams = mCustomTireParams[i]; setExampleTireData<TFloat>(tolerancesScale.length, computeAligningMoment, customTireParams.mfTireData); customTireParams.maxNormalizedLoad = 3.0f; //For the given parameter set, larger loads than this resulted in values //going out of the expected range in the Magic Formula Tire Model makeTireSymmetric(customTireParams.mfTireData); } PX_ASSERT(mBaseParams.axleDescription.getAxle(0) == 0); PX_ASSERT(mBaseParams.axleDescription.getAxle(1) == 0); mTireParamsList[0] = mCustomTireParams + 0; mTireParamsList[1] = mCustomTireParams + 0; PX_ASSERT(mBaseParams.axleDescription.getAxle(2) == 1); PX_ASSERT(mBaseParams.axleDescription.getAxle(3) == 1); mTireParamsList[2] = mCustomTireParams + 1; mTireParamsList[3] = mCustomTireParams + 1; const PxReal chassisMass = 1630.0f; const PxVec3 chassisMoi(2589.9f, 2763.1f, 607.0f); const PxReal massScale = chassisMass / mBaseParams.rigidBodyParams.mass; //Adjust some non custom parameters to match more closely with the wheel the custom tire model //parameters were taken from. const PxU32 wheelCount = mBaseParams.axleDescription.getNbWheels(); for (PxU32 i = 0; i < wheelCount; i++) { PxVehicleWheelParams& wp = mBaseParams.wheelParams[i]; wp.radius = PxReal(mTireParamsList[i]->mfTireData.sharedParams.r0); wp.halfWidth = 0.5f * 0.205f; wp.mass = 9.3f + 7.247f; wp.moi = 0.736f + 0.5698f; //Map the sprung masses etc. to the new total mass PxVehicleSuspensionForceParams& sfp = mBaseParams.suspensionForceParams[i]; sfp.sprungMass *= massScale; sfp.stiffness *= massScale; //Adjust damping to a range that is not ultra extreme const PxReal dampingRatio = 0.3f; sfp.damping = dampingRatio * 2.0f * PxSqrt(sfp.sprungMass * sfp.stiffness); } mBaseParams.rigidBodyParams.mass = chassisMass; mBaseParams.rigidBodyParams.moi = chassisMoi; //Adjust some non custom parameters given that the model should be higher fidelity. mBaseParams.suspensionStateCalculationParams.limitSuspensionExpansionVelocity = true; mBaseParams.suspensionStateCalculationParams.suspensionJounceCalculationType = PxVehicleSuspensionJounceCalculationType::eSWEEP; mPhysXParams.physxRoadGeometryQueryParams.roadGeometryQueryType = PxVehiclePhysXRoadGeometryQueryType::eSWEEP; //Recreate PhysX actor and shapes since related properties changed mPhysXState.destroy(); mPhysXState.create(mBaseParams, mPhysXParams, physics, cookingParams, defaultMaterial); return true; } void CustomTireVehicle::destroy() { DirectDriveVehicle::destroy(); } void CustomTireVehicle::initComponentSequence(const bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we perform multiple updates of the road geometry queries, suspensions, //tires and wheels. Some tire models might need small time steps to be stable and running //the road geometry queries every substep can reduce large discontinuities (for example //having the wheel go from one frame with no ground contact to a highly compressed suspension //in the next frame). Running substeps on a subset of the operations is computationally //cheaper than simulating the entire sequence. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(16); //16 to get more or less a 1kHz update frequence, assuming main update is 60Hz //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<CustomTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
23,707
C++
44.945736
161
0.797149
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTire.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 "CustomTire.h" #include "VehicleMFTire.h" namespace snippetvehicle2 { void CustomTireGripUpdate( bool isWheelOnGround, PxF32 unfilteredLoad, PxF32 restLoad, PxF32 maxNormalizedLoad, PxF32 friction, PxVehicleTireGripState& trGripState) { trGripState.setToDefault(); //If the wheel is not touching the ground then carry on with zero grip state. if (!isWheelOnGround) return; //Note: in a future release the tire load might be recomputed here using // mfTireComputeLoad(). The missing piece is the tire normal deflection // value (difference between free rolling radius and loaded radius). // With a two degree of freedom quarter car model, this value could // be estimated using the compression length of the tire spring. //Compute load and friction. const PxF32 normalizedLoad = unfilteredLoad / restLoad; if (normalizedLoad < maxNormalizedLoad) trGripState.load = unfilteredLoad; else trGripState.load = maxNormalizedLoad * restLoad; trGripState.friction = friction; } void CustomTireSlipsUpdate( const MFTireData& tireData, const PxVehicleTireSpeedState& tireSpeedState, PxF32 wheelOmega, PxF32 tireLoad, PxVehicleTireSlipState& tireSlipState, PxF32& effectiveRollingRadius) { typedef MFTireConfig::Float TFloat; TFloat longSlipTmp, tanLatSlipTmp, effectiveRollingRadiusTmp; mfTireComputeSlip<MFTireConfig>(tireData, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL], tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL], wheelOmega, tireLoad, tireData.sharedParams.pi0, longSlipTmp, tanLatSlipTmp, effectiveRollingRadiusTmp); tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = PxReal(longSlipTmp); tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = PxReal(MF_ARCTAN(-tanLatSlipTmp)); // note: implementation of Magic Formula Tire Model has lateral axis flipped. // Furthermore, to be consistent with the default PhysX states, the angle is returned. effectiveRollingRadius = PxF32(effectiveRollingRadiusTmp); } void CustomTireForcesUpdate( const MFTireData& tireData, const PxVehicleTireSlipState& tireSlipState, const PxVehicleTireSpeedState& tireSpeedState, const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireGripState& tireGripState, const PxVehicleTireStickyState& tireStickyState, const PxTransform& bodyPose, const PxTransform& suspensionAttachmentPose, const PxVec3& tireForceApplicationPoint, PxF32 camber, PxF32 effectiveRollingRadius, PxVehicleTireForce& tireForce) { typedef MFTireConfig::Float TFloat; PxF32 wheelTorque; PxF32 tireLongForce; PxF32 tireLatForce; PxF32 tireAlignMoment; if ((tireGripState.friction > 0.0f) && (tireGripState.load > 0.0f)) { // note: implementation of Magic Formula Tire Model has lateral axis flipped. Furthermore, it expects the // tangens of the angle. const TFloat tanLatSlipNeg = PxTan(-tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL]); TFloat wheelTorqueTmp, tireLongForceTmp, tireLatForceTmp, tireAlignMomentTmp; mfTireComputeForce<MFTireConfig>(tireData, tireGripState.friction, tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL], tanLatSlipNeg, camber, effectiveRollingRadius, tireGripState.load, tireData.sharedParams.pi0, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL], tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL], wheelTorqueTmp, tireLongForceTmp, tireLatForceTmp, tireAlignMomentTmp); wheelTorque = PxF32(wheelTorqueTmp); tireLongForce = PxF32(tireLongForceTmp); tireLatForce = PxF32(tireLatForceTmp); tireAlignMoment = PxF32(tireAlignMomentTmp); // In the Magic Formula Tire Model, having 0 longitudinal slip does not necessarily mean that // the longitudinal force will be 0 too. The graph used to compute the force allows for vertical // and horizontal shift to model certain effects. Similarly, the lateral force will not necessarily // be 0 just because lateral slip and camber are 0. If the 0 => 0 behavior is desired, then the // parameters need to be set accordingly (see the parameters related to the Sh, Sv parts of the // Magic Formula. The user scaling factors lambdaH and lambdaV can be set to 0, for example, to // eliminate the effect of the parameters that shift the graphs). // // For parameter configurations where 0 slip does not result in 0 force, vehicles might never come // fully to rest. The PhysX default tire model has the sticky tire concept that drives the velocity // towards 0 once velocities stay below a threshold for a defined amount of time. This might not // be enough to cancel the constantly applied force at 0 slip or the sticky tire damping coefficient // needs to be very high. Thus, the following code is added to set the forces to 0 when the tire // fulfills the "stickiness" condition and overrules the results from the Magic Formula Tire Model. const bool clearLngForce = tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL]; const bool clearLatForce = tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL]; if (clearLngForce) { wheelTorque = 0.0f; tireLongForce = 0.0f; } if (clearLatForce) // note: small camber angle could also be seen as requirement but the sticky tire active state is seen as reference here { tireLatForce = 0.0f; } if (clearLngForce && clearLatForce) { tireAlignMoment = 0.0f; } } else { wheelTorque = 0.0f; tireLongForce = 0.0f; tireLatForce = 0.0f; tireAlignMoment = 0.0f; } const PxVec3 tireLongForceVec = tireDirectionState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] * tireLongForce; const PxVec3 tireLatForceVec = tireDirectionState.directions[PxVehicleTireDirectionModes::eLATERAL] * tireLatForce; tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongForceVec; tireForce.forces[PxVehicleTireDirectionModes::eLATERAL] = tireLatForceVec; const PxVec3 r = bodyPose.rotate(suspensionAttachmentPose.transform(tireForceApplicationPoint)); tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL] = r.cross(tireLongForceVec); tireForce.torques[PxVehicleTireDirectionModes::eLATERAL] = r.cross(tireLatForceVec); tireForce.aligningMoment = tireAlignMoment; tireForce.wheelTorque = wheelTorque; } }//namespace snippetvehicle2
8,116
C++
42.406417
142
0.786594
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/SnippetVehicleCustomTire.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. // **************************************************************************** // This snippet illustrates how to change the tire model using custom vehicle components. // // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. In this example, the change has been localised to the tire component // to replace the low fidelity model with the high fidelty . // The low and high fidelity components consume the same state data (tire slip, load, friction) and // output the same state data for the tire forces. Again, the change has been localised to the component // that converts slip angle to tire force and the parameterisation that governs the conversion. // This snippet demonstrates how to modify the vehicle component pipeline to include a custom tire model. // The vehicle is then a mixture of custom components and components maintained by the PhysX Vehicle SDK. // In this instance, the custom component implements a version of the Magic Formula Tire Model (also // known as Pacejka) to compute the tire forces. The Magic Formula Tire Model uses measurements on // real tires to infer the parameters of predefined formulas such that the resulting graphs will fit closely // to the measurement points. //This snippet organises the components into four distinct groups. //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a direct drive drivetrain model that forwards input controls to wheel torques and steer angles. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. //4) a custom tire model // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" #include "CustomTireVehicle.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with the custom tire component CustomTireVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //If sweeps are used for wheel vs. ground collision detection, then //a cylinder mesh (with unit size) needs to be provided to do the sweep. PxConvexMesh* gUnitCylinderSweepMesh = NULL; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The timestep of the simulation const PxReal gTimestep = 1.0f / 60.0f; //The timestep for the tire model simulation. For the Magic Formula //Tire Model a high update rate is recommended, like 1 kHz. const PxReal gTireModelTimestep = 1.0f / 1000.0f; //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "CustomTireVehicle"; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxF32 duration; }; Command gCommands[] = { {0.0f, 0.0f, 0.0f, 2.0f}, //fall on ground and come to rest for 2 seconds {0.0f, 0.5f, 0.0f, 5.0f}, //throttle for 5 seconds {0.5f, 0.0f, 0.0f, 5.0f}, //brake for 5 seconds {0.0f, 0.5f, 0.0f, 5.0f}, //throttle for 5 seconds {0.0f, 0.1f, 0.5f, 5.0f} //light throttle and steer for 5 seconds. }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", gVehicle.mBaseParams.axleDescription, gVehicle.mDirectDriveParams); //Set the states to default. PxCookingParams cookingParams(gPhysics->getTolerancesScale()); if (!gVehicle.initialize(*gPhysics, cookingParams, *gMaterial)) { return false; } gVehicle.mCommandState.nbBrakes = 1; gVehicle.mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eFORWARD; //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(-5.0f, 0.5f, 0.0f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Disabling sleeping in this snippet to show stability at rest is reached independent of //sleeping. gVehicle.mPhysXState.physxActor.rigidBody->is<PxRigidDynamic>()->setSleepThreshold(0.0f); gVehicle.mPhysXState.physxActor.rigidBody->is<PxRigidDynamic>()->setStabilizationThreshold(0.0f); //Set the substep count to match the targeted tire model simulation timestep PxU8 substepCount = static_cast<PxU8>(gTimestep / gTireModelTimestep); gVehicle.mComponentSequence.setSubsteps(gVehicle.mComponentSequenceSubstepGroupHandle, substepCount); //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; gUnitCylinderSweepMesh = PxVehicleUnitCylinderSweepMeshCreate(gVehicleSimulationContext.frame, *gPhysics, cookingParams); if (!gUnitCylinderSweepMesh) { return false; } gVehicleSimulationContext.physxUnitCylinderSweepMesh = gUnitCylinderSweepMesh; //Larger lateral damping factor than default to avoid drift when nearly rest gVehicleSimulationContext.tireStickyParams.stickyParams[PxVehicleTireDirectionModes::eLATERAL].damping = 1.0f; return true; } void cleanupVehicles() { if (gUnitCylinderSweepMesh) PxVehicleUnitCylinderSweepMeshDestroy(gUnitCylinderSweepMesh); gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; //Apply the brake, throttle and steer to the command state of the direct drive vehicle. const Command& command = gCommands[gCommandProgress]; gVehicle.mCommandState.brakes[0] = command.brake; gVehicle.mCommandState.throttle = command.throttle; gVehicle.mCommandState.steer = command.steer; //Forward integrate the vehicle by a single timestep. gVehicle.step(gTimestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(gTimestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += gTimestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char *const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2CustomTire", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. DirectDrivetrainParams directDrivetrainParams; if (!readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if(initPhysics()) { while(gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
16,129
C++
39.024814
127
0.770166
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemallqueries/SnippetQuerySystemAllQueries.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. // **************************************************************************** // This snippet demonstrates all queries supported by the low-level query system. // Please get yourself familiar with SnippetStandaloneQuerySystem first. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "GuQuerySystem.h" #include "GuFactory.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace Gu; #ifdef RENDER_SNIPPET using namespace Snippets; #endif static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static const bool gManualBoundsComputation = false; static const bool gUseDelayedUpdates = true; static const float gBoundsInflation = 0.001f; static bool gPause = false; static bool gOneFrame = false; enum QueryScenario { RAYCAST_CLOSEST, RAYCAST_ANY, RAYCAST_MULTIPLE, SWEEP_CLOSEST, SWEEP_ANY, SWEEP_MULTIPLE, OVERLAP_ANY, OVERLAP_MULTIPLE, NB_SCENES }; static QueryScenario gSceneIndex = RAYCAST_CLOSEST; // Tweak number of created objects per scene static const PxU32 gFactor[NB_SCENES] = { 2, 1, 2, 2, 1, 2, 1, 2 }; // Tweak amplitude of created objects per scene static const float gAmplitude[NB_SCENES] = { 4.0f, 4.0f, 4.0f, 4.0f, 8.0f, 4.0f, 4.0f, 4.0f }; static const PxVec3 gCamPos[NB_SCENES] = { PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-3.404853f, 4.865191f, 17.692263f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), }; static const PxVec3 gCamDir[NB_SCENES] = { PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), }; #define MAX_NB_OBJECTS 32 /////////////////////////////////////////////////////////////////////////////// // The following functions determine how we use the pruner payloads in this snippet static PX_FORCE_INLINE void setupPayload(PrunerPayload& payload, PxU32 objectIndex, const PxGeometryHolder* gh) { payload.data[0] = objectIndex; payload.data[1] = size_t(gh); } static PX_FORCE_INLINE PxU32 getObjectIndexFromPayload(const PrunerPayload& payload) { return PxU32(payload.data[0]); } static PX_FORCE_INLINE const PxGeometry& getGeometryFromPayload(const PrunerPayload& payload) { const PxGeometryHolder* gh = reinterpret_cast<const PxGeometryHolder*>(payload.data[1]); return gh->any(); } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomRaycastHit : PxGeomRaycastHit { PxU32 mObjectIndex; }; struct CustomSweepHit : PxGeomSweepHit { PxU32 mObjectIndex; }; class CustomScene : public Adapter { public: CustomScene(); ~CustomScene() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose, bool isDynamic); void render(); void updateObjects(); void runQueries(); bool raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const; bool raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const; bool raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const; bool sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const; bool sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const; bool sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const; bool overlapAny(const PxGeometry& geom, const PxTransform& pose) const; bool overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const; struct Object { PxGeometryHolder mGeom; ActorShapeData mData; PxVec3 mTouchedColor; bool mTouched; }; PxU32 mNbObjects; Object mObjects[MAX_NB_OBJECTS]; QuerySystem* mQuerySystem; PxU32 mPrunerIndex; }; const PxGeometry& CustomScene::getGeometry(const PrunerPayload& payload) const { PX_ASSERT(!gManualBoundsComputation); return getGeometryFromPayload(payload); } void CustomScene::release() { PX_DELETE(mQuerySystem); PX_DELETE_THIS; } CustomScene::CustomScene() : mNbObjects(0) { const PxU64 contextID = PxU64(this); mQuerySystem = PX_NEW(QuerySystem)(contextID, gBoundsInflation, *this); Pruner* pruner = createAABBPruner(contextID, true, COMPANION_PRUNER_INCREMENTAL, BVH_SPLATTER_POINTS, 4); mPrunerIndex = mQuerySystem->addPruner(pruner, 0); const PxU32 nb = gFactor[gSceneIndex]; for(PxU32 i=0;i<nb;i++) { addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), true); addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f)), true); addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f)), true); addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f)), true); addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f)), true); } #ifdef RENDER_SNIPPET Camera* camera = getCamera(); camera->setPose(gCamPos[gSceneIndex], gCamDir[gSceneIndex]); #endif } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose, bool isDynamic) { PX_ASSERT(mQuerySystem); Object& obj = mObjects[mNbObjects]; obj.mGeom.storeAny(geom); PrunerPayload payload; setupPayload(payload, mNbObjects, &obj.mGeom); if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom, pose, 0.0f, 1.0f + gBoundsInflation); obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, &bounds); } else { obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, NULL); } mNbObjects++; } void CustomScene::updateObjects() { if(!mQuerySystem) return; if(gPause && !gOneFrame) { mQuerySystem->update(true, true); return; } gOneFrame = false; static float time = 0.0f; time += 0.005f; const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; if(!getDynamic(getPrunerInfo(obj.mData))) continue; // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); const float amplitude = gAmplitude[gSceneIndex]; // Compute an arbitrary new pose for this object PxTransform pose; { const float phase = PxPi * 2.0f * float(i)/float(nbObjects); pose.p.z = 0.0f; pose.p.y = sinf(phase+time*1.17f)*amplitude; pose.p.x = cosf(phase+time*1.17f)*amplitude; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; pose.q = PxQuat(rot); pose.q.normalize(); } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj.mGeom.any(), pose, 0.0f, 1.0f + gBoundsInflation); mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, &bounds); } else { mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, NULL); } } mQuerySystem->update(true, true); } namespace { struct CustomPrunerFilterCallback : public PrunerFilterCallback { virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& /*hitFlags*/) { return &getGeometryFromPayload(payload); } }; } static CustomPrunerFilterCallback gFilterCallback; static CachedFuncs gCachedFuncs; /////////////////////////////////////////////////////////////////////////////// // Custom queries. It is not mandatory to use e.g. different raycast queries for different usages - one could just use the same code // for everything. But it is -possible- to do so, the system is flexible enough to let users decide what to do. // Common raycast usage, returns the closest touched object (single hit). bool CustomScene::raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const { DefaultPrunerRaycastClosestCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist, PxHitFlag::eDEFAULT); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); if(CB.mFoundHit) { static_cast<PxGeomRaycastHit&>(hit) = CB.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(CB.mClosestPayload); } return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// // "Shadow feeler" usage, returns boolean result, early exits as soon as an impact is found. bool CustomScene::raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const { DefaultPrunerRaycastAnyCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { // Beware, there is something a bit subtle here. The query can return multiple hits per query and/or // multiple hits per object. For example a raycast against a scene can touch multiple simple objects, // like e.g. multiple spheres, and return the set of touched spheres to users. But a single raycast // against a complex object like a mesh can also return multiple hits, against multiple triangles of // that same mesh. There are use cases for all of these, and it is up to users to decide what they // need. In this example we do "multiple hits per query", but a single hit per mesh. That is, we do // not use PxHitFlag::eMESH_MULTIPLE. That is why our CustomRaycastCallback only has a single // PxGeomRaycastHit member (mLocalHit). struct CustomRaycastMultipleCallback : public DefaultPrunerRaycastCallback { // This mandatory local hit structure is where DefaultPrunerRaycastCallback writes its // temporary hit when traversing the pruners. PxGeomRaycastHit mLocalHit; // This is the user-provided array where we'll write our results. PxArray<CustomRaycastHit>& mHits; CustomRaycastMultipleCallback(PxArray<CustomRaycastHit>& hits, PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) : DefaultPrunerRaycastCallback(filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eDEFAULT, false), mHits (hits) {} // So far this looked similar to the DefaultPrunerRaycastClosestCallback code. But we customize the behavior in // the following function. virtual bool reportHits(const PrunerPayload& payload, PxU32 nbHits, PxGeomRaycastHit* hits) { // Because we didn't use PxHitFlag::eMESH_MULTIPLE we should only be called for a single hit PX_ASSERT(nbHits==1); PX_UNUSED(nbHits); // We process each hit the way we processed the closest hit at the end of CustomScene::raycastClosest CustomRaycastHit customHit; static_cast<PxGeomRaycastHit&>(customHit) = hits[0]; customHit.mObjectIndex = getObjectIndexFromPayload(payload); // Then we gather the new hit in our user-provided array. This is written for clarity, not performance. // Here we could instead call a user-provided callback. mHits.pushBack(customHit); // We return false to tell the system to ignore that hit now (otherwise the code would shrink the ray etc). // This is also the way one does "post filtering". return false; } PX_NOCOPY(CustomRaycastMultipleCallback) }; } // Generic usage, returns all hits touched by the ray, it's up to users to process them / sort them / etc. // We're using a PxArray here but it's an arbitrary choice, one could also return hits via a callback, etc. bool CustomScene::raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const { CustomRaycastMultipleCallback CB(hits, gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// namespace { // The sweep code is more complicated because the swept geometry is arbitrary (to some extent), and for performance reason there is no // generic sweep callback available operating on an anonymous PxGeometry. So the code below is what you can do instead. // It can be simplified in your app though if you know you only need to sweep one kind of geometry (say sphere sweeps). template<class CallbackT> static bool _sweepClosestT(CustomSweepHit& hit, const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eDEFAULT | PxHitFlag::ePRECISE_SWEEP, false); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); if(pcb.mFoundHit) { static_cast<PxGeomSweepHit&>(hit) = pcb.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(pcb.mClosestPayload); } return pcb.mFoundHit; } } // Common sweep usage, returns the closest touched object (single hit). bool CustomScene::sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepClosestT<DefaultPrunerSphereSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepClosestT<DefaultPrunerCapsuleSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepClosestT<DefaultPrunerBoxSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepClosestT<DefaultPrunerConvexSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { // This could easily be combined with _sweepClosestT to make the code shorter. template<class CallbackT> static bool _sweepAnyT(const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eMESH_ANY | PxHitFlag::ePRECISE_SWEEP, true); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return pcb.mFoundHit; } } // Returns boolean result, early exits as soon as an impact is found. bool CustomScene::sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepAnyT<DefaultPrunerSphereSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepAnyT<DefaultPrunerCapsuleSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepAnyT<DefaultPrunerBoxSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepAnyT<DefaultPrunerConvexSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { // We use a similar strategy as for raycasts. Please refer to CustomRaycastMultipleCallback above. template<class BaseCallbackT> struct CustomSweepMultipleCallback : public BaseCallbackT { PxArray<CustomSweepHit>& mHits; CustomSweepMultipleCallback(PxArray<CustomSweepHit>& hits, PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs, const PxGeometry& geom, const PxTransform& pose, const ShapeData& queryVolume, const PxVec3& dir, float distance) : BaseCallbackT (filterCB, funcs, geom, pose, queryVolume, dir, distance, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, false), mHits (hits) {} virtual bool reportHit(const PrunerPayload& payload, PxGeomSweepHit& hit) { CustomSweepHit customHit; static_cast<PxGeomSweepHit&>(customHit) = hit; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomSweepMultipleCallback) }; // Previous template was customizing the callback for multiple hits, this template customizes the previous template for different geoms. template<class CallbackT> static bool _sweepMultipleT(PxArray<CustomSweepHit>& hits, const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CustomSweepMultipleCallback<CallbackT> pcb(hits, gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return hits.size()!=0; } } // Generic usage, returns all hits touched by the swept volume, it's up to users to process them / sort them / etc. // We're using a PxArray here but it's an arbitrary choice, one could also return hits via a callback, etc. bool CustomScene::sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepMultipleT<DefaultPrunerSphereSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepMultipleT<DefaultPrunerCapsuleSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepMultipleT<DefaultPrunerBoxSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepMultipleT<DefaultPrunerConvexSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapAnyCallback : public DefaultPrunerOverlapCallback { bool mFoundHit; CustomOverlapAnyCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mFoundHit(false) {} virtual bool reportHit(const PrunerPayload& /*payload*/) { mFoundHit = true; return false; // Early exits as soon as we hit something } }; } // Simple boolean overlap. The query returns true if the passed shape touches anything, otherwise it returns false if space was free. bool CustomScene::overlapAny(const PxGeometry& geom, const PxTransform& pose) const { CustomOverlapAnyCallback pcb(gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return pcb.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapMultipleCallback : public DefaultPrunerOverlapCallback { PxArray<PxU32>& mHits; CustomOverlapMultipleCallback(PxArray<PxU32>& hits, PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mHits(hits) {} virtual bool reportHit(const PrunerPayload& payload) { // In this example we only return touched objects but we don't go deeper. For triangle meshes we could // here go to the triangle-level and return all touched triangles of a mesh, if needed. To do that we'd // fetch the PxTriangleMeshGeometry from the payload and use PxMeshQuery::findOverlapTriangleMesh. That // call is part of the regular PxMeshQuery API though so it's beyond the scope of this snippet, which is // about the Gu-level query system. Instead here we just retrieve & output the touched object's index: mHits.pushBack(getObjectIndexFromPayload(payload)); return true; // Continue query, call us again for next touched object } PX_NOCOPY(CustomOverlapMultipleCallback) }; } // Gather-touched-objects overlap. The query returns all objects touched by query volume, in an array. // This is an arbitrary choice in this snippet, it would be equally easy to report each object individually // to a user-callback, etc. bool CustomScene::overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const { CustomOverlapMultipleCallback pcb(hits, gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// void CustomScene::runQueries() { if(!mQuerySystem) return; // Reset all touched flags & colors const PxVec3 touchedColor(0.25f, 0.5f, 1.0f); for(PxU32 i=0;i<mNbObjects;i++) { mObjects[i].mTouched = false; mObjects[i].mTouchedColor = touchedColor; } // This is optional, the SIMD guard can be ommited if your app already // setups the FPU/SIMD control word per thread. If not, try to use one // PX_SIMD_GUARD for many queries, rather than one for each query. PX_SIMD_GUARD if(0) mQuerySystem->commitUpdates(); switch(gSceneIndex) { case RAYCAST_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; CustomRaycastHit hit; const bool hasHit = raycastClosest(origin, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, hit.position, PxVec3(1.0f)); DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const bool hasHit = raycastAny(origin, unitDir, maxDist); #ifdef RENDER_SNIPPET if(hasHit) DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f, 0.0f, 0.0f)); else DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.0f, 1.0f, 0.0f)); #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; PxArray<CustomRaycastHit> hits; const bool hasHit = raycastMultiple(origin, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.5f)); const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const CustomRaycastHit& hit = hits[i]; DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxSphereGeometry sweptGeom(0.5f); //const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); CustomSweepHit hit; const bool hasHit = sweepClosest(sweptGeom, pose, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); if(hasHit) { const PxVec3 sweptPos = origin + unitDir * hit.distance; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(0.0f, 1.0f, 0.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxBoxGeometry sweptGeom(PxVec3(0.5f)); PxQuat q(1.1f, 0.1f, 0.8f, 1.4f); q.normalize(); const PxTransform pose(origin, q); const bool hasHit = sweepAny(sweptGeom, pose, unitDir, maxDist); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); { // We only have a boolean result so we're just going to draw a sequence of geoms along // the sweep direction in the appropriate color. const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); const PxU32 nb = 20; for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const PxVec3 sweptPos = origin + unitDir * coeff * maxDist; const PxTransform impactPose(sweptPos, q); renderGeoms(1, &gh, &impactPose, false, color); } } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); PxArray<CustomSweepHit> hits; const bool hasHit = sweepMultiple(sweptGeom, pose, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); if(hasHit) { { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(0.5f)); } // It can be difficult to see what is touching what so we use different colors to make it clearer. const PxVec3 touchedColors[] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f), PxVec3(1.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 1.0f), PxVec3(1.0f, 1.0f, 0.0f), PxVec3(1.0f, 1.0f, 1.0f), PxVec3(0.5f, 0.5f, 0.5f), }; const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const PxVec3& shapeTouchedColor = touchedColors[i]; const CustomSweepHit& hit = hits[i]; const PxVec3 sweptPos = origin + unitDir * hit.distance; const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, shapeTouchedColor); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; mObjects[hit.mObjectIndex].mTouchedColor = shapeTouchedColor; } } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_ANY: { const PxVec3 origin(0.0f, 4.0f, 0.0f); const PxSphereGeometry queryGeom(0.5f); const PxTransform pose(origin); const bool hasHit = overlapAny(queryGeom, pose); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_MULTIPLE: { const PxVec3 origin(0.0f, 4.0f, 0.0f); const PxSphereGeometry queryGeom(0.5f); const PxTransform pose(origin); PxArray<PxU32> hits; const bool hasHit = overlapMultiple(queryGeom, pose, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); for(PxU32 i=0;i<hits.size();i++) mObjects[hits[i]].mTouched = true; } #else PX_UNUSED(hasHit); #endif } break; case NB_SCENES: // Blame pedantic compilers { } break; } } void CustomScene::render() { updateObjects(); runQueries(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PrunerPayloadData ppd; mQuerySystem->getPayloadData(obj.mData, &ppd); //DrawBounds(*bounds); const PxVec3& objectColor = obj.mTouched ? obj.mTouchedColor : color; renderGeoms(1, &obj.mGeom, ppd.mTransform, false, objectColor); } //mQuerySystem->visualize(true, true, PxRenderOutput) #endif } } static CustomScene* gScene = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; { { const PxF32 width = 3.0f; const PxF32 radius = 1.0f; PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } PxConvexMeshDesc convexDesc; convexDesc.points.count = 32; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = points; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; gConvexMesh = PxCreateConvexMesh(params, convexDesc); } { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } } gScene = new CustomScene; } void renderScene() { if(gScene) gScene->render(); #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F8 to select a scenario."); switch(PxU32(gSceneIndex)) { case RAYCAST_CLOSEST: { Snippets::print("Current scenario: raycast closest"); }break; case RAYCAST_ANY: { Snippets::print("Current scenario: raycast any"); }break; case RAYCAST_MULTIPLE: { Snippets::print("Current scenario: raycast multiple"); }break; case SWEEP_CLOSEST: { Snippets::print("Current scenario: sweep closest"); }break; case SWEEP_ANY: { Snippets::print("Current scenario: sweep any"); }break; case SWEEP_MULTIPLE: { Snippets::print("Current scenario: sweep multiple"); }break; case OVERLAP_ANY: { Snippets::print("Current scenario: overlap any"); }break; case OVERLAP_MULTIPLE: { Snippets::print("Current scenario: overlap multiple"); }break; } #endif } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetQuerySystemAllQueries done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(gScene) { if(key=='p' || key=='P') { gPause = !gPause; } else if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } else { if(key>=1 && key<=NB_SCENES) { gSceneIndex = QueryScenario(key-1); PX_RELEASE(gScene); gScene = new CustomScene; } } } } int snippetMain(int, const char*const*) { printf("Query System All Queries snippet.\n"); printf("Press F1 to F8 to select a scene:\n"); printf(" F1......raycast closest\n"); printf(" F2..........raycast any\n"); printf(" F3.....raycast multiple\n"); printf(" F4........sweep closest\n"); printf(" F5............sweep any\n"); printf(" F6.......sweep multiple\n"); printf(" F7..........overlap any\n"); printf(" F8.....overlap multiple\n"); printf("\n"); printf("Press P to Pause.\n"); printf("Press O to step the simulation One frame.\n"); printf("Press the cursor keys to move the camera.\n"); printf("Use the mouse/left mouse button to rotate the camera.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
36,068
C++
32.182153
186
0.6999
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemallqueries/SnippetQuerySystemAllQueriesRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet QuerySystemAllQueries", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,909
C++
33.642857
117
0.75043
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmbp/SnippetMBP.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. // **************************************************************************** // This snippet demonstrates the use of broad phase regions (MBP). // // It shows the setup of MBP and its regions. In this example 4 regions are setup // and set for the MBP. Created stacks are then simulated in multiple regions. // Note that current regions setup is not optimal, some objects get out of regions bounds. // In this case a warning is reported. It is possible to add PxBroadPhaseCallback // to scene to handle such cases. // // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxReal stackZ = 10.0f; PxU32 gRegionHandles[4]; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } class SnippetMBPBroadPhaseCallback : public physx::PxBroadPhaseCallback { std::vector<PxActor*> outOfBoundsActors; public: virtual void onObjectOutOfBounds(PxShape& /*shape*/, PxActor& actor) { PxU32 i = 0; for(; i < outOfBoundsActors.size(); ++i) { if(outOfBoundsActors[i] == &actor) break; } if(i == outOfBoundsActors.size()) { outOfBoundsActors.push_back(&actor); } } virtual void onObjectOutOfBounds(PxAggregate& /*aggregate*/) { //This test does not use aggregates so no need to do anything here } void purgeOutOfBoundsObjects() { for(PxU32 i = 0; i < outOfBoundsActors.size(); ++i) { outOfBoundsActors[i]->release(); } outOfBoundsActors.clear(); } } gBroadPhaseCallback; void initPhysics(bool interactive) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.broadPhaseType = PxBroadPhaseType::eMBP; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } PxBroadPhaseRegion regions[4] = { { PxBounds3(PxVec3(-100, -100, -100), PxVec3( 0, 100, 0)), reinterpret_cast<void*>(1) }, { PxBounds3(PxVec3(-100, -100, 0), PxVec3( 0, 100, 100)), reinterpret_cast<void*>(2) }, { PxBounds3(PxVec3( 0, -100, -100), PxVec3(100, 100, 0)), reinterpret_cast<void*>(3) }, { PxBounds3(PxVec3( 0, -100, 0), PxVec3(100, 100, 100)), reinterpret_cast<void*>(4) } }; for(PxU32 i=0;i<4;i++) gScene->addBroadPhaseRegion(regions[i]); gScene->setBroadPhaseCallback(&gBroadPhaseCallback); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); for(PxU32 i=0;i<5;i++) createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); if(!interactive) createDynamic(PxTransform(PxVec3(0,40,100)), PxSphereGeometry(10), PxVec3(0,-50,-100)); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); gBroadPhaseCallback.purgeOutOfBoundsObjects(); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMBP done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case 'B': createStack(PxTransform(PxVec3(0,0,stackZ-=10.0f)), 10, 2.0f); break; case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,591
C++
33.352941
120
0.719273
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmbp/SnippetMBPRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet MBP", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,997
C++
33.860465
136
0.758759
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfixedtendon/SnippetFixedTendon.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. // *************************************************************************************** // This snippet demonstrates the use of a fixed tendon to mirror articulation joint angles // *************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulation = NULL; static PxArticulationJointReducedCoordinate* gDriveJoint = NULL; static const PxReal gGravity = 9.81f; static PxReal gDriveTargetPos = 0.0f; static void createArticulation() { gArticulation->setArticulationFlags(PxArticulationFlag::eFIX_BASE); gArticulation->setSolverIterationCounts(10, 1); // link geometry and density: const PxVec3 halfLengths(0.50f, 0.05f, 0.05f); const PxBoxGeometry linkGeom = PxBoxGeometry(halfLengths); const PxReal density = 1000.0f; //Create links PxTransform pose = PxTransform(PxIdentity); pose.p.y = 3.0f; pose.p.x -= 2.0f * halfLengths.x; PxArticulationLink* parent = NULL; const PxU32 numLinks = 3; for(PxU32 j = 0; j < numLinks; ++j) { pose.p.x += 2.0f * halfLengths.x; parent = gArticulation->createLink(parent, pose); PxRigidActorExt::createExclusiveShape(*parent, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*parent, density); PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(parent->getInboundJoint()); if(joint) { PxVec3 parentOffset(halfLengths.x, 0.0f, 0.0f); PxVec3 childOffset(-halfLengths.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } // tendon and drive stiffness sizing // assuming all links extend horizontally, size to allow for two degrees // deviation due to gravity const PxReal linkMass = parent->getMass(); const PxReal deflectionAngle = 2.0f * PxPi / 180.0f; // two degrees // moment arm of first link is one half-length, for second it is three half-lengths const PxReal gravityTorque = gGravity * linkMass * (halfLengths.x + 3.0f * halfLengths.x); const PxReal driveStiffness = gravityTorque / deflectionAngle; const PxReal driveDamping = 0.2f * driveStiffness; // same idea for the tendon, but it has to support only a single link const PxReal tendonStiffness = gGravity * linkMass * halfLengths.x / deflectionAngle; const PxReal tendonDamping = 0.2f * tendonStiffness; // compute drive target angle that compensates, statically, for the first fixed tendon joint // torque acting on the drive joint: const PxReal targetAngle = PxPiDivFour; const PxReal tendonTorque = targetAngle * tendonStiffness; gDriveTargetPos = targetAngle + tendonTorque / driveStiffness; // setup fixed tendon PxArticulationLink* links[numLinks]; gArticulation->getLinks(links, numLinks, 0u); PxArticulationFixedTendon* tendon = gArticulation->createFixedTendon(); tendon->setLimitStiffness(0.0f); tendon->setDamping(tendonDamping); tendon->setStiffness(tendonStiffness); tendon->setRestLength(0.f); tendon->setOffset(0.f); PxArticulationTendonJoint* tendonParentJoint = NULL; // root fixed-tendon joint - does not contribute to length so its coefficient and axis are irrelevant // but its parent link experiences all tendon-joint reaction forces tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, 42.0f, 1.f/42.f, links[0]); // drive joint tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, 1.0f, 1.f, links[1]); // second joint that is driven only by the tendon - negative coefficient to mirror angle of drive joint tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, -1.0f, -1.0f, links[2]); // configure joint drive gDriveJoint = links[1]->getInboundJoint(); PxArticulationDrive driveConfiguration; driveConfiguration.damping = driveDamping; driveConfiguration.stiffness = driveStiffness; driveConfiguration.maxForce = PX_MAX_F32; driveConfiguration.driveType = PxArticulationDriveType::eFORCE; gDriveJoint->setDriveParams(PxArticulationAxis::eSWING2, driveConfiguration); gDriveJoint->setDriveVelocity(PxArticulationAxis::eSWING2, 0.0f); gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, 0.0f); // add articulation to scene: gScene->addArticulation(*gArticulation); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -gGravity, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); gArticulation = gPhysics->createArticulationReducedCoordinate(); createArticulation(); } void stepPhysics(bool /*interactive*/) { static bool dir = false; static PxReal time = 0.0f; const PxReal switchTime = 3.0f; const PxReal dt = 1.0f / 60.f; time += dt; if(time > switchTime) { if(dir) { gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, 0.0f); } else { gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, gDriveTargetPos); } dir = !dir; time = 0.0f; } gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gArticulation); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetFixedTendon done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
8,907
C++
38.591111
126
0.74593
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfixedtendon/SnippetFixedTendonRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 dynLinkColor(1.0f, 0.5f, 0.25f); const PxVec3 baseLinkColor(0.5f, 0.25f, 1.0f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbArticulations = scene->getNbArticulations(); for(PxU32 i=0;i<nbArticulations;i++) { PxArticulationReducedCoordinate* articulation; scene->getArticulations(&articulation, 1, i); const PxU32 nbLinks = articulation->getNbLinks(); std::vector<PxArticulationLink*> links(nbLinks); articulation->getLinks(&links[0], nbLinks); PxReal colorScale = 1.0f; if(articulation->isSleeping()) colorScale = 0.4f; const PxU32 numLinks = static_cast<PxU32>(links.size()); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[0]), 1, true, colorScale * baseLinkColor); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[1]), numLinks - 1, true, colorScale * dynLinkColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { const PxVec3 camEye(3.3f, 2.95f, 3.2f); const PxVec3 camDir(-0.5f, -0.078f, -0.86f); sCamera = new Snippets::Camera(camEye, camDir); Snippets::setupDefault("PhysX Snippet Articulation Fixed Tendon", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,420
C++
32.539215
117
0.752047
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatearticulation/SnippetImmediateArticulationRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; using namespace immediate; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxU32 getNbGeoms(); extern const PxGeometryHolder* getGeoms(); extern const PxTransform* getGeomPoses(); extern PxU32 getNbContacts(); extern const PxContactPoint* getContacts(); extern PxU32 getNbArticulations(); extern PxArticulationHandle* getArticulations(); extern PxU32 getNbBounds(); extern const PxBounds3* getBounds(); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); /* if(0) { PxVec3 camPos = sCamera->getEye(); PxVec3 camDir = sCamera->getDir(); printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); }*/ Snippets::startRender(sCamera); const PxVec3 color(0.6f, 0.8f, 1.0f); // const PxVec3 color(0.75f, 0.75f, 1.0f); // const PxVec3 color(1.0f); Snippets::renderGeoms(getNbGeoms(), getGeoms(), getGeomPoses(), true, color); /* PxU32 getNbGeoms(); const PxGeometry* getGeoms(); const PxTransform* getGeomPoses(); Snippets::renderGeoms(getNbGeoms(), getGeoms(), getGeomPoses(), true, PxVec3(1.0f));*/ /* PxBoxGeometry boxGeoms[10]; for(PxU32 i=0;i<10;i++) boxGeoms[i].halfExtents = PxVec3(1.0f); PxTransform poses[10]; for(PxU32 i=0;i<10;i++) { poses[i] = PxTransform(PxIdentity); poses[i].p.y += 1.5f; poses[i].p.x = float(i)*2.5f; } Snippets::renderGeoms(10, boxGeoms, poses, true, PxVec3(1.0f));*/ if(1) { const PxU32 nbContacts = getNbContacts(); const PxContactPoint* contacts = getContacts(); for(PxU32 j=0;j<nbContacts;j++) { Snippets::DrawFrame(contacts[j].point, 1.0f); } } if(0) { const PxU32 nbArticulations = getNbArticulations(); PxArticulationHandle* articulations = getArticulations(); for(PxU32 j=0;j<nbArticulations;j++) { immediate::PxArticulationLinkDerivedDataRC data[64]; const PxU32 nbLinks = immediate::PxGetAllLinkData(articulations[j], data); for(PxU32 i=0;i<nbLinks;i++) { Snippets::DrawFrame(data[i].pose.p, 1.0f); } } } const PxBounds3* bounds = getBounds(); const PxU32 nbBounds = getNbBounds(); for(PxU32 i=0;i<nbBounds;i++) { Snippets::DrawBounds(bounds[i]); } renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera( PxVec3(8.526230f, 5.546278f, 5.448466f), PxVec3(-0.784231f, -0.210605f, -0.583632f)); Snippets::setupDefault("PhysX Snippet Immediate Articulation", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
4,717
C++
29.24359
113
0.728641
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatearticulation/SnippetImmediateArticulation.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. // **************************************************************************** // This snippet demonstrates the use of immediate articulations. // **************************************************************************** #include "PxImmediateMode.h" #include "PxMaterial.h" #include "geometry/PxGeometryQuery.h" #include "geometry/PxConvexMesh.h" #include "foundation/PxPhysicsVersion.h" #include "foundation/PxArray.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "foundation/PxMathUtils.h" #include "foundation/PxFPU.h" #include "cooking/PxCooking.h" #include "cooking/PxConvexMeshDesc.h" #include "ExtConstraintHelper.h" #include "extensions/PxMassProperties.h" #include "extensions/PxDefaultAllocator.h" #include "extensions/PxDefaultErrorCallback.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetutils/SnippetImmUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif //Enables TGS or PGS solver #define USE_TGS 0 //#define PRINT_TIMINGS #define TEST_IMMEDIATE_JOINTS //Enables whether we want persistent state caching (contact cache, friction caching) or not. Avoiding persistency results in one-shot collision detection and zero friction //correlation but simplifies code by not longer needing to cache persistent pairs. #define WITH_PERSISTENCY 1 //Toggles whether we batch constraints or not. Constraint batching is an optional process which can improve performance by grouping together independent constraints. These independent constraints //can be solved in parallel by using multiple lanes of SIMD registers. #define BATCH_CONTACTS 1 using namespace physx; using namespace immediate; using namespace SnippetImmUtils; static const PxVec3 gGravity(0.0f, -9.81f, 0.0f); static const float gContactDistance = 0.1f; static const float gMeshContactMargin = 0.01f; static const float gToleranceLength = 1.0f; static const float gBounceThreshold = -2.0f; static const float gFrictionOffsetThreshold = 0.04f; static const float gCorrelationDistance = 0.025f; static const float gBoundsInflation = 0.02f; static const float gStaticFriction = 0.5f; static const float gDynamicFriction = 0.5f; static const float gRestitution = 0.0f; static const float gMaxDepenetrationVelocity = 10.0f; static const float gMaxContactImpulse = FLT_MAX; static const float gLinearDamping = 0.1f; static const float gAngularDamping = 0.05f; static const float gMaxLinearVelocity = 100.0f; static const float gMaxAngularVelocity = 100.0f; static const float gJointFrictionCoefficient = 0.05f; static const PxU32 gNbIterPos = 4; static const PxU32 gNbIterVel = 1; static bool gPause = false; static bool gOneFrame = false; static bool gDrawBounds = false; static PxU32 gSceneIndex = 2; static float gTime = 0.0f; #if WITH_PERSISTENCY struct PersistentContactPair { PersistentContactPair() { reset(); } PxCache cache; PxU8* frictions; PxU32 nbFrictions; PX_FORCE_INLINE void reset() { cache = PxCache(); frictions = NULL; nbFrictions = 0; } }; #endif struct IDS { PX_FORCE_INLINE IDS(PxU32 id0, PxU32 id1) : mID0(id0), mID1(id1) {} PxU32 mID0; PxU32 mID1; PX_FORCE_INLINE bool operator == (const IDS& other) const { return mID0 == other.mID0 && mID1 == other.mID1; } }; PX_FORCE_INLINE uint32_t PxComputeHash(const IDS& p) { return PxComputeHash(uint64_t(p.mID0)|(uint64_t(p.mID1)<<32)); } struct MassProps { PxVec3 mInvInertia; float mInvMass; }; static void computeMassProps(MassProps& props, const PxGeometry& geometry, float mass) { if(mass!=0.0f) { PxMassProperties inertia(geometry); inertia = inertia * (mass/inertia.mass); PxQuat orient; const PxVec3 diagInertia = PxMassProperties::getMassSpaceInertia(inertia.inertiaTensor, orient); props.mInvMass = 1.0f/inertia.mass; props.mInvInertia.x = diagInertia.x == 0.0f ? 0.0f : 1.0f/diagInertia.x; props.mInvInertia.y = diagInertia.y == 0.0f ? 0.0f : 1.0f/diagInertia.y; props.mInvInertia.z = diagInertia.z == 0.0f ? 0.0f : 1.0f/diagInertia.z; } else { props.mInvMass = 0.0f; props.mInvInertia = PxVec3(0.0f); } } #ifdef TEST_IMMEDIATE_JOINTS struct MyJointData : Ext::JointData { PxU32 mActors[2]; PxTransform mLocalFrames[2]; void initInvMassScale() { invMassScale.linear0 = 1.0f; invMassScale.angular0 = 1.0f; invMassScale.linear1 = 1.0f; invMassScale.angular1 = 1.0f; } }; #endif class ImmediateScene { PX_NOCOPY(ImmediateScene) public: ImmediateScene(); ~ImmediateScene(); void reset(); PxU32 createActor(const PxGeometry& geometry, const PxTransform& pose, const MassProps* massProps=NULL, PxArticulationLinkCookie* linkCookie=0); void createGroundPlane() { createActor(PxPlaneGeometry(), PxTransformFromPlaneEquation(PxPlane(0.0f, 1.0f, 0.0f, 0.0f))); } void createScene(); #ifdef TEST_IMMEDIATE_JOINTS void createSphericalJoint(PxU32 id0, PxU32 id1, const PxTransform& localFrame0, const PxTransform& localFrame1, const PxTransform* pose0=NULL, const PxTransform* pose1=NULL); #endif void updateArticulations(float dt); void updateBounds(); void broadPhase(); void narrowPhase(); void buildSolverBodyData(float dt); void buildSolverConstraintDesc(); void createContactConstraints(float dt, float invDt, float lengthScale, PxU32 nbPositionIterations); void solveAndIntegrate(float dt); TestCacheAllocator* mCacheAllocator; TestConstraintAllocator* mConstraintAllocator; // PT: TODO: revisit this basic design once everything works PxArray<PxGeometryHolder> mGeoms; PxArray<PxTransform> mPoses; PxArray<PxBounds3> mBounds; class ImmediateActor { public: ImmediateActor() {} ~ImmediateActor() {} enum Type { eSTATIC, eDYNAMIC, eLINK, }; Type mType; PxU32 mCollisionGroup; MassProps mMassProps; PxVec3 mLinearVelocity; PxVec3 mAngularVelocity; // PT: ### TODO: revisit, these two could be a union, the cookie is only needed for a brief time during scene creation // Or move them to a completely different / hidden array PxArticulationLinkCookie mLinkCookie; PxArticulationLinkHandle mLink; }; PxArray<ImmediateActor> mActors; #if USE_TGS PxArray<PxTGSSolverBodyData> mSolverBodyData; PxArray<PxTGSSolverBodyVel> mSolverBodies; PxArray<PxTGSSolverBodyTxInertia> mSolverBodyTxInertias; #else PxArray<PxSolverBodyData> mSolverBodyData; PxArray<PxSolverBody> mSolverBodies; #endif PxArray<PxArticulationHandle> mArticulations; PxArray<PxSpatialVector> mTempZ; PxArray<PxSpatialVector> mTempDeltaV; #ifdef TEST_IMMEDIATE_JOINTS PxArray<MyJointData> mJointData; #endif PxArray<IDS> mBroadphasePairs; PxHashSet<IDS> mFilteredPairs; struct ContactPair { PxU32 mID0; PxU32 mID1; PxU32 mNbContacts; PxU32 mStartContactIndex; }; // PT: we use separate arrays here because the immediate mode API expects an array of PxContactPoint PxArray<ContactPair> mContactPairs; PxArray<PxContactPoint> mContactPoints; #if WITH_PERSISTENCY PxHashMap<IDS, PersistentContactPair> mPersistentPairs; #endif PxArray<PxSolverConstraintDesc> mSolverConstraintDesc; #if BATCH_CONTACTS PxArray<PxSolverConstraintDesc> mOrderedSolverConstraintDesc; #endif PxArray<PxConstraintBatchHeader> mHeaders; PxArray<PxReal> mContactForces; PxArray<PxVec3> mMotionLinearVelocity; // Persistent to avoid runtime allocations but could be managed on the stack PxArray<PxVec3> mMotionAngularVelocity; // Persistent to avoid runtime allocations but could be managed on the stack PxU32 mNbStaticActors; PxU32 mNbArticulationLinks; PxU32 mMaxNumArticulationsLinks; PX_FORCE_INLINE void disableCollision(PxU32 i, PxU32 j) { if(i>j) PxSwap(i, j); mFilteredPairs.insert(IDS(i, j)); } PX_FORCE_INLINE bool isCollisionDisabled(PxU32 i, PxU32 j) const { if(i>j) PxSwap(i, j); return mFilteredPairs.contains(IDS(i, j)); } PxArticulationLinkCookie mMotorLinkCookie; PxArticulationLinkHandle mMotorLink; PxArticulationHandle endCreateImmediateArticulation(PxArticulationCookie immArt); void allocateTempBuffer(const PxU32 maxLinks); }; ImmediateScene::ImmediateScene() : mNbStaticActors (0), mNbArticulationLinks (0), mMaxNumArticulationsLinks (0), mMotorLinkCookie (PxCreateArticulationLinkCookie()), mMotorLink (PxArticulationLinkHandle()) { mCacheAllocator = new TestCacheAllocator; mConstraintAllocator = new TestConstraintAllocator; } ImmediateScene::~ImmediateScene() { reset(); PX_DELETE(mConstraintAllocator); PX_DELETE(mCacheAllocator); } void ImmediateScene::reset() { mGeoms.clear(); mPoses.clear(); mBounds.clear(); mActors.clear(); mSolverBodyData.clear(); mSolverBodies.clear(); #if USE_TGS mSolverBodyTxInertias.clear(); #endif mBroadphasePairs.clear(); mFilteredPairs.clear(); mContactPairs.clear(); mContactPoints.clear(); mSolverConstraintDesc.clear(); #if BATCH_CONTACTS mOrderedSolverConstraintDesc.clear(); #endif mHeaders.clear(); mContactForces.clear(); mMotionLinearVelocity.clear(); mMotionAngularVelocity.clear(); const PxU32 size = mArticulations.size(); for(PxU32 i=0;i<size;i++) PxReleaseArticulation(mArticulations[i]); mArticulations.clear(); #ifdef TEST_IMMEDIATE_JOINTS mJointData.clear(); #endif #if WITH_PERSISTENCY mPersistentPairs.clear(); #endif mNbStaticActors = mNbArticulationLinks = 0; mMotorLinkCookie = PxCreateArticulationLinkCookie(); mMotorLink = PxArticulationLinkHandle(); gTime = 0.0f; } PxU32 ImmediateScene::createActor(const PxGeometry& geometry, const PxTransform& pose, const MassProps* massProps, PxArticulationLinkCookie* linkCookie) { const PxU32 id = mActors.size(); // PT: we don't support compounds in this simple snippet. 1 actor = 1 shape/geom. PX_ASSERT(mGeoms.size()==id); PX_ASSERT(mPoses.size()==id); PX_ASSERT(mBounds.size()==id); const bool isStaticActor = !massProps; if(isStaticActor) { PX_ASSERT(!linkCookie); mNbStaticActors++; } else { // PT: make sure we don't create dynamic actors after static ones. We could reorganize the array but // in this simple snippet we just enforce the order in which actors are created. PX_ASSERT(!mNbStaticActors); if(linkCookie) mNbArticulationLinks++; } ImmediateActor actor; if(isStaticActor) actor.mType = ImmediateActor::eSTATIC; else if(linkCookie) actor.mType = ImmediateActor::eLINK; else actor.mType = ImmediateActor::eDYNAMIC; actor.mCollisionGroup = 0; actor.mLinearVelocity = PxVec3(0.0f); actor.mAngularVelocity = PxVec3(0.0f); actor.mLinkCookie = linkCookie ? *linkCookie : PxCreateArticulationLinkCookie(); actor.mLink = PxArticulationLinkHandle(); // Not available yet if(massProps) actor.mMassProps = *massProps; else { actor.mMassProps.mInvMass = 0.0f; actor.mMassProps.mInvInertia = PxVec3(0.0f); } mActors.pushBack(actor); #if USE_TGS mSolverBodyData.pushBack(PxTGSSolverBodyData()); mSolverBodies.pushBack(PxTGSSolverBodyVel()); mSolverBodyTxInertias.pushBack(PxTGSSolverBodyTxInertia()); #else mSolverBodyData.pushBack(PxSolverBodyData()); mSolverBodies.pushBack(PxSolverBody()); #endif mGeoms.pushBack(geometry); mPoses.pushBack(pose); mBounds.pushBack(PxBounds3()); return id; } static PxArticulationCookie beginCreateImmediateArticulation(bool fixBase) { PxArticulationDataRC data; data.flags = fixBase ? PxArticulationFlag::eFIX_BASE : PxArticulationFlag::Enum(0); return PxBeginCreateArticulationRC(data); } void ImmediateScene::allocateTempBuffer(const PxU32 maxLinks) { mTempZ.resize(maxLinks); mTempDeltaV.resize(maxLinks); } PxArticulationHandle ImmediateScene::endCreateImmediateArticulation(PxArticulationCookie immArt) { PxU32 expectedNbLinks = 0; const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mLinkCookie.articulation) expectedNbLinks++; } PxArticulationLinkHandle* realLinkHandles = PX_ALLOCATE(PxArticulationLinkHandle, sizeof(PxArticulationLinkHandle) * expectedNbLinks, "PxArticulationLinkHandle"); PxArticulationHandle immArt2 = PxEndCreateArticulationRC(immArt, realLinkHandles, expectedNbLinks); mArticulations.pushBack(immArt2); mMaxNumArticulationsLinks = PxMax(mMaxNumArticulationsLinks, expectedNbLinks); PxU32 nbLinks = 0; for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mLinkCookie.articulation) mActors[i].mLink = realLinkHandles[nbLinks++]; } PX_ASSERT(expectedNbLinks==nbLinks); PX_FREE(realLinkHandles); return immArt2; } static void setupCommonLinkData(PxArticulationLinkDataRC& data, const PxTransform& pose, const MassProps& massProps) { data.pose = pose; data.inverseMass = massProps.mInvMass; data.inverseInertia = massProps.mInvInertia; data.linearDamping = gLinearDamping; data.angularDamping = gAngularDamping; data.maxLinearVelocitySq = gMaxLinearVelocity * gMaxLinearVelocity; data.maxAngularVelocitySq = gMaxAngularVelocity * gMaxAngularVelocity; data.inboundJoint.frictionCoefficient = gJointFrictionCoefficient; } #ifdef TEST_IMMEDIATE_JOINTS void ImmediateScene::createSphericalJoint(PxU32 id0, PxU32 id1, const PxTransform& localFrame0, const PxTransform& localFrame1, const PxTransform* pose0, const PxTransform* pose1) { const bool isStatic0 = mActors[id0].mType == ImmediateActor::eSTATIC; const bool isStatic1 = mActors[id1].mType == ImmediateActor::eSTATIC; MyJointData jointData; jointData.mActors[0] = id0; jointData.mActors[1] = id1; jointData.mLocalFrames[0] = localFrame0; jointData.mLocalFrames[1] = localFrame1; if(isStatic0) jointData.c2b[0] = pose0->getInverse().transformInv(localFrame0); else jointData.c2b[0] = localFrame0; if(isStatic1) jointData.c2b[1] = pose1->getInverse().transformInv(localFrame1); else jointData.c2b[1] = localFrame1; jointData.initInvMassScale(); mJointData.pushBack(jointData); disableCollision(id0, id1); } #endif void ImmediateScene::createScene() { mMotorLink = PxArticulationLinkHandle(); const PxU32 index = gSceneIndex; if(index==0) { // Box stack { const PxVec3 extents(0.5f, 0.5f, 0.5f); const PxBoxGeometry boxGeom(extents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); // for(PxU32 i=0;i<8;i++) // createBox(extents, PxTransform(PxVec3(0.0f, extents.y + float(i)*extents.y*2.0f, 0.0f)), 1.0f); PxU32 size = 8; // PxU32 size = 2; // PxU32 size = 1; float y = extents.y; float x = 0.0f; while(size) { for(PxU32 i=0;i<size;i++) createActor(boxGeom, PxTransform(PxVec3(x+float(i)*extents.x*2.0f, y, 0.0f)), &massProps); x += extents.x; y += extents.y*2.0f; size--; } } createGroundPlane(); } else if(index==1) { // Simple scene with regular spherical joint #ifdef TEST_IMMEDIATE_JOINTS const float boxSize = 1.0f; const PxVec3 extents(boxSize, boxSize, boxSize); const PxBoxGeometry boxGeom(extents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxVec3 staticPos(0.0f, 6.0f, 0.0f); const PxVec3 dynamicPos = staticPos - extents*2.0f; const PxTransform dynPose(dynamicPos); const PxTransform staticPose(staticPos); const PxU32 dynamicObject = createActor(boxGeom, dynPose, &massProps); const PxU32 staticObject = createActor(boxGeom, staticPose); createSphericalJoint(staticObject, dynamicObject, PxTransform(-extents), PxTransform(extents), &staticPose, &dynPose); #endif } else if(index==2) { // RC articulation with contacts if(1) { const PxBoxGeometry boxGeom(PxVec3(1.0f)); MassProps massProps; computeMassProps(massProps, boxGeom, 0.5f); createActor(boxGeom, PxTransform(PxVec3(0.0f, 1.0f, 0.0f)), &massProps); } const PxU32 nbLinks = 6; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); createGroundPlane(); } else if(index==3) { // RC articulation with limits const PxU32 nbLinks = 4; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi/8.0f; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi/8.0f; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); } else if(index==4) { if(0) { const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(false); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); PX_UNUSED(baseID); } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); return; } // RC articulation with drive const PxU32 nbLinks = 1; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].stiffness = 0.0f; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].damping = 1000.0f; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].maxForce = FLT_MAX; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].driveType = PxArticulationDriveType::eFORCE; linkData.inboundJoint.targetVel[PxArticulationAxis::eTWIST] = 4.0f; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); mMotorLinkCookie = link; mMotorLink = PxArticulationLinkHandle(); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); //### not nice, revisit mMotorLink = mActors[1].mLink; } else if(index==5) { // Scissor lift const PxReal runnerLength = 2.f; const PxReal placementDistance = 1.8f; const PxReal cosAng = (placementDistance) / (runnerLength); const PxReal angle = PxAcos(cosAng); const PxReal sinAng = PxSin(angle); const PxQuat leftRot(-angle, PxVec3(1.f, 0.f, 0.f)); const PxQuat rightRot(angle, PxVec3(1.f, 0.f, 0.f)); PxArticulationCookie immArt = beginCreateImmediateArticulation(false); // PxArticulationLinkCookie base; PxU32 baseID; { const PxBoxGeometry boxGeom(0.5f, 0.25f, 1.5f); MassProps massProps; computeMassProps(massProps, boxGeom, 3.0f); const PxTransform pose(PxVec3(0.f, 0.25f, 0.f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, pose, &massProps, &base); } // PxArticulationLinkCookie leftRoot; PxU32 leftRootID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, 0.55f, -0.9f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eFIX; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.25f, -0.9f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.05f, 0.f)); leftRoot = PxAddArticulationLink(immArt, &base, linkData); leftRootID = createActor(boxGeom, pose, &massProps, &leftRoot); disableCollision(baseID, leftRootID); } // PxArticulationLinkCookie rightRoot; PxU32 rightRootID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, 0.55f, 0.9f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::ePRISMATIC; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.25f, 0.9f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.05f, 0.f)); linkData.inboundJoint.motion[PxArticulationAxis::eZ] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eZ].low = -1.4f; linkData.inboundJoint.limits[PxArticulationAxis::eZ].high = 0.2f; if(0) { linkData.inboundJoint.drives[PxArticulationAxis::eZ].stiffness = 100000.f; linkData.inboundJoint.drives[PxArticulationAxis::eZ].damping = 0.f; linkData.inboundJoint.drives[PxArticulationAxis::eZ].maxForce = PX_MAX_F32; linkData.inboundJoint.drives[PxArticulationAxis::eZ].driveType = PxArticulationDriveType::eFORCE; } rightRoot = PxAddArticulationLink(immArt, &base, linkData); rightRootID = createActor(boxGeom, pose, &massProps, &rightRoot); disableCollision(baseID, rightRootID); } // const PxU32 linkHeight = 3; PxU32 currLeftID = leftRootID; PxU32 currRightID = rightRootID; PxArticulationLinkCookie currLeft = leftRoot; PxArticulationLinkCookie currRight = rightRoot; PxQuat rightParentRot(PxIdentity); PxQuat leftParentRot(PxIdentity); for(PxU32 i=0; i<linkHeight; ++i) { const PxVec3 pos(0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLinkCookie leftLink; PxU32 leftLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currLeftID].transformInv(leftAnchorLocation), leftParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = angle; leftLink = PxAddArticulationLink(immArt, &currLeft, linkData); leftLinkID = createActor(boxGeom, pose, &massProps, &leftLink); disableCollision(currLeftID, leftLinkID); mActors[leftLinkID].mCollisionGroup = 1; } leftParentRot = leftRot; // PxArticulationLinkCookie rightLink; PxU32 rightLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currRightID].transformInv(rightAnchorLocation), rightParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -angle; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi; rightLink = PxAddArticulationLink(immArt, &currRight, linkData); rightLinkID = createActor(boxGeom, pose, &massProps, &rightLink); disableCollision(currRightID, rightLinkID); mActors[rightLinkID].mCollisionGroup = 1; } rightParentRot = rightRot; #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(leftLinkID, rightLinkID, PxTransform(PxIdentity), PxTransform(PxIdentity)); #else disableCollision(leftLinkID, rightLinkID); #endif currLeftID = rightLinkID; currRightID = leftLinkID; currLeft = rightLink; currRight = leftLink; } // PxArticulationLinkCookie leftTop; PxU32 leftTopID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(mPoses[currLeftID].transform(PxTransform(PxVec3(-0.5f, 0.f, -1.0f), leftParentRot))); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.f, -1.f), mPoses[currLeftID].q.getConjugate()); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.5f, 0.f, 0.f), pose.q.getConjugate()); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; leftTop = PxAddArticulationLink(immArt, &currLeft, linkData); leftTopID = createActor(boxGeom, pose, &massProps, &leftTop); disableCollision(currLeftID, leftTopID); mActors[leftTopID].mCollisionGroup = 1; } // PxArticulationLinkCookie rightTop; PxU32 rightTopID; { // TODO: use a capsule here // PxRigidActorExt::createExclusiveShape(*rightTop, PxCapsuleGeometry(0.05f, 0.8f), *gMaterial); const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(mPoses[currRightID].transform(PxTransform(PxVec3(-0.5f, 0.f, 1.0f), rightParentRot))); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.f, 1.f), mPoses[currRightID].q.getConjugate()); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.5f, 0.f, 0.f), pose.q.getConjugate()); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; rightTop = PxAddArticulationLink(immArt, &currRight, linkData); rightTopID = createActor(boxGeom, pose, &massProps, &rightTop); disableCollision(currRightID, rightTopID); mActors[rightTopID].mCollisionGroup = 1; } // currLeftID = leftRootID; currRightID = rightRootID; currLeft = leftRoot; currRight = rightRoot; rightParentRot = PxQuat(PxIdentity); leftParentRot = PxQuat(PxIdentity); for(PxU32 i=0; i<linkHeight; ++i) { const PxVec3 pos(-0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLinkCookie leftLink; PxU32 leftLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currLeftID].transformInv(leftAnchorLocation), leftParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = angle; leftLink = PxAddArticulationLink(immArt, &currLeft, linkData); leftLinkID = createActor(boxGeom, pose, &massProps, &leftLink); disableCollision(currLeftID, leftLinkID); mActors[leftLinkID].mCollisionGroup = 1; } leftParentRot = leftRot; // PxArticulationLinkCookie rightLink; PxU32 rightLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currRightID].transformInv(rightAnchorLocation), rightParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -angle; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi; rightLink = PxAddArticulationLink(immArt, &currRight, linkData); rightLinkID = createActor(boxGeom, pose, &massProps, &rightLink); disableCollision(currRightID, rightLinkID); mActors[rightLinkID].mCollisionGroup = 1; } rightParentRot = rightRot; #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(leftLinkID, rightLinkID, PxTransform(PxIdentity), PxTransform(PxIdentity)); #else disableCollision(leftLinkID, rightLinkID); #endif currLeftID = rightLinkID; currRightID = leftLinkID; currLeft = rightLink; currRight = leftLink; } // #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(currLeftID, leftTopID, PxTransform(PxVec3(0.f, 0.f, -1.f)), PxTransform(PxVec3(-0.5f, 0.f, 0.f))); createSphericalJoint(currRightID, rightTopID, PxTransform(PxVec3(0.f, 0.f, 1.f)), PxTransform(PxVec3(-0.5f, 0.f, 0.f))); #else disableCollision(currLeftID, leftTopID); disableCollision(currRightID, rightTopID); #endif // // Create top { PxArticulationLinkCookie top; PxU32 topID; { const PxBoxGeometry boxGeom(0.5f, 0.1f, 1.5f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, mPoses[leftTopID].p.y + 0.15f, 0.f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eFIX; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.0f, 0.f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.15f, -0.9f)); top = PxAddArticulationLink(immArt, &leftTop, linkData); topID = createActor(boxGeom, pose, &massProps, &top); disableCollision(leftTopID, topID); } } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); createGroundPlane(); } else if(index==6) { //const float scaleFactor = 0.25f; const float scaleFactor = 1.0f; const float halfHeight = 1.0f*scaleFactor; const float radius = 1.0f*scaleFactor; const PxU32 nbCirclePts = 20; const PxU32 totalNbVerts = nbCirclePts*2; PxVec3 verts[totalNbVerts]; const float step = 3.14159f*2.0f/float(nbCirclePts); for(PxU32 i=0;i<nbCirclePts;i++) { verts[i].x = sinf(float(i) * step) * radius; verts[i].y = cosf(float(i) * step) * radius; verts[i].z = 0.0f; } const PxVec3 offset(0.0f, 0.0f, halfHeight); PxVec3* verts2 = verts + nbCirclePts; for(PxU32 i=0;i<nbCirclePts;i++) { const PxVec3 P = verts[i]; verts[i] = P - offset; verts2[i] = P + offset; } const PxTolerancesScale scale; PxCookingParams params(scale); PxConvexMeshDesc convexDesc; convexDesc.points.count = totalNbVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; PxConvexMesh* convexMesh = PxCreateConvexMesh(params, convexDesc); const PxConvexMeshGeometry convexGeom(convexMesh); MassProps massProps; computeMassProps(massProps, convexGeom, 1.0f); const PxQuat rot = PxShortestRotation(PxVec3(0.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 0.0f)); PxU32 Nb = 14; float altitude = radius; float offsetX = 0.0f; while(Nb) { for(PxU32 i=0;i<Nb;i++) { createActor(convexGeom, PxTransform(PxVec3(offsetX + float(i)*radius*2.2f, altitude, 0.0f), rot), &massProps); } Nb--; altitude += halfHeight*2.0f+0.01f; offsetX += radius*1.1f; } createGroundPlane(); } } void ImmediateScene::updateArticulations(float dt) { #if USE_TGS const float stepDt = dt/gNbIterPos; const float invTotalDt = 1.0f/dt; const float stepInvDt = 1.0f/stepDt; #endif const PxU32 nbArticulations = mArticulations.size(); for(PxU32 i=0;i<nbArticulations;i++) { PxArticulationHandle articulation = mArticulations[i]; #if USE_TGS PxComputeUnconstrainedVelocitiesTGS(articulation, gGravity, stepDt, dt, stepInvDt, invTotalDt, 1.0f); #else PxComputeUnconstrainedVelocities(articulation, gGravity, dt, 1.0f); #endif } } void ImmediateScene::updateBounds() { PX_SIMD_GUARD // PT: in this snippet we simply recompute all bounds each frame (i.e. even static ones) const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) PxGeometryQuery::computeGeomBounds(mBounds[i], mGeoms[i].any(), mPoses[i], gBoundsInflation, 1.0f, PxGeometryQueryFlag::Enum(0)); } void ImmediateScene::broadPhase() { // PT: in this snippet we simply do a brute-force O(n^2) broadphase between all actors mBroadphasePairs.clear(); const PxU32 nbActors = mActors.size(); for(PxU32 i=0; i<nbActors; i++) { const ImmediateActor::Type type0 = mActors[i].mType; for(PxU32 j=i+1; j<nbActors; j++) { const ImmediateActor::Type type1 = mActors[j].mType; // Filtering { if(type0==ImmediateActor::eSTATIC && type1==ImmediateActor::eSTATIC) continue; if(mActors[i].mCollisionGroup==1 && mActors[j].mCollisionGroup==1) continue; if(isCollisionDisabled(i, j)) continue; } if(mBounds[i].intersects(mBounds[j])) { mBroadphasePairs.pushBack(IDS(i, j)); } #if WITH_PERSISTENCY else { //No collision detection performed at all so clear contact cache and friction data mPersistentPairs.erase(IDS(i, j)); } #endif } } } void ImmediateScene::narrowPhase() { class ContactRecorder : public PxContactRecorder { public: ContactRecorder(ImmediateScene* scene, PxU32 id0, PxU32 id1) : mScene(scene), mID0(id0), mID1(id1), mHasContacts(false) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { { ImmediateScene::ContactPair pair; pair.mID0 = mID0; pair.mID1 = mID1; pair.mNbContacts = nbContacts; pair.mStartContactIndex = mScene->mContactPoints.size(); mScene->mContactPairs.pushBack(pair); mHasContacts = true; } for(PxU32 i=0; i<nbContacts; i++) { // Fill in solver-specific data that our contact gen does not produce... PxContactPoint point = contactPoints[i]; point.maxImpulse = PX_MAX_F32; point.targetVel = PxVec3(0.0f); point.staticFriction = gStaticFriction; point.dynamicFriction = gDynamicFriction; point.restitution = gRestitution; point.materialFlags = PxMaterialFlag::eIMPROVED_PATCH_FRICTION; mScene->mContactPoints.pushBack(point); } return true; } ImmediateScene* mScene; PxU32 mID0; PxU32 mID1; bool mHasContacts; }; mCacheAllocator->reset(); mConstraintAllocator->release(); mContactPairs.resize(0); mContactPoints.resize(0); const PxU32 nbPairs = mBroadphasePairs.size(); for(PxU32 i=0;i<nbPairs;i++) { const IDS& pair = mBroadphasePairs[i]; const PxTransform& tr0 = mPoses[pair.mID0]; const PxTransform& tr1 = mPoses[pair.mID1]; const PxGeometry* pxGeom0 = &mGeoms[pair.mID0].any(); const PxGeometry* pxGeom1 = &mGeoms[pair.mID1].any(); ContactRecorder contactRecorder(this, pair.mID0, pair.mID1); #if WITH_PERSISTENCY PersistentContactPair& persistentData = mPersistentPairs[IDS(pair.mID0, pair.mID1)]; PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &persistentData.cache, 1, contactRecorder, gContactDistance, gMeshContactMargin, gToleranceLength, *mCacheAllocator); if(!contactRecorder.mHasContacts) { //Contact generation run but no touches found so clear cached friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; } #else PxCache cache; PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &cache, 1, contactRecorder, gContactDistance, gMeshContactMargin, gToleranceLength, *mCacheAllocator); #endif } if(1) { printf("Narrow-phase: %d contacts \r", mContactPoints.size()); } } void ImmediateScene::buildSolverBodyData(float dt) { const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mType==ImmediateActor::eSTATIC) { #if USE_TGS PxConstructStaticSolverBodyTGS(mPoses[i], mSolverBodies[i], mSolverBodyTxInertias[i], mSolverBodyData[i]); #else PxConstructStaticSolverBody(mPoses[i], mSolverBodyData[i]); #endif } else { PxRigidBodyData data; data.linearVelocity = mActors[i].mLinearVelocity; data.angularVelocity = mActors[i].mAngularVelocity; data.invMass = mActors[i].mMassProps.mInvMass; data.invInertia = mActors[i].mMassProps.mInvInertia; data.body2World = mPoses[i]; data.maxDepenetrationVelocity = gMaxDepenetrationVelocity; data.maxContactImpulse = gMaxContactImpulse; data.linearDamping = gLinearDamping; data.angularDamping = gAngularDamping; data.maxLinearVelocitySq = gMaxLinearVelocity*gMaxLinearVelocity; data.maxAngularVelocitySq = gMaxAngularVelocity*gMaxAngularVelocity; #if USE_TGS PxConstructSolverBodiesTGS(&data, &mSolverBodies[i], &mSolverBodyTxInertias[i], &mSolverBodyData[i], 1, gGravity, dt); #else PxConstructSolverBodies(&data, &mSolverBodyData[i], 1, gGravity, dt); #endif } } } #if USE_TGS static void setupDesc(PxSolverConstraintDesc& desc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyVel* solverBodies, PxU32 id, bool aorb) #else static void setupDesc(PxSolverConstraintDesc& desc, const ImmediateScene::ImmediateActor* actors, PxSolverBody* solverBodies, PxU32 id, bool aorb) #endif { if(!aorb) desc.bodyADataIndex = id; else desc.bodyBDataIndex = id; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { if(!aorb) { desc.articulationA = link.articulation; desc.linkIndexA = link.linkId; } else { desc.articulationB = link.articulation; desc.linkIndexB = link.linkId; } } else { if(!aorb) { #if USE_TGS desc.tgsBodyA = &solverBodies[id]; #else desc.bodyA = &solverBodies[id]; #endif desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } else { #if USE_TGS desc.tgsBodyB = &solverBodies[id]; #else desc.bodyB = &solverBodies[id]; #endif desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } } void ImmediateScene::buildSolverConstraintDesc() { const PxU32 nbContactPairs = mContactPairs.size(); #ifdef TEST_IMMEDIATE_JOINTS const PxU32 nbJoints = mJointData.size(); mSolverConstraintDesc.resize(nbContactPairs+nbJoints); #else mSolverConstraintDesc.resize(nbContactPairs); #endif for(PxU32 i=0; i<nbContactPairs; i++) { const ContactPair& pair = mContactPairs[i]; PxSolverConstraintDesc& desc = mSolverConstraintDesc[i]; setupDesc(desc, mActors.begin(), mSolverBodies.begin(), pair.mID0, false); setupDesc(desc, mActors.begin(), mSolverBodies.begin(), pair.mID1, true); //Cache pointer to our contact data structure and identify which type of constraint this is. We'll need this later after batching. //If we choose not to perform batching and instead just create a single header per-pair, then this would not be necessary because //the constraintDescs would not have been reordered desc.constraint = reinterpret_cast<PxU8*>(const_cast<ContactPair*>(&pair)); desc.constraintLengthOver16 = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJoints; i++) { const MyJointData& jointData = mJointData[i]; PxSolverConstraintDesc& desc = mSolverConstraintDesc[nbContactPairs+i]; const PxU32 id0 = jointData.mActors[0]; const PxU32 id1 = jointData.mActors[1]; setupDesc(desc, mActors.begin(), mSolverBodies.begin(), id0, false); setupDesc(desc, mActors.begin(), mSolverBodies.begin(), id1, true); desc.constraint = reinterpret_cast<PxU8*>(const_cast<MyJointData*>(&jointData)); desc.constraintLengthOver16 = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif } #ifdef TEST_IMMEDIATE_JOINTS // PT: this is copied from PxExtensions, it's the solver prep function for spherical joints //TAG:solverprepshader static PxU32 SphericalJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const MyJointData& data = *reinterpret_cast<const MyJointData*>(constantBlock); PxTransform32 cA2w, cB2w; Ext::joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); Ext::joint::applyNeighborhoodOperator(cA2w, cB2w); /* if(data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED) { PxQuat swing, twist; PxSeparateSwingTwist(cA2w.q.getConjugate() * cB2w.q, swing, twist); PX_ASSERT(PxAbs(swing.x)<1e-6f); // PT: TODO: refactor with D6 joint code PxVec3 axis; PxReal error; const PxReal pad = data.limit.isSoft() ? 0.0f : data.limit.contactDistance; const Cm::ConeLimitHelperTanLess coneHelper(data.limit.yAngle, data.limit.zAngle, pad); const bool active = coneHelper.getLimit(swing, axis, error); if(active) ch.angularLimit(cA2w.rotate(axis), error, data.limit); }*/ PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 0, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; return ch.getCount(); } #endif #if USE_TGS static void setupDesc(PxTGSSolverContactDesc& contactDesc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyData, PxTransform* poses, const PxU32 id, const bool aorb) { PxTransform& bodyFrame = aorb ? contactDesc.bodyFrame1 : contactDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? contactDesc.bodyState1 : contactDesc.bodyState0; const PxTGSSolverBodyData*& data = aorb ? contactDesc.bodyData1 : contactDesc.bodyData0; const PxTGSSolverBodyTxInertia*& txI = aorb ? contactDesc.body1TxI : contactDesc.body0TxI; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(link, linkData); PX_ASSERT(status); PX_UNUSED(status); data = NULL; txI = NULL; bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { data = &solverBodyData[id]; txI = &txInertias[id]; bodyFrame = poses[id]; bodyState = actors[id].mType == ImmediateScene::ImmediateActor::eDYNAMIC ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; } } #else static void setupDesc(PxSolverContactDesc& contactDesc, const ImmediateScene::ImmediateActor* actors, PxSolverBodyData* solverBodyData, const PxU32 id, const bool aorb) { PxTransform& bodyFrame = aorb ? contactDesc.bodyFrame1 : contactDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? contactDesc.bodyState1 : contactDesc.bodyState0; const PxSolverBodyData*& data = aorb ? contactDesc.data1 : contactDesc.data0; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(link, linkData); PX_ASSERT(status); PX_UNUSED(status); data = NULL; bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { data = &solverBodyData[id]; bodyFrame = solverBodyData[id].body2World; bodyState = actors[id].mType == ImmediateScene::ImmediateActor::eDYNAMIC ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; } } #endif #if USE_TGS static void setupJointDesc(PxTGSSolverConstraintPrepDesc& jointDesc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyData, PxTransform* poses, const PxU32 bodyDataIndex, const bool aorb) { if(!aorb) { jointDesc.bodyData0 = &solverBodyData[bodyDataIndex]; jointDesc.body0TxI = &txInertias[bodyDataIndex]; } else { jointDesc.bodyData1 = &solverBodyData[bodyDataIndex]; jointDesc.body1TxI = &txInertias[bodyDataIndex]; } PxTransform& bodyFrame = aorb ? jointDesc.bodyFrame1 : jointDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? jointDesc.bodyState1 : jointDesc.bodyState0; if(actors[bodyDataIndex].mLink.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(actors[bodyDataIndex].mLink, linkData); PX_ASSERT(status); PX_UNUSED(status); bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. // PT: TODO: this is a bug in the immediate mode snippet if(actors[bodyDataIndex].mType == ImmediateScene::ImmediateActor::eSTATIC) { bodyFrame = PxTransform(PxIdentity); bodyState = PxSolverConstraintPrepDescBase::eSTATIC_BODY; } else { bodyFrame = poses[bodyDataIndex]; bodyState = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; } } } #else static void setupJointDesc(PxSolverConstraintPrepDesc& jointDesc, const ImmediateScene::ImmediateActor* actors, PxSolverBodyData* solverBodyData, const PxU32 bodyDataIndex, const bool aorb) { if(!aorb) jointDesc.data0 = &solverBodyData[bodyDataIndex]; else jointDesc.data1 = &solverBodyData[bodyDataIndex]; PxTransform& bodyFrame = aorb ? jointDesc.bodyFrame1 : jointDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? jointDesc.bodyState1 : jointDesc.bodyState0; if(actors[bodyDataIndex].mLink.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(actors[bodyDataIndex].mLink, linkData); PX_ASSERT(status); PX_UNUSED(status); bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. // PT: TODO: this is a bug in the immediate mode snippet if(actors[bodyDataIndex].mType == ImmediateScene::ImmediateActor::eSTATIC) { bodyFrame = PxTransform(PxIdentity); bodyState = PxSolverConstraintPrepDescBase::eSTATIC_BODY; } else { bodyFrame = solverBodyData[bodyDataIndex].body2World; bodyState = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; } } } #endif void ImmediateScene::createContactConstraints(float dt, float invDt, float lengthScale, const PxU32 nbPosIterations) { //Only referenced if using TGS solver PX_UNUSED(lengthScale); PX_UNUSED(nbPosIterations); #if USE_TGS const float stepDt = dt/float(nbPosIterations); const float stepInvDt = invDt*float(nbPosIterations); #endif #if BATCH_CONTACTS mHeaders.resize(mSolverConstraintDesc.size()); const PxU32 nbBodies = mActors.size() - mNbStaticActors; mOrderedSolverConstraintDesc.resize(mSolverConstraintDesc.size()); PxArray<PxSolverConstraintDesc>& orderedDescs = mOrderedSolverConstraintDesc; #if USE_TGS const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraintsTGS( mSolverConstraintDesc.begin(), mContactPairs.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin(), orderedDescs.begin(), mArticulations.begin(), mArticulations.size()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraintsTGS( mSolverConstraintDesc.begin() + mContactPairs.size(), mJointData.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin() + nbContactHeaders, orderedDescs.begin() + mContactPairs.size(), mArticulations.begin(), mArticulations.size()); #else //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraints(mSolverConstraintDesc.begin(), mContactPairs.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin(), orderedDescs.begin(), mArticulations.begin(), mArticulations.size()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraints( mSolverConstraintDesc.begin() + mContactPairs.size(), mJointData.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin() + nbContactHeaders, orderedDescs.begin() + mContactPairs.size(), mArticulations.begin(), mArticulations.size()); #endif const PxU32 totalHeaders = nbContactHeaders + nbJointHeaders; mHeaders.forceSize_Unsafe(totalHeaders); #else PxArray<PxSolverConstraintDesc>& orderedDescs = mSolverConstraintDesc; const PxU32 nbContactHeaders = mContactPairs.size(); #ifdef TEST_IMMEDIATE_JOINTS const PxU32 nbJointHeaders = mJointData.size(); PX_ASSERT(nbContactHeaders+nbJointHeaders==mSolverConstraintDesc.size()); mHeaders.resize(nbContactHeaders+nbJointHeaders); #else PX_ASSERT(nbContactHeaders==mSolverConstraintDesc.size()); PX_UNUSED(dt); mHeaders.resize(nbContactHeaders); #endif // We are bypassing the constraint batching so we create dummy PxConstraintBatchHeaders for(PxU32 i=0; i<nbContactHeaders; i++) { PxConstraintBatchHeader& hdr = mHeaders[i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJointHeaders; i++) { PxConstraintBatchHeader& hdr = mHeaders[nbContactHeaders+i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif #endif mContactForces.resize(mContactPoints.size()); for(PxU32 i=0; i<nbContactHeaders; i++) { PxConstraintBatchHeader& header = mHeaders[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eCONTACT_CONSTRAINT); #if USE_TGS PxTGSSolverContactDesc contactDescs[4]; #else PxSolverContactDesc contactDescs[4]; #endif #if WITH_PERSISTENCY PersistentContactPair* persistentPairs[4]; #endif for(PxU32 a=0; a<header.stride; a++) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. const ContactPair& pair = *reinterpret_cast<const ContactPair*>(constraintDesc.constraint); #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; PxMemZero(&contactDesc, sizeof(contactDesc)); setupDesc(contactDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), pair.mID0, false); setupDesc(contactDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), pair.mID1, true); contactDesc.body0 = constraintDesc.tgsBodyA; contactDesc.body1 = constraintDesc.tgsBodyB; contactDesc.torsionalPatchRadius = 0.0f; contactDesc.minTorsionalPatchRadius = 0.0f; #else PxSolverContactDesc& contactDesc = contactDescs[a]; PxMemZero(&contactDesc, sizeof(contactDesc)); setupDesc(contactDesc, mActors.begin(), mSolverBodyData.begin(), pair.mID0, false); setupDesc(contactDesc, mActors.begin(), mSolverBodyData.begin(), pair.mID1, true); contactDesc.body0 = constraintDesc.bodyA; contactDesc.body1 = constraintDesc.bodyB; #endif contactDesc.contactForces = &mContactForces[pair.mStartContactIndex]; contactDesc.contacts = &mContactPoints[pair.mStartContactIndex]; contactDesc.numContacts = pair.mNbContacts; #if WITH_PERSISTENCY const PxHashMap<IDS, PersistentContactPair>::Entry* e = mPersistentPairs.find(IDS(pair.mID0, pair.mID1)); PX_ASSERT(e); { PersistentContactPair& pcp = const_cast<PersistentContactPair&>(e->second); contactDesc.frictionPtr = pcp.frictions; contactDesc.frictionCount = PxU8(pcp.nbFrictions); persistentPairs[a] = &pcp; } #else contactDesc.frictionPtr = NULL; contactDesc.frictionCount = 0; #endif contactDesc.maxCCDSeparation = PX_MAX_F32; contactDesc.desc = &constraintDesc; contactDesc.invMassScales.angular0 = contactDesc.invMassScales.angular1 = contactDesc.invMassScales.linear0 = contactDesc.invMassScales.linear1 = 1.0f; } #if USE_TGS PxCreateContactConstraintsTGS(&header, 1, contactDescs, *mConstraintAllocator, stepInvDt, invDt, gBounceThreshold, gFrictionOffsetThreshold, gCorrelationDistance); #else PxCreateContactConstraints(&header, 1, contactDescs, *mConstraintAllocator, invDt, gBounceThreshold, gFrictionOffsetThreshold, gCorrelationDistance, mTempZ.begin()); #endif #if WITH_PERSISTENCY //Cache friction information... for (PxU32 a = 0; a < header.stride; ++a) { #if USE_TGS const PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else const PxSolverContactDesc& contactDesc = contactDescs[a]; #endif PersistentContactPair& pcp = *persistentPairs[a]; pcp.frictions = contactDesc.frictionPtr; pcp.nbFrictions = contactDesc.frictionCount; } #endif } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJointHeaders; i++) { PxConstraintBatchHeader& header = mHeaders[nbContactHeaders+i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eJOINT_CONSTRAINT); { #if USE_TGS PxTGSSolverConstraintPrepDesc jointDescs[4]; #else PxSolverConstraintPrepDesc jointDescs[4]; #endif PxImmediateConstraint constraints[4]; header.startIndex += mContactPairs.size(); for(PxU32 a=0; a<header.stride; a++) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. const MyJointData& jd = *reinterpret_cast<const MyJointData*>(constraintDesc.constraint); constraints[a].prep = SphericalJointSolverPrep; constraints[a].constantBlock = &jd; #if USE_TGS PxTGSSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.tgsBodyA; jointDesc.body1 = constraintDesc.tgsBodyB; setupJointDesc(jointDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), constraintDesc.bodyADataIndex, false); setupJointDesc(jointDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), constraintDesc.bodyBDataIndex, true); #else PxSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.bodyA; jointDesc.body1 = constraintDesc.bodyB; setupJointDesc(jointDesc, mActors.begin(), mSolverBodyData.begin(), constraintDesc.bodyADataIndex, false); setupJointDesc(jointDesc, mActors.begin(), mSolverBodyData.begin(), constraintDesc.bodyBDataIndex, true); #endif jointDesc.desc = &constraintDesc; jointDesc.writeback = NULL; jointDesc.linBreakForce = PX_MAX_F32; jointDesc.angBreakForce = PX_MAX_F32; jointDesc.minResponseThreshold = 0; jointDesc.disablePreprocessing = false; jointDesc.improvedSlerp = false; jointDesc.driveLimitsAreForces = false; jointDesc.invMassScales.angular0 = jointDesc.invMassScales.angular1 = jointDesc.invMassScales.linear0 = jointDesc.invMassScales.linear1 = 1.0f; } #if USE_TGS immediate::PxCreateJointConstraintsWithImmediateShadersTGS(&header, 1, constraints, jointDescs, *mConstraintAllocator, stepDt, dt, stepInvDt, invDt, lengthScale); #else immediate::PxCreateJointConstraintsWithImmediateShaders(&header, 1, constraints, jointDescs, *mConstraintAllocator, dt, invDt, mTempZ.begin()); #endif } } #endif } void ImmediateScene::solveAndIntegrate(float dt) { #ifdef PRINT_TIMINGS unsigned long long time0 = __rdtsc(); #endif const PxU32 totalNbActors = mActors.size(); const PxU32 nbDynamicActors = totalNbActors - mNbStaticActors - mNbArticulationLinks; const PxU32 nbDynamic = nbDynamicActors + mNbArticulationLinks; mMotionLinearVelocity.resize(nbDynamic); mMotionAngularVelocity.resize(nbDynamic); const PxU32 nbArticulations = mArticulations.size(); PxArticulationHandle* articulations = mArticulations.begin(); #if USE_TGS const float stepDt = dt/float(gNbIterPos); immediate::PxSolveConstraintsTGS(mHeaders.begin(), mHeaders.size(), #if BATCH_CONTACTS mOrderedSolverConstraintDesc.begin(), #else mSolverConstraintDesc.begin(), #endif mSolverBodies.begin(), mSolverBodyTxInertias.begin(), nbDynamic, gNbIterPos, gNbIterVel, stepDt, 1.0f / stepDt, nbArticulations, articulations, mTempZ.begin(), mTempDeltaV.begin()); #else PxMemZero(mSolverBodies.begin(), mSolverBodies.size() * sizeof(PxSolverBody)); PxSolveConstraints( mHeaders.begin(), mHeaders.size(), #if BATCH_CONTACTS mOrderedSolverConstraintDesc.begin(), #else mSolverConstraintDesc.begin(), #endif mSolverBodies.begin(), mMotionLinearVelocity.begin(), mMotionAngularVelocity.begin(), nbDynamic, gNbIterPos, gNbIterVel, dt, 1.0f/dt, nbArticulations, articulations, mTempZ.begin(), mTempDeltaV.begin()); #endif #ifdef PRINT_TIMINGS unsigned long long time1 = __rdtsc(); #endif #if USE_TGS PxIntegrateSolverBodiesTGS(mSolverBodies.begin(), mSolverBodyTxInertias.begin(), mPoses.begin(), nbDynamicActors, dt); for (PxU32 i = 0; i<nbArticulations; i++) PxUpdateArticulationBodiesTGS(articulations[i], dt); for (PxU32 i = 0; i<nbDynamicActors; i++) { PX_ASSERT(mActors[i].mType == ImmediateActor::eDYNAMIC); const PxTGSSolverBodyVel& data = mSolverBodies[i]; mActors[i].mLinearVelocity = data.linearVelocity; mActors[i].mAngularVelocity = data.angularVelocity; } #else PxIntegrateSolverBodies(mSolverBodyData.begin(), mSolverBodies.begin(), mMotionLinearVelocity.begin(), mMotionAngularVelocity.begin(), nbDynamicActors, dt); for (PxU32 i = 0; i<nbArticulations; i++) PxUpdateArticulationBodies(articulations[i], dt); for (PxU32 i = 0; i<nbDynamicActors; i++) { PX_ASSERT(mActors[i].mType == ImmediateActor::eDYNAMIC); const PxSolverBodyData& data = mSolverBodyData[i]; mActors[i].mLinearVelocity = data.linearVelocity; mActors[i].mAngularVelocity = data.angularVelocity; mPoses[i] = data.body2World; } #endif for(PxU32 i=0;i<mNbArticulationLinks;i++) { const PxU32 j = nbDynamicActors + i; PX_ASSERT(mActors[j].mType==ImmediateActor::eLINK); PxArticulationLinkDerivedDataRC data; bool status = PxGetLinkData(mActors[j].mLink, data); PX_ASSERT(status); PX_UNUSED(status); mActors[j].mLinearVelocity = data.linearVelocity; mActors[j].mAngularVelocity = data.angularVelocity; mPoses[j] = data.pose; } #ifdef PRINT_TIMINGS unsigned long long time2 = __rdtsc(); printf("solve: %d \n", (time1-time0)/1024); printf("integrate: %d \n", (time2-time1)/1024); #endif } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static ImmediateScene* gScene = NULL; /////////////////////////////////////////////////////////////////////////////// PxU32 getNbGeoms() { return gScene ? gScene->mGeoms.size() : 0; } const PxGeometryHolder* getGeoms() { if(!gScene || !gScene->mGeoms.size()) return NULL; return &gScene->mGeoms[0]; } const PxTransform* getGeomPoses() { if(!gScene || !gScene->mPoses.size()) return NULL; return &gScene->mPoses[0]; } PxU32 getNbArticulations() { return gScene ? gScene->mArticulations.size() : 0; } PxArticulationHandle* getArticulations() { if(!gScene || !gScene->mArticulations.size()) return NULL; return &gScene->mArticulations[0]; } PxU32 getNbBounds() { if(!gDrawBounds) return 0; return gScene ? gScene->mBounds.size() : 0; } const PxBounds3* getBounds() { if(!gDrawBounds) return NULL; if(!gScene || !gScene->mBounds.size()) return NULL; return &gScene->mBounds[0]; } PxU32 getNbContacts() { return gScene ? gScene->mContactPoints.size() : 0; } const PxContactPoint* getContacts() { if(!gScene || !gScene->mContactPoints.size()) return NULL; return &gScene->mContactPoints[0]; } /////////////////////////////////////////////////////////////////////////////// void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gScene = new ImmediateScene; gScene->createScene(); } void stepPhysics(bool /*interactive*/) { if(!gScene) return; if(gPause && !gOneFrame) return; gOneFrame = false; const float dt = 1.0f/60.0f; const float invDt = 60.0f; { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->updateArticulations(dt); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("updateArticulations: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->updateBounds(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("updateBounds: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->broadPhase(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("broadPhase: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->narrowPhase(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("narrowPhase: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->buildSolverBodyData(dt); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("buildSolverBodyData: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->buildSolverConstraintDesc(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("buildSolverConstraintDesc: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->createContactConstraints(dt, invDt, 1.f, gNbIterPos); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("createContactConstraints: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS // unsigned long long time = __rdtsc(); #endif gScene->solveAndIntegrate(dt); #ifdef PRINT_TIMINGS // time = __rdtsc() - time; // printf("solveAndIntegrate: %d \n", time/1024); #endif } if(gScene->mMotorLink.articulation) { gTime += 0.1f; const float target = sinf(gTime) * 4.0f; // printf("target: %f\n", target); PxArticulationJointDataRC data; bool status = PxGetJointData(gScene->mMotorLink, data); PX_ASSERT(status); data.targetVel[PxArticulationAxis::eTWIST] = target; const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const float s = boxExtents.x*1.1f + fabsf(sinf(gTime))*0.5f; data.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); data.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); status = PxSetJointData(gScene->mMotorLink, data); PX_ASSERT(status); PX_UNUSED(status); } } void cleanupPhysics(bool /*interactive*/) { PX_DELETE(gScene); PX_RELEASE(gFoundation); printf("SnippetImmediateArticulation done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='b' || key=='B') gDrawBounds = !gDrawBounds; if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } if(gScene) { if(key>=1 && key<=7) { gSceneIndex = key-1; gScene->reset(); gScene->createScene(); } if(key=='r' || key=='R') { gScene->reset(); gScene->createScene(); } } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F7 to select a scene."); #endif } int snippetMain(int, const char*const*) { printf("Immediate articulation snippet. Use these keys:\n"); printf(" P - enable/disable pause\n"); printf(" O - step simulation for one frame\n"); printf(" R - reset scene\n"); printf(" F1 to F6 - select scene\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
70,838
C++
30.610442
253
0.729608
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbdinflatable/SnippetPBDInflatable.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. // **************************************************************************** // This snippet illustrates inflatable simulation using position-based dynamics // particle simulation. It creates an inflatable body that drops to the ground. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxRemeshingExt.h" #include "extensions/PxParticleExt.h" #include "extensions/PxParticleClothCooker.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleClothBuffer* gUserClothBuffer = NULL; static bool gIsRunning = true; static void initObstacles() { PxShape* shape = gPhysics->createShape(PxCapsuleGeometry(0.5f, 4.f), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.f, 5.0f, 2.f))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); shape = gPhysics->createShape(PxCapsuleGeometry(0.5f, 4.f), *gMaterial); body = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.f, 5.0f, -2.f))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); } // ----------------------------------------------------------------------------------------------------------------- static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); } // ----------------------------------------------------------------------------------------------------------------- PxVec3 cubeVertices[] = { PxVec3(0.5f, -0.5f, -0.5f), PxVec3(0.5f, -0.5f, 0.5f), PxVec3(-0.5f, -0.5f, 0.5f), PxVec3(-0.5f, -0.5f, -0.5f), PxVec3(0.5f, 0.5f, -0.5f), PxVec3(0.5f, 0.5f, 0.5f), PxVec3(-0.5f, 0.5f, 0.5f), PxVec3(-0.5f, 0.5f, -0.5f) }; PxU32 cubeIndices[] = { 1, 2, 3, 7, 6, 5, 4, 5, 1, 5, 6, 2, 2, 6, 7, 0, 3, 7, 0, 1, 3, 4, 7, 5, 0, 4, 1, 1, 5, 2, 3, 2, 7, 4, 0, 7 }; static void projectPointsOntoSphere(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); triVerts[i] = center + radius * dir; } } static void createSphere(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, const PxReal maxEdgeLength) { for (PxU32 i = 0; i < 8; ++i) triVerts.pushBack(cubeVertices[i] * radius + center); for (PxU32 i = 0; i < 36; ++i) triIndices.pushBack(cubeIndices[i]); projectPointsOntoSphere(triVerts, center, radius); while (PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 1)) projectPointsOntoSphere(triVerts, center, radius); } static void initInflatable(PxArray<PxVec3>& verts, PxArray<PxU32>& indices, const PxReal restOffset = 0.1f, const PxReal totalInflatableMass = 10.f) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; PxArray<PxVec4> vertices; vertices.resize(verts.size()); PxReal invMass = 1.0f / (totalInflatableMass / verts.size()); for (PxU32 i = 0; i < verts.size(); ++i) vertices[i] = PxVec4(verts[i], invMass); const PxU32 numParticles = vertices.size(); const PxReal stretchStiffness = 100000.f; const PxReal shearStiffness = 1000.f; const PxReal bendStiffness = 1000.f; const PxReal pressure = 1.0f; //Pressure is used to compute the target volume of the inflatable by scaling its rest volume // Cook cloth PxParticleClothCooker* cooker = PxCreateParticleClothCooker(vertices.size(), vertices.begin(), indices.size(), indices.begin(), PxParticleClothConstraint::eTYPE_HORIZONTAL_CONSTRAINT | PxParticleClothConstraint::eTYPE_VERTICAL_CONSTRAINT | PxParticleClothConstraint::eTYPE_DIAGONAL_CONSTRAINT); cooker->cookConstraints(); cooker->calculateMeshVolume(); // Apply cooked constraints to particle springs PxU32 constraintCount = cooker->getConstraintCount(); PxParticleClothConstraint* constraintBuffer = cooker->getConstraints(); PxArray<PxParticleSpring> springs; springs.reserve(constraintCount); for (PxU32 i = 0; i < constraintCount; i++) { const PxParticleClothConstraint& c = constraintBuffer[i]; PxReal stiffness = 0.0f; switch (c.constraintType) { case PxParticleClothConstraint::eTYPE_INVALID_CONSTRAINT: continue; case PxParticleClothConstraint::eTYPE_HORIZONTAL_CONSTRAINT: case PxParticleClothConstraint::eTYPE_VERTICAL_CONSTRAINT: stiffness = stretchStiffness; break; case PxParticleClothConstraint::eTYPE_DIAGONAL_CONSTRAINT: stiffness = shearStiffness; break; case PxParticleClothConstraint::eTYPE_BENDING_CONSTRAINT: stiffness = bendStiffness; break; default: PX_ASSERT("Invalid cloth constraint generated by PxParticleClothCooker"); } PxParticleSpring spring; spring.ind0 = c.particleIndexA; spring.ind1 = c.particleIndexB; spring.stiffness = stiffness; spring.damping = 0.001f; spring.length = c.length; springs.pushBack(spring); } const PxU32 numSprings = springs.size(); // Read triangles from cooker const PxU32 numTriangles = cooker->getTriangleIndicesCount() / 3; const PxU32* triangles = cooker->getTriangleIndices(); // Material setup PxPBDMaterial* defaultMat = gPhysics->createPBDMaterial(0.8f, 0.05f, 1e+6f, 0.001f, 0.5f, 0.005f, 0.05f, 0.f, 0.f); PxPBDParticleSystem *particleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager); gParticleSystem = particleSystem; // General particle system setting particleSystem->setRestOffset(restOffset); particleSystem->setContactOffset(restOffset + 0.02f); particleSystem->setParticleContactOffset(restOffset + 0.02f); particleSystem->setSolidRestOffset(restOffset); particleSystem->setFluidRestOffset(0.0f); gScene->addActor(*particleSystem); // Create particles and add them to the particle system const PxU32 particlePhase = particleSystem->createPhase(defaultMat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseSelfCollideFilter | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); PxU32* phases = cudaContextManager->allocPinnedHostBuffer<PxU32>(numParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(numParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(numParticles); for (PxU32 v = 0; v < numParticles; v++) { positionInvMass[v] = vertices[v]; velocity[v] = PxVec4(0.0f, 0.0f, 0.0f, 0.0f); phases[v] = particlePhase; } PxParticleVolumeBufferHelper* volumeBuffers = PxCreateParticleVolumeBufferHelper(1, numTriangles, cudaContextManager); //Volumes are optional. They are used to accelerate scene queries, e. g. to support picking. PxParticleClothBufferHelper* clothBuffers = PxCreateParticleClothBufferHelper(1, numTriangles, numSprings, numParticles, cudaContextManager); clothBuffers->addCloth(0.0f, cooker->getMeshVolume(), pressure, triangles, numTriangles, springs.begin(), numSprings, positionInvMass, numParticles); volumeBuffers->addVolume(0, numParticles, triangles, numTriangles); cooker->release(); ExtGpu::PxParticleBufferDesc bufferDesc; bufferDesc.maxParticles = numParticles; bufferDesc.numActiveParticles = numParticles; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phases; bufferDesc.maxVolumes = volumeBuffers->getMaxVolumes(); bufferDesc.numVolumes = volumeBuffers->getNumVolumes(); bufferDesc.volumes = volumeBuffers->getParticleVolumes(); PxParticleClothPreProcessor* clothPreProcessor = PxCreateParticleClothPreProcessor(cudaContextManager); PxPartitionedParticleCloth output; const PxParticleClothDesc& clothDesc = clothBuffers->getParticleClothDesc(); clothPreProcessor->partitionSprings(clothDesc, output); clothPreProcessor->release(); gUserClothBuffer = physx::ExtGpu::PxCreateAndPopulateParticleClothBuffer(bufferDesc, clothDesc, output, cudaContextManager); gParticleSystem->addParticleBuffer(gUserClothBuffer); clothBuffers->release(); volumeBuffers->release(); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phases); } PxPBDParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleClothBuffer* getUserClothBuffer() { return gUserClothBuffer; } // ----------------------------------------------------------------------------------------------------------------- void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup Cloth const PxReal totalInflatableMass = 100.0f; PxReal particleSpacing = 0.05f; PxArray<PxVec3> vertices; PxArray<PxU32> indices; createSphere(vertices, indices, PxVec3(0, 10, 0), 3, 0.25f); initInflatable(vertices, indices, particleSpacing, totalInflatableMass); initObstacles(); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.0f), *gMaterial)); // Setup rigid bodies const PxReal boxSize = 0.75f; const PxReal boxMass = 0.25f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 2.0f, 10, 0.f))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } // --------------------------------------------------- void stepPhysics(bool /*interactive*/) { if (gIsRunning) { const PxReal dt = 1.0f / 60.0f; gScene->simulate(dt); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBDInflatable done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
14,487
C++
36.926701
212
0.728377
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbdinflatable/SnippetPBDInflatableRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContext.h" #include "cudamanager/PxCudaContextManager.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #define CUDA_SUCCESS 0 #define SHOW_SOLID_SDF_SLICE 0 #define IDX(i, j, k, offset) ((i) + dimX * ((j) + dimY * ((k) + dimZ * (offset)))) using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxPBDParticleSystem* getParticleSystem(); extern PxParticleClothBuffer* getUserClothBuffer(); namespace { Snippets::Camera* sCamera; Snippets::SharedGLBuffer sPosBuffer; void onBeforeRenderParticles() { PxPBDParticleSystem* particleSystem = getParticleSystem(); if (particleSystem) { PxParticleClothBuffer* userBuffer = getUserClothBuffer(); PxVec4* positions = userBuffer->getPositionInvMasses(); const PxU32 numParticles = userBuffer->getNbActiveParticles(); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); cudaContextManager->acquireContext(); PxCudaContext* cudaContext = cudaContextManager->getCudaContext(); cudaContext->memcpyDtoH(sPosBuffer.map(), CUdeviceptr(positions), sizeof(PxVec4) * numParticles); cudaContextManager->releaseContext(); #if SHOW_SOLID_SDF_SLICE particleSystem->copySparseGridData(sSparseGridSolidSDFBufferD, PxSparseGridDataFlag::eGRIDCELL_SOLID_GRADIENT_AND_SDF); #endif } } void renderParticles() { sPosBuffer.unmap(); PxVec3 color(1.f, 0.75f, 0); Snippets::DrawPoints(sPosBuffer.vbo, sPosBuffer.size / sizeof(PxVec4), color, 2.f); Snippets::DrawFrame(PxVec3(0, 0, 0)); } void allocParticleBuffers() { PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxCudaContextManager* cudaContextManager = scene->getCudaContextManager(); PxParticleClothBuffer* userBuffer = getUserClothBuffer(); PxU32 maxParticles = userBuffer->getMaxParticles(); sPosBuffer.initialize(cudaContextManager); sPosBuffer.allocate(maxParticles * sizeof(PxVec4)); } void clearupParticleBuffers() { sPosBuffer.release(); } void renderCallback() { onBeforeRenderParticles(); stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true); } renderParticles(); Snippets::showFPS(); Snippets::finishRender(); } void cleanup() { delete sCamera; clearupParticleBuffers(); cleanupPhysics(true); } void exitCallback(void) { } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(15.0f, 10.0f, 15.0f), PxVec3(-0.6f,-0.2f,-0.6f)); Snippets::setupDefault("PhysX Snippet PBDInflatable", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); Snippets::initFPS(); allocParticleBuffers(); glutMainLoop(); cleanup(); } #endif
5,042
C++
29.197605
136
0.760809
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonebroadphase/SnippetStandaloneBroadphase.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. // **************************************************************************** // This snippet illustrates how to use a standalone broadphase. // It creates a small custom scene (no PxScene) and creates a broadphase for the // scene objects. These objects are then updated each frame and rendered in red // when they touch another object, or green if they don't. Use the P and O keys // to pause and step the simulation one frame, to visually check the results. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace immediate; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static const PxU32 gNbObjects = 100; static float gTime = 0.0f; static bool gPause = false; static bool gOneFrame = false; static PxVec3 computeObjectPosition(PxU32 i) { const float coeff = float(i)*0.2f; return PxVec3( sinf(gTime*coeff*0.567f)*cosf(gTime+coeff)*3.0f, cosf(gTime*coeff*0.0917f)*cosf(gTime*1.17f+coeff)*2.0f, sinf(gTime*coeff*0.533f)*cosf(gTime*0.33f+coeff)*3.0f); } namespace { class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void render(); void updateObjects(); void createBroadphase(); void runBroadphase(); struct Object { PxGeometryHolder mGeom; PxTransform mPose; PxU32 mNbCollisions; }; PxArray<Object> mObjects; PxBroadPhase* mBroadphase; PxAABBManager* mAABBManager; }; CustomScene::CustomScene() : mBroadphase(NULL), mAABBManager(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mAABBManager); PX_RELEASE(mBroadphase); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { Object obj; obj.mGeom.storeAny(geom); obj.mPose = pose; mObjects.pushBack(obj); } void CustomScene::createBroadphase() { PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); mBroadphase = PxCreateBroadPhase(bpDesc); mAABBManager = PxCreateAABBManager(*mBroadphase); const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; obj.mPose.p = computeObjectPosition(i); obj.mNbCollisions = 0; PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj.mGeom.any(), obj.mPose); mAABBManager->addObject(i, bounds, PxGetBroadPhaseDynamicFilterGroup(i)); } runBroadphase(); } void CustomScene::runBroadphase() { PxBroadPhaseResults results; mAABBManager->update(results); for(PxU32 i=0;i<results.mNbCreatedPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; mObjects[id0].mNbCollisions++; mObjects[id1].mNbCollisions++; } for(PxU32 i=0;i<results.mNbDeletedPairs;i++) { const PxU32 id0 = results.mDeletedPairs[i].mID0; const PxU32 id1 = results.mDeletedPairs[i].mID1; PX_ASSERT(mObjects[id0].mNbCollisions); PX_ASSERT(mObjects[id1].mNbCollisions); mObjects[id0].mNbCollisions--; mObjects[id1].mNbCollisions--; } } void CustomScene::updateObjects() { if(gPause && !gOneFrame) return; gOneFrame = false; gTime += 0.001f; const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; obj.mPose.p = computeObjectPosition(i); PxBounds3 newBounds; PxGeometryQuery::computeGeomBounds(newBounds, obj.mGeom.any(), obj.mPose); mAABBManager->updateObject(i, &newBounds); } runBroadphase(); } void CustomScene::render() { updateObjects(); #ifdef RENDER_SNIPPET const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; const PxVec3 color = obj.mNbCollisions ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } #endif } } static void initScene() { } static void releaseScene() { } static CustomScene* gScene = NULL; void renderScene() { if(gScene) gScene->render(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gScene = new CustomScene; for(PxU32 i=0;i<gNbObjects;i++) gScene->addGeom(PxBoxGeometry(PxVec3(0.1f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->createBroadphase(); initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gScene); PX_RELEASE(gFoundation); printf("SnippetStandaloneBroadphase done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } } int snippetMain(int, const char*const*) { printf("Standalone broadphase snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,206
C++
24.831541
95
0.712046
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonebroadphase/SnippetStandaloneBroadphaseRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void renderScene(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); renderScene(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet StandaloneBroadphase", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,908
C++
33.630952
117
0.750344
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatemode/SnippetImmediateMode.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. // **************************************************************************** // This snippet illustrates the use of PhysX immediate mode. // // It creates a number of box stacks on a plane, and if rendering, allows the // user to create new stacks and fire a ball from the camera position // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetutils/SnippetImmUtils.h" #include "foundation/PxArray.h" #include "PxImmediateMode.h" #include "extensions/PxMassProperties.h" #include "../snippetcommon/SnippetPrint.h" #include "extensions/PxRigidActorExt.h" #define USE_TGS 1 //Enables whether we want persistent state caching (contact cache, friction caching) or not. Avoiding persistency results in one-shot collision detection and zero friction //correlation but simplifies code by not longer needing to cache persistent pairs. #define WITH_PERSISTENCY 1 //Toggles between using low-level inertia computation code or using the RigidBodyExt inertia computation code. The former can operate without the need for PxRigidDynamics being constructed. #define USE_LOWLEVEL_INERTIA_COMPUTATION 1 //Toggles whether we batch constraints or not. Constraint batching is an optional process which can improve performance by grouping together independent constraints. These independent constraints //can be solved in parallel by using multiple lanes of SIMD registers. #define BATCH_CONTACTS 1 // Toggles whether we use PhysX' "immediate broadphase", or not. If we don't, a simple O(n^2) broadphase is used. #define USE_IMMEDIATE_BROADPHASE 1 // Toggles profiling for the full step. Only for Windows. #define PROFILE_STEP 0 using namespace physx; using namespace immediate; using namespace SnippetImmUtils; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static physx::PxArray<PxConstraint*>* gConstraints = NULL; static PxReal gStackZ = 10.0f; //Enable to 1 to use centimeter units instead of meter units. //Instructive to demonstrate which values used in immediate mode are unit-dependent #define USE_CM_UNITS 0 #if !USE_CM_UNITS static const PxReal gUnitScale = 1.0f; //static float cameraSpeed = 1.0f; #else static const PxReal gUnitScale = 100.0f; //static float cameraSpeed = 100.0f; #endif #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY static PxU32 gFrameIndex = 0; #endif #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE static PxAABBManager* gAABBManager = NULL; struct PersistentPair { PersistentPair() {} PersistentPair(PxU32 id0, PxU32 id1) : mID0(id0), mID1(id1) {} PX_INLINE bool operator == (const PersistentPair& a) const { return a.mID0 == mID0 && a.mID1 == mID1; } PxU32 mID0; PxU32 mID1; }; struct PersistentPairData { PxRigidActor* actor0; PxRigidActor* actor1; PxCache cache; PxU8* frictions; PxU32 nbFrictions; }; static PX_INLINE uint32_t PxComputeHash(const PersistentPair& p) { return PxComputeHash(uint64_t(p.mID0)|(uint64_t(p.mID1)<<32)); } static PxHashMap<PersistentPair, PersistentPairData>* gPersistentPairs = NULL; #else namespace { struct PersistentContactPair { PxCache cache; PxU8* frictions; PxU32 nbFrictions; }; } static PxArray<PersistentContactPair>* allContactCache = NULL; #endif #endif static TestCacheAllocator* gCacheAllocator = NULL; static TestConstraintAllocator* gConstraintAllocator = NULL; namespace { struct ContactPair { PxRigidActor* actor0; PxRigidActor* actor1; PxU32 idx0, idx1; PxU32 startContactIndex; PxU32 nbContacts; }; class TestContactRecorder : public immediate::PxContactRecorder { PxArray<ContactPair>& mContactPairs; PxArray<PxContactPoint>& mContactPoints; PxRigidActor& mActor0; PxRigidActor& mActor1; PxU32 mIdx0, mIdx1; bool mHasContacts; public: TestContactRecorder(PxArray<ContactPair>& contactPairs, PxArray<PxContactPoint>& contactPoints, PxRigidActor& actor0, PxRigidActor& actor1, PxU32 idx0, PxU32 idx1) : mContactPairs(contactPairs), mContactPoints(contactPoints), mActor0(actor0), mActor1(actor1), mIdx0(idx0), mIdx1(idx1), mHasContacts(false) { } virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 index) { PX_UNUSED(index); { ContactPair pair; pair.actor0 = &mActor0; pair.actor1 = &mActor1; pair.nbContacts = nbContacts; pair.startContactIndex = mContactPoints.size(); pair.idx0 = mIdx0; pair.idx1 = mIdx1; mContactPairs.pushBack(pair); mHasContacts = true; } for (PxU32 c = 0; c < nbContacts; ++c) { //Fill in solver-specific data that our contact gen does not produce... PxContactPoint point = contactPoints[c]; point.maxImpulse = PX_MAX_F32; point.targetVel = PxVec3(0.0f); point.staticFriction = 0.5f; point.dynamicFriction = 0.5f; point.restitution = 0.0f; point.materialFlags = 0; mContactPoints.pushBack(point); } return true; } PX_FORCE_INLINE bool hasContacts() const { return mHasContacts; } private: PX_NOCOPY(TestContactRecorder) }; } static bool generateContacts( const PxGeometryHolder& geom0, const PxGeometryHolder& geom1, PxRigidActor& actor0, PxRigidActor& actor1, PxCacheAllocator& cacheAllocator, PxArray<PxContactPoint>& contactPoints, PxArray<ContactPair>& contactPairs, PxU32 idx0, PxU32 idx1, PxCache& cache) { const PxTransform tr0 = actor0.getGlobalPose(); const PxTransform tr1 = actor1.getGlobalPose(); TestContactRecorder recorder(contactPairs, contactPoints, actor0, actor1, idx0, idx1); const PxGeometry* pxGeom0 = &geom0.any(); const PxGeometry* pxGeom1 = &geom1.any(); physx::immediate::PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &cache, 1, recorder, gUnitScale*0.04f, gUnitScale*0.01f, gUnitScale, cacheAllocator); return recorder.hasContacts(); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void updateInertia(PxRigidBody* body, PxReal density) { #if !USE_LOWLEVEL_INERTIA_COMPUTATION PX_UNUSED(density); //Compute the inertia of the rigid body using the helper function in PxRigidBodyExt PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); #else //Compute the inertia/mass of the bodies using the more low-level PxMassProperties interface //This was written for readability rather than performance. Complexity can be avoided if you know that you are dealing with a single shape body PxU32 nbShapes = body->getNbShapes(); //Keep track of an array of inertia tensors and local poses. physx::PxArray<PxMassProperties> inertias; physx::PxArray<PxTransform> localPoses; for (PxU32 a = 0; a < nbShapes; ++a) { PxShape* shape; body->getShapes(&shape, 1, a); //(1) initialize an inertia tensor based on the shape's geometry PxMassProperties inertia(shape->getGeometry()); //(2) Scale the inertia tensor based on density. If you use a single density instead of a density per-shape, this could be performed just prior to //extracting the massSpaceInertiaTensor inertia = inertia * density; inertias.pushBack(inertia); localPoses.pushBack(shape->getLocalPose()); } //(3)Sum all the inertia tensors - can be skipped if the shape count is 1 PxMassProperties inertia = PxMassProperties::sum(inertias.begin(), localPoses.begin(), inertias.size()); //(4)Get the diagonalized inertia component and frame of the mass space orientation PxQuat orient; const PxVec3 diagInertia = PxMassProperties::getMassSpaceInertia(inertia.inertiaTensor, orient); //(4) Set properties on the rigid body body->setMass(inertia.mass); body->setCMassLocalPose(PxTransform(inertia.centerOfMass, orient)); body->setMassSpaceInertiaTensor(diagInertia); #endif } /*static*/ void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i<size; i++) { for (PxU32 j = 0; j<size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); updateInertia(body, 10.f); gScene->addActor(*body); } } shape->release(); } struct Triangle { PxU32 ind0, ind1, ind2; }; static PxTriangleMesh* createMeshGround() { const PxU32 gridSize = 8; const PxReal gridStep = 512.f / (gridSize-1); PxVec3 verts[gridSize * gridSize]; const PxU32 nbTriangles = 2 * (gridSize - 1) * (gridSize-1); Triangle indices[nbTriangles]; for (PxU32 a = 0; a < gridSize; ++a) { for (PxU32 b = 0; b < gridSize; ++b) { verts[a * gridSize + b] = PxVec3(-400.f + b*gridStep, 0.f, -400.f + a*gridStep); } } for (PxU32 a = 0; a < (gridSize-1); ++a) { for (PxU32 b = 0; b < (gridSize-1); ++b) { Triangle& tri0 = indices[(a * (gridSize-1) + b) * 2]; Triangle& tri1 = indices[((a * (gridSize-1) + b) * 2) + 1]; tri0.ind0 = a * gridSize + b + 1; tri0.ind1 = a * gridSize + b; tri0.ind2 = (a + 1) * gridSize + b + 1; tri1.ind0 = (a + 1) * gridSize + b + 1; tri1.ind1 = a * gridSize + b; tri1.ind2 = (a + 1) * gridSize + b; } } PxTriangleMeshDesc meshDesc; meshDesc.points.data = verts; meshDesc.points.count = gridSize * gridSize; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = nbTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = sizeof(Triangle); PxCookingParams cookingParams(gPhysics->getTolerancesScale()); PxTriangleMesh* triMesh = PxCreateTriangleMesh(cookingParams, meshDesc, gPhysics->getPhysicsInsertionCallback()); return triMesh; } #if WITH_PERSISTENCY && USE_IMMEDIATE_BROADPHASE static void createBroadPhase() { PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); PxBroadPhase* bp = PxCreateBroadPhase(bpDesc); gAABBManager = PxCreateAABBManager(*bp); gPersistentPairs = new PxHashMap<PersistentPair, PersistentPairData>; } static void releaseBroadPhase() { PxBroadPhase* bp = &gAABBManager->getBroadPhase(); PX_RELEASE(gAABBManager); PX_RELEASE(bp); delete gPersistentPairs; } #endif static void updateContactPairs() { #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE // In this simple snippet we just recreate the broadphase structure here releaseBroadPhase(); createBroadPhase(); gFrameIndex = 0; #else allContactCache->clear(); const PxU32 nbDynamic = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); const PxU32 nbStatic = gScene->getNbActors(PxActorTypeFlag::eRIGID_STATIC); const PxU32 totalPairs = (nbDynamic * (nbDynamic - 1)) / 2 + nbDynamic * nbStatic; allContactCache->resize(totalPairs); for (PxU32 a = 0; a < totalPairs; ++a) { (*allContactCache)[a].frictions = NULL; (*allContactCache)[a].nbFrictions = 0; (*allContactCache)[a].cache.mCachedData = 0; (*allContactCache)[a].cache.mCachedSize = 0; (*allContactCache)[a].cache.mManifoldFlags = 0; (*allContactCache)[a].cache.mPairData = 0; } #endif #endif } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::ePROFILE); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f)*gUnitScale; gDispatcher = PxDefaultCpuDispatcherCreate(0); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.2f); gConstraints = new physx::PxArray<PxConstraint*>(); const bool useGroundMesh = true; // Use a triangle mesh or a plane for the ground if(useGroundMesh) { PxTriangleMesh* mesh = createMeshGround(); PxTriangleMeshGeometry geom(mesh); PxRigidStatic* groundMesh = gPhysics->createRigidStatic(PxTransform(PxVec3(0, 2, 0))); PxRigidActorExt::createExclusiveShape(*groundMesh, geom, *gMaterial); gScene->addActor(*groundMesh); } else { PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); } for (PxU32 i = 0; i<4; i++) createStack(PxTransform(PxVec3(0, 2, gStackZ -= 10.0f*gUnitScale)), 20, gUnitScale); PxRigidDynamic* ball = createDynamic(PxTransform(PxVec3(0, 20, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); PxRigidDynamic* ball2 = createDynamic(PxTransform(PxVec3(0, 24, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); PxRigidDynamic* ball3 = createDynamic(PxTransform(PxVec3(0, 27, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); updateInertia(ball, 1000.f); updateInertia(ball2, 1000.f); PxD6Joint* joint = PxD6JointCreate(*gPhysics, ball, PxTransform(PxVec3(0, 4, 0)*gUnitScale), ball2, PxTransform(PxVec3(0, -2, 0)*gUnitScale)); PxD6Joint* joint2 = PxD6JointCreate(*gPhysics, ball2, PxTransform(PxVec3(0, 4, 0)*gUnitScale), ball3, PxTransform(PxVec3(0, -2, 0)*gUnitScale)); gConstraints->pushBack(joint->getConstraint()); gConstraints->pushBack(joint2->getConstraint()); gCacheAllocator = new TestCacheAllocator; gConstraintAllocator = new TestConstraintAllocator; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE createBroadPhase(); #else allContactCache = new PxArray<PersistentContactPair>; #endif #endif updateContactPairs(); } void stepPhysics(bool /*interactive*/) { #if PROFILE_STEP PxU64 time = __rdtsc(); #endif gCacheAllocator->reset(); gConstraintAllocator->release(); const PxU32 nbStatics = gScene->getNbActors(PxActorTypeFlag::eRIGID_STATIC); const PxU32 nbDynamics = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); const PxU32 totalActors = nbDynamics + nbStatics; PxArray<ContactPair> activeContactPairs; PxArray<PxContactPoint> contactPoints; activeContactPairs.reserve(4 * totalActors); PxArray<PxActor*> actors(totalActors); PxArray<PxBounds3> shapeBounds(totalActors+1); PxArray<PxGeometryHolder> mGeometries(totalActors); #if USE_TGS PxArray<PxTGSSolverBodyVel> bodies(totalActors); PxArray<PxTGSSolverBodyData> bodyData(totalActors); PxArray<PxTGSSolverBodyTxInertia> txInertia(totalActors); PxArray<PxTransform> globalPoses(totalActors); #else PxArray<PxSolverBody> bodies(totalActors); PxArray<PxSolverBodyData> bodyData(totalActors); #endif #if USE_IMMEDIATE_BROADPHASE && !WITH_PERSISTENCY PxArray<PxBpIndex> handles(totalActors); PxArray<PxBpFilterGroup> groups(totalActors); PxArray<float> distances(totalActors); #endif gScene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC, actors.begin(), nbDynamics); gScene->getActors(PxActorTypeFlag::eRIGID_STATIC, actors.begin() + nbDynamics, nbStatics); #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY gFrameIndex++; #endif //Now do collision detection...Brute force every dynamic against every dynamic/static for (PxU32 a = 0; a < totalActors; ++a) { PxRigidActor* actor = actors[a]->is<PxRigidActor>(); PxShape* shape; actor->getShapes(&shape, 1); //Compute the AABBs. We inflate these by 2cm margins shapeBounds[a] = PxShapeExt::getWorldBounds(*shape, *actor, 1.f); shapeBounds[a].minimum -= PxVec3(0.02f)*gUnitScale; shapeBounds[a].maximum += PxVec3(0.02f)*gUnitScale; mGeometries[a].storeAny(shape->getGeometry()); #if USE_IMMEDIATE_BROADPHASE #if WITH_PERSISTENCY if(gFrameIndex==1) { const PxBpFilterGroup group = a < nbDynamics ? PxGetBroadPhaseDynamicFilterGroup(a) : PxGetBroadPhaseStaticFilterGroup(); gAABBManager->addObject(a, shapeBounds[a], group); } else if(a < nbDynamics) { gAABBManager->updateObject(a, &shapeBounds[a]); } #else handles[a] = a; distances[a]= 0.0f; if(a < nbDynamics) groups[a] = PxGetBroadPhaseDynamicFilterGroup(a); else groups[a] = PxGetBroadPhaseStaticFilterGroup(); #endif #endif } #if USE_IMMEDIATE_BROADPHASE { PxBroadPhaseResults results; #if WITH_PERSISTENCY gAABBManager->update(results); const PxU32 nbCreatedPairs = results.mNbCreatedPairs; for(PxU32 i=0;i<nbCreatedPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; const PersistentPair currentPair(id0, id1); PersistentPairData data; data.actor0 = actors[id0]->is<PxRigidActor>(); data.actor1 = actors[id1]->is<PxRigidActor>(); data.frictions = NULL; data.nbFrictions = 0; data.cache = PxCache(); bool b = gPersistentPairs->insert(currentPair, data); PX_ASSERT(b); PX_UNUSED(b); } const PxU32 nbDeletedPairs = results.mNbDeletedPairs; for(PxU32 i=0;i<nbDeletedPairs;i++) { const PxU32 id0 = results.mDeletedPairs[i].mID0; const PxU32 id1 = results.mDeletedPairs[i].mID1; const PersistentPair currentPair(id0, id1); PxHashMap<PersistentPair, PersistentPairData>::Entry removedEntry; bool b = gPersistentPairs->erase(currentPair, removedEntry); PX_ASSERT(b); PX_UNUSED(b); } #else PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); PxBroadPhase* bp = PxCreateBroadPhase(bpDesc); const PxBroadPhaseUpdateData updateData(handles.begin(), totalActors, NULL, 0, NULL, 0, shapeBounds.begin(), groups.begin(), distances.begin(), totalActors); bp->update(results, updateData); const PxU32 nbPairs = results.mNbCreatedPairs; for(PxU32 i=0;i<nbPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; ContactPair pair; pair.actor0 = actors[id0]->is<PxRigidActor>(); pair.actor1 = actors[id1]->is<PxRigidActor>(); pair.idx0 = id0; pair.idx1 = id1; activeContactPairs.pushBack(pair); } PX_RELEASE(bp); #endif } #else { //Broad phase for active pairs... for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dyn0 = actors[a]->is<PxRigidDynamic>(); for (PxU32 b = a + 1; b < totalActors; ++b) { PxRigidActor* actor1 = actors[b]->is<PxRigidActor>(); if (shapeBounds[a].intersects(shapeBounds[b])) { ContactPair pair; pair.actor0 = dyn0; pair.actor1 = actor1; pair.idx0 = a; pair.idx1 = b; activeContactPairs.pushBack(pair); } #if WITH_PERSISTENCY else { const PxU32 startIndex = a == 0 ? 0 : (a * totalActors) - (a * (a + 1)) / 2; PersistentContactPair& persistentData = (*allContactCache)[startIndex + (b - a - 1)]; //No collision detection performed at all so clear contact cache and friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; persistentData.cache = PxCache(); } #endif } } } #endif #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY const PxU32 nbActivePairs = gPersistentPairs->size(); activeContactPairs.forceSize_Unsafe(0); contactPoints.reserve(4 * nbActivePairs); for(PxHashMap<PersistentPair, PersistentPairData>::Iterator iter = gPersistentPairs->getIterator(); !iter.done(); ++iter) { const PxU32 id0 = iter->first.mID0; const PxU32 id1 = iter->first.mID1; PxRigidActor* dyn0 = iter->second.actor0; const PxGeometryHolder& holder0 = mGeometries[id0]; PxRigidActor* actor1 = iter->second.actor1; const PxGeometryHolder& holder1 = mGeometries[id1]; if (!generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, id0, id1, iter->second.cache)) { //Contact generation run but no touches found so clear cached friction data iter->second.frictions = NULL; iter->second.nbFrictions = 0; } } #else const PxU32 nbActivePairs = activeContactPairs.size(); ContactPair* activePairs = activeContactPairs.begin(); activeContactPairs.forceSize_Unsafe(0); contactPoints.reserve(4 * nbActivePairs); for (PxU32 a = 0; a < nbActivePairs; ++a) { const ContactPair& pair = activePairs[a]; PxRigidActor* dyn0 = pair.actor0; const PxGeometryHolder& holder0 = mGeometries[pair.idx0]; PxRigidActor* actor1 = pair.actor1; const PxGeometryHolder& holder1 = mGeometries[pair.idx1]; #if WITH_PERSISTENCY const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; PersistentContactPair& persistentData = (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)]; if (!generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, pair.idx0, pair.idx1, persistentData.cache)) { //Contact generation run but no touches found so clear cached friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; } #else PxCache cache; generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, pair.idx0, pair.idx1, cache); #endif } #endif const PxReal dt = 1.f / 60.f; const PxReal invDt = 60.f; const PxU32 nbPositionIterations = 4; const PxU32 nbVelocityIterations = 1; #if USE_TGS const PxReal stepDt = dt/PxReal(nbPositionIterations); const PxReal invStepDt = invDt * PxReal(nbPositionIterations); #endif const PxVec3 gravity(0.f, -9.8f* gUnitScale, 0.f); //Construct solver bodies for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dyn = actors[a]->is<PxRigidDynamic>(); immediate::PxRigidBodyData data; data.linearVelocity = dyn->getLinearVelocity(); data.angularVelocity = dyn->getAngularVelocity(); data.invMass = dyn->getInvMass(); data.invInertia = dyn->getMassSpaceInvInertiaTensor(); data.body2World = dyn->getGlobalPose(); data.maxDepenetrationVelocity = dyn->getMaxDepenetrationVelocity(); data.maxContactImpulse = dyn->getMaxContactImpulse(); data.linearDamping = dyn->getLinearDamping(); data.angularDamping = dyn->getAngularDamping(); data.maxLinearVelocitySq = 100.f*100.f*gUnitScale*gUnitScale; data.maxAngularVelocitySq = 7.f*7.f; #if USE_TGS physx::immediate::PxConstructSolverBodiesTGS(&data, &bodies[a], &txInertia[a], &bodyData[a], 1, gravity, dt); globalPoses[a] = data.body2World; #else physx::immediate::PxConstructSolverBodies(&data, &bodyData[a], 1, gravity, dt); #endif dyn->userData = reinterpret_cast<void*>(size_t(a)); } //Construct static bodies for (PxU32 a = nbDynamics; a < totalActors; ++a) { PxRigidStatic* sta = actors[a]->is<PxRigidStatic>(); #if USE_TGS physx::immediate::PxConstructStaticSolverBodyTGS(sta->getGlobalPose(), bodies[a], txInertia[a], bodyData[a]); globalPoses[a] = sta->getGlobalPose(); #else physx::immediate::PxConstructStaticSolverBody(sta->getGlobalPose(), bodyData[a]); #endif sta->userData = reinterpret_cast<void*>(size_t(a)); } PxArray<PxSolverConstraintDesc> descs(activeContactPairs.size() + gConstraints->size()); for (PxU32 a = 0; a < activeContactPairs.size(); ++a) { PxSolverConstraintDesc& desc = descs[a]; ContactPair& pair = activeContactPairs[a]; //Set body pointers and bodyData idxs #if USE_TGS desc.tgsBodyA = &bodies[pair.idx0]; desc.tgsBodyB = &bodies[pair.idx1]; #else desc.bodyA = &bodies[pair.idx0]; desc.bodyB = &bodies[pair.idx1]; #endif desc.bodyADataIndex = pair.idx0; desc.bodyBDataIndex = pair.idx1; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; //Cache pointer to our contact data structure and identify which type of constraint this is. We'll need this later after batching. //If we choose not to perform batching and instead just create a single header per-pair, then this would not be necessary because //the constraintDescs would not have been reordered desc.constraint = reinterpret_cast<PxU8*>(&pair); desc.constraintLengthOver16 = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } for (PxU32 a = 0; a < gConstraints->size(); ++a) { PxConstraint* constraint = (*gConstraints)[a]; PxSolverConstraintDesc& desc = descs[activeContactPairs.size() + a]; PxRigidActor* actor0, *actor1; constraint->getActors(actor0, actor1); const PxU32 id0 = PxU32(size_t(actor0->userData)); const PxU32 id1 = PxU32(size_t(actor1->userData)); #if USE_TGS desc.tgsBodyA = &bodies[id0]; desc.tgsBodyB = &bodies[id1]; #else desc.bodyA = &bodies[id0]; desc.bodyB = &bodies[id1]; #endif desc.bodyADataIndex = PxU16(id0); desc.bodyBDataIndex = PxU16(id1); desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; desc.constraint = reinterpret_cast<PxU8*>(constraint); desc.constraintLengthOver16 = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } PxArray<PxConstraintBatchHeader> headers(descs.size()); PxArray<PxReal> contactForces(contactPoints.size()); //Technically, you can batch the contacts and joints all at once using a single call but doing so mixes them in the orderedDescs array, which means that it is impossible to //batch all contact or all joint dispatches into a single call. While we don't do this in this snippet (we instead process a single header at a time), our approach could be extended to //dispatch all contact headers at once if that was necessary. #if BATCH_CONTACTS PxArray<PxSolverConstraintDesc> tempOrderedDescs(descs.size()); physx::PxArray<PxSolverConstraintDesc>& orderedDescs = tempOrderedDescs; #if USE_TGS //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraintsTGS(descs.begin(), activeContactPairs.size(), bodies.begin(), nbDynamics, headers.begin(), orderedDescs.begin()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraintsTGS(descs.begin() + activeContactPairs.size(), gConstraints->size(), bodies.begin(), nbDynamics, headers.begin() + nbContactHeaders, orderedDescs.begin() + activeContactPairs.size()); #else //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraints(descs.begin(), activeContactPairs.size(), bodies.begin(), nbDynamics, headers.begin(), orderedDescs.begin()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraints(descs.begin() + activeContactPairs.size(), gConstraints->size(), bodies.begin(), nbDynamics, headers.begin() + nbContactHeaders, orderedDescs.begin() + activeContactPairs.size()); #endif #else physx::PxArray<PxSolverConstraintDesc>& orderedDescs = descs; //We are bypassing the constraint batching so we create dummy PxConstraintBatchHeaders const PxU32 nbContactHeaders = activeContactPairs.size(); const PxU32 nbJointHeaders = gConstraints->size(); for (PxU32 i = 0; i < nbContactHeaders; ++i) { PxConstraintBatchHeader& hdr = headers[i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } for (PxU32 i = 0; i < nbJointHeaders; ++i) { PxConstraintBatchHeader& hdr = headers[nbContactHeaders+i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif const PxU32 totalHeaders = nbContactHeaders + nbJointHeaders; headers.forceSize_Unsafe(totalHeaders); //1 - Create all the contact constraints. We do this by looping over all the headers and, for each header, constructing the PxSolverContactDesc objects, then creating that contact constraint. //We could alternatively create all the PxSolverContactDesc objects in a single pass, then create batch create that constraint for (PxU32 i = 0; i < nbContactHeaders; ++i) { PxConstraintBatchHeader& header = headers[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eCONTACT_CONSTRAINT); #if USE_TGS PxTGSSolverContactDesc contactDescs[4]; #else PxSolverContactDesc contactDescs[4]; #endif #if WITH_PERSISTENCY const ContactPair* pairs[4]; #endif for (PxU32 a = 0; a < header.stride; ++a) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else PxSolverContactDesc& contactDesc = contactDescs[a]; #endif PxMemZero(&contactDesc, sizeof(contactDesc)); //Extract the contact pair that we saved in this structure earlier. const ContactPair& pair = *reinterpret_cast<const ContactPair*>(constraintDesc.constraint); #if WITH_PERSISTENCY pairs[a] = &pair; #endif #if USE_TGS contactDesc.body0 = constraintDesc.tgsBodyA; contactDesc.body1 = constraintDesc.tgsBodyB; contactDesc.bodyData0 = &bodyData[constraintDesc.bodyADataIndex]; contactDesc.bodyData1 = &bodyData[constraintDesc.bodyBDataIndex]; contactDesc.body0TxI = &txInertia[constraintDesc.bodyADataIndex]; contactDesc.body1TxI = &txInertia[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. contactDesc.bodyFrame0 = globalPoses[constraintDesc.bodyADataIndex]; contactDesc.bodyFrame1 = globalPoses[constraintDesc.bodyBDataIndex]; #else contactDesc.body0 = constraintDesc.bodyA; contactDesc.body1 = constraintDesc.bodyB; contactDesc.data0 = &bodyData[constraintDesc.bodyADataIndex]; contactDesc.data1 = &bodyData[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. contactDesc.bodyFrame0 = contactDesc.data0->body2World; contactDesc.bodyFrame1 = contactDesc.data1->body2World; #endif contactDesc.contactForces = &contactForces[pair.startContactIndex]; contactDesc.contacts = &contactPoints[pair.startContactIndex]; contactDesc.numContacts = pair.nbContacts; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE const PersistentPair currentPair(pair.idx0, pair.idx1); const PxHashMap<PersistentPair, PersistentPairData>::Entry* e = gPersistentPairs->find(currentPair); contactDesc.frictionPtr = e->second.frictions; contactDesc.frictionCount = PxU8(e->second.nbFrictions); #else const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; contactDesc.frictionPtr = (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].frictions; contactDesc.frictionCount = PxU8((*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].nbFrictions); #endif #else contactDesc.frictionPtr = NULL; contactDesc.frictionCount = 0; #endif contactDesc.shapeInteraction = NULL; contactDesc.maxCCDSeparation = PX_MAX_F32; contactDesc.bodyState0 = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; contactDesc.bodyState1 = pair.actor1->is<PxRigidDynamic>() ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; contactDesc.desc = &constraintDesc; contactDesc.invMassScales.angular0 = contactDesc.invMassScales.angular1 = contactDesc.invMassScales.linear0 = contactDesc.invMassScales.linear1 = 1.f; } #if USE_TGS immediate::PxCreateContactConstraintsTGS(&header, 1, contactDescs, *gConstraintAllocator, invStepDt, invDt, -2.f * gUnitScale, 0.04f * gUnitScale, 0.025f * gUnitScale); #else immediate::PxCreateContactConstraints(&header, 1, contactDescs, *gConstraintAllocator, invDt, -2.f * gUnitScale, 0.04f * gUnitScale, 0.025f * gUnitScale); #endif #if WITH_PERSISTENCY for (PxU32 a = 0; a < header.stride; ++a) { //Cache friction information... #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else PxSolverContactDesc& contactDesc = contactDescs[a]; #endif //PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; const ContactPair& pair = *pairs[a]; #if USE_IMMEDIATE_BROADPHASE const PersistentPair currentPair(pair.idx0, pair.idx1); PxHashMap<PersistentPair, PersistentPairData>::Entry* e = const_cast<PxHashMap<PersistentPair, PersistentPairData>::Entry*>(gPersistentPairs->find(currentPair)); e->second.frictions = contactDesc.frictionPtr; e->second.nbFrictions = contactDesc.frictionCount; #else const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].frictions = contactDesc.frictionPtr; (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].nbFrictions = contactDesc.frictionCount; #endif } #endif } for (PxU32 i = nbContactHeaders; i < totalHeaders; ++i) { PxConstraintBatchHeader& header = headers[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eJOINT_CONSTRAINT); { #if USE_TGS PxTGSSolverConstraintPrepDesc jointDescs[4]; #else PxSolverConstraintPrepDesc jointDescs[4]; #endif PxConstraint* constraints[4]; header.startIndex += activeContactPairs.size(); for (PxU32 a = 0; a < header.stride; ++a) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. PxConstraint& constraint = *reinterpret_cast<PxConstraint*>(constraintDesc.constraint); constraints[a] = &constraint; #if USE_TGS PxTGSSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.tgsBodyA; jointDesc.body1 = constraintDesc.tgsBodyB; jointDesc.bodyData0 = &bodyData[constraintDesc.bodyADataIndex]; jointDesc.bodyData1 = &bodyData[constraintDesc.bodyBDataIndex]; jointDesc.body0TxI = &txInertia[constraintDesc.bodyADataIndex]; jointDesc.body1TxI = &txInertia[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. jointDesc.bodyFrame0 = globalPoses[constraintDesc.bodyADataIndex]; jointDesc.bodyFrame1 = globalPoses[constraintDesc.bodyBDataIndex]; #else PxSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.bodyA; jointDesc.body1 = constraintDesc.bodyB; jointDesc.data0 = &bodyData[constraintDesc.bodyADataIndex]; jointDesc.data1 = &bodyData[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. jointDesc.bodyFrame0 = jointDesc.data0->body2World; jointDesc.bodyFrame1 = jointDesc.data1->body2World; #endif PxRigidActor* actor0, *actor1; constraint.getActors(actor0, actor1); jointDesc.bodyState0 = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; jointDesc.bodyState1 = actor1 == NULL ? PxSolverConstraintPrepDescBase::eSTATIC_BODY : actor1->is<PxRigidDynamic>() ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; jointDesc.desc = &constraintDesc; jointDesc.invMassScales.angular0 = jointDesc.invMassScales.angular1 = jointDesc.invMassScales.linear0 = jointDesc.invMassScales.linear1 = 1.f; jointDesc.writeback = NULL; constraint.getBreakForce(jointDesc.linBreakForce, jointDesc.angBreakForce); jointDesc.minResponseThreshold = constraint.getMinResponseThreshold(); jointDesc.disablePreprocessing = !!(constraint.getFlags() & PxConstraintFlag::eDISABLE_PREPROCESSING); jointDesc.improvedSlerp = !!(constraint.getFlags() & PxConstraintFlag::eIMPROVED_SLERP); jointDesc.driveLimitsAreForces = !!(constraint.getFlags() & PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES); } #if USE_TGS immediate::PxCreateJointConstraintsWithShadersTGS(&header, 1, constraints, jointDescs, *gConstraintAllocator, stepDt, dt, invStepDt, invDt, 1.f); #else immediate::PxCreateJointConstraintsWithShaders(&header, 1, constraints, jointDescs, *gConstraintAllocator, dt, invDt); #endif } } #if USE_TGS immediate::PxSolveConstraintsTGS(headers.begin(), headers.size(), orderedDescs.begin(), bodies.begin(), txInertia.begin(), nbDynamics, nbPositionIterations, nbVelocityIterations, stepDt, invStepDt); immediate::PxIntegrateSolverBodiesTGS(bodies.begin(), txInertia.begin(), globalPoses.begin(), nbDynamics, dt); for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dynamic = actors[a]->is<PxRigidDynamic>(); const PxTGSSolverBodyVel& body = bodies[a]; dynamic->setLinearVelocity(body.linearVelocity); dynamic->setAngularVelocity(body.angularVelocity); dynamic->setGlobalPose(globalPoses[a]); } #else //Solve all the constraints produced earlier. Intermediate motion linear/angular velocity buffers are filled in. These contain intermediate delta velocity information that is used //the PxIntegrateSolverBody PxArray<PxVec3> motionLinearVelocity(nbDynamics); PxArray<PxVec3> motionAngularVelocity(nbDynamics); //Zero the bodies array. This buffer contains the delta velocities and are accumulated during the simulation. For correct behavior, it is vital //that this buffer is zeroed. PxMemZero(bodies.begin(), bodies.size() * sizeof(PxSolverBody)); immediate::PxSolveConstraints(headers.begin(), headers.size(), orderedDescs.begin(), bodies.begin(), motionLinearVelocity.begin(), motionAngularVelocity.begin(), nbDynamics, nbPositionIterations, nbVelocityIterations); immediate::PxIntegrateSolverBodies(bodyData.begin(), bodies.begin(), motionLinearVelocity.begin(), motionAngularVelocity.begin(), nbDynamics, dt); for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dynamic = actors[a]->is<PxRigidDynamic>(); const PxSolverBodyData& data = bodyData[a]; dynamic->setLinearVelocity(data.linearVelocity); dynamic->setAngularVelocity(data.angularVelocity); dynamic->setGlobalPose(data.body2World); } #endif #if PROFILE_STEP time = __rdtsc() - time; printf("Time: %d\n", PxU32(time/1024)); #endif } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } delete gCacheAllocator; delete gConstraintAllocator; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE releaseBroadPhase(); #else delete allContactCache; #endif #endif PX_RELEASE(gFoundation); printf("SnippetImmediateMode done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f*gUnitScale), camera.rotate(PxVec3(0, 0, -1)) * 200*gUnitScale); updateContactPairs(); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
41,062
C++
34.399138
249
0.741245
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatemode/SnippetImmediateModeRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern float cameraSpeed; namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera, 10.f, 100000.f); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], PxU32(actors.size()), true, dynColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet Immediate Mode", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
2,957
C++
33
136
0.758877
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdeformablemesh/SnippetDeformableMesh.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. // **************************************************************************** // This snippet shows how to use deformable meshes in PhysX. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxTriangleMesh* gMesh = NULL; static PxRigidStatic* gActor = NULL; static const PxU32 gGridSize = 8; static const PxReal gGridStep = 512.0f / PxReal(gGridSize-1); static float gTime = 0.0f; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0), PxReal density=1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } struct Triangle { PxU32 ind0, ind1, ind2; }; static void updateVertices(PxVec3* verts, float amplitude=0.0f) { const PxU32 gridSize = gGridSize; const PxReal gridStep = gGridStep; for(PxU32 a=0; a<gridSize; a++) { const float coeffA = float(a)/float(gridSize); for(PxU32 b=0; b<gridSize; b++) { const float coeffB = float(b)/float(gridSize); const float y = 20.0f + sinf(coeffA*PxTwoPi)*cosf(coeffB*PxTwoPi)*amplitude; verts[a * gridSize + b] = PxVec3(-400.0f + b*gridStep, y, -400.0f + a*gridStep); } } } static PxTriangleMesh* createMeshGround(const PxCookingParams& params) { const PxU32 gridSize = gGridSize; PxVec3 verts[gridSize * gridSize]; const PxU32 nbTriangles = 2 * (gridSize - 1) * (gridSize-1); Triangle indices[nbTriangles]; updateVertices(verts); for (PxU32 a = 0; a < (gridSize-1); ++a) { for (PxU32 b = 0; b < (gridSize-1); ++b) { Triangle& tri0 = indices[(a * (gridSize-1) + b) * 2]; Triangle& tri1 = indices[((a * (gridSize-1) + b) * 2) + 1]; tri0.ind0 = a * gridSize + b + 1; tri0.ind1 = a * gridSize + b; tri0.ind2 = (a + 1) * gridSize + b + 1; tri1.ind0 = (a + 1) * gridSize + b + 1; tri1.ind1 = a * gridSize + b; tri1.ind2 = (a + 1) * gridSize + b; } } PxTriangleMeshDesc meshDesc; meshDesc.points.data = verts; meshDesc.points.count = gridSize * gridSize; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = nbTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = sizeof(Triangle); PxTriangleMesh* triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); return triMesh; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxCookingParams cookingParams(gPhysics->getTolerancesScale()); if(0) { cookingParams.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH33); } else { cookingParams.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); cookingParams.midphaseDesc.mBVH34Desc.quantized = false; } // We need to disable the mesh cleaning part so that the vertex mapping remains untouched. cookingParams.meshPreprocessParams = PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; PxTriangleMesh* mesh = createMeshGround(cookingParams); gMesh = mesh; PxTriangleMeshGeometry geom(mesh); PxRigidStatic* groundMesh = gPhysics->createRigidStatic(PxTransform(PxVec3(0, 2, 0))); gActor = groundMesh; PxShape* shape = gPhysics->createShape(geom, *gMaterial); { shape->setContactOffset(0.02f); // A negative rest offset helps to avoid jittering when the deformed mesh moves away from objects resting on it. shape->setRestOffset(-0.5f); } groundMesh->attachShape(*shape); gScene->addActor(*groundMesh); createStack(PxTransform(PxVec3(0,22,0)), 10, 2.0f); } PxBounds3 gBounds; void debugRender() { const PxVec3 c = gBounds.getCenter(); const PxVec3 e = gBounds.getExtents(); PxVec3 pts[8]; pts[0] = c + PxVec3(-e.x, -e.y, e.z); pts[1] = c + PxVec3(-e.x, e.y, e.z); pts[2] = c + PxVec3( e.x, e.y, e.z); pts[3] = c + PxVec3( e.x, -e.y, e.z); pts[4] = c + PxVec3(-e.x, -e.y, -e.z); pts[5] = c + PxVec3(-e.x, e.y, -e.z); pts[6] = c + PxVec3( e.x, e.y, -e.z); pts[7] = c + PxVec3( e.x, -e.y, -e.z); std::vector<PxVec3> gContactVertices; struct AddQuad { static void func(std::vector<PxVec3>& v, const PxVec3* pts_, PxU32 index0, PxU32 index1, PxU32 index2, PxU32 index3) { v.push_back(pts_[index0]); v.push_back(pts_[index1]); v.push_back(pts_[index1]); v.push_back(pts_[index2]); v.push_back(pts_[index2]); v.push_back(pts_[index3]); v.push_back(pts_[index3]); v.push_back(pts_[index0]); } }; AddQuad::func(gContactVertices, pts, 0, 1, 2, 3); AddQuad::func(gContactVertices, pts, 4, 5, 6, 7); AddQuad::func(gContactVertices, pts, 0, 1, 5, 4); AddQuad::func(gContactVertices, pts, 2, 3, 7, 6); glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(gContactVertices.size())); glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_LIGHTING); } void stepPhysics(bool /*interactive*/) { { PxVec3* verts = gMesh->getVerticesForModification(); gTime += 0.01f; updateVertices(verts, sinf(gTime)*20.0f); { // unsigned long long time = __rdtsc(); gBounds = gMesh->refitBVH(); // time = __rdtsc() - time; // printf("Time: %d\n", int(time)); } // Reset filtering to tell the broadphase about the new mesh bounds. gScene->resetFiltering(*gActor); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetDeformableMesh done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200, 3.0f); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char*const*) { return 0; } #endif
10,192
C++
29.426866
141
0.705455
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdeformablemesh/SnippetDeformableMeshRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern void debugRender(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } debugRender(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(50.0f, 50.0f, 50.0f), PxVec3(-0.6f,-0.2f,-0.7f)); Snippets::setupDefault("PhysX Snippet DeformableMesh", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,107
C++
33.533333
136
0.757644
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcommon/SnippetPrint.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_PRINT_H #define PHYSX_SNIPPET_PRINT_H #include "foundation/PxPreprocessor.h" #if PX_SWITCH #include "../SnippetCommon/Switch/SwitchSnippetPrint.h" #endif #endif // PHYSX_SNIPPET_PRINT_H
1,909
C
47.974358
74
0.766894
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcommon/ClassicMain.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. extern int snippetMain(int, const char*const*); int main(int argc, char** argv) { return snippetMain(argc, argv); }
1,816
C++
50.914284
74
0.762665
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcommon/SnippetPVD.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_PVD_H #define PHYSX_SNIPPET_PVD_H #define PVD_HOST "127.0.0.1" //Set this to the IP address of the system running the PhysX Visual Debugger that you want to connect to. #endif //PHYSX_SNIPPET_PVD_H
1,921
C
52.388887
134
0.764185
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2fourwheeldrive/SnippetVehicleFourWheelDrive.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. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a vehicle with a fully featured drivetrain comprising engine, // clutch, differential and gears. The snippet uses only parameters, states and // components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a drivetrain model that forwards input controls to wheel torques via a drivetrain model // that includes engine, clutch, differential and gears. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/EngineDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with engine drivetrain EngineDriveVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "engineDrive"; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxU32 gear; PxF32 duration; }; const PxU32 gTargetGearCommand = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; Command gCommands[] = { {0.5f, 0.0f, 0.0f, gTargetGearCommand, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.65f, 0.0f, gTargetGearCommand, 5.0f}, //throttle for 5 seconds {0.5f, 0.0f, 0.0f, gTargetGearCommand, 5.0f}, //brake for 5 seconds {0.0f, 0.75f, 0.0f, gTargetGearCommand, 5.0f}, //throttle for 5 seconds {0.0f, 0.25f, 0.5f, gTargetGearCommand, 5.0f} //light throttle and steer for 5 seconds. }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", gVehicle.mEngineDriveParams); //Set the states to default. if (!gVehicle.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, EngineDriveVehicle::eDIFFTYPE_FOURWHEELDRIVE)) { return false; } //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(0.000000000f, -0.0500000119f, -1.59399998f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Set the vehicle in 1st gear. gVehicle.mEngineDriveState.gearboxState.currentGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; gVehicle.mEngineDriveState.gearboxState.targetGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; //Set the vehicle to use the automatic gearbox. gVehicle.mTransmissionCommandState.targetGear = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; const PxReal timestep = 1.0f/60.0f; //Apply the brake, throttle and steer to the command state of the vehicle. const Command& command = gCommands[gCommandProgress]; gVehicle.mCommandState.brakes[0] = command.brake; gVehicle.mCommandState.nbBrakes = 1; gVehicle.mCommandState.throttle = command.throttle; gVehicle.mCommandState.steer = command.steer; gVehicle.mTransmissionCommandState.targetGear = command.gear; //Forward integrate the vehicle by a single timestep. //Apply substepping at low forward speed to improve simulation fidelity. const PxVec3 linVel = gVehicle.mPhysXState.physxActor.rigidBody->getLinearVelocity(); const PxVec3 forwardDir = gVehicle.mPhysXState.physxActor.rigidBody->getGlobalPose().q.getBasisVector2(); const PxReal forwardSpeed = linVel.dot(forwardDir); const PxU8 nbSubsteps = (forwardSpeed < 5.0f ? 3 : 1); gVehicle.mComponentSequence.setSubsteps(gVehicle.mComponentSequenceSubstepGroupHandle, nbSubsteps); gVehicle.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2FourWheelDrive", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. EngineDrivetrainParams engineDrivetrainParams; if (!readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", engineDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { while (gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
14,778
C++
38.943243
133
0.769252
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrackjoint/SnippetRackJoint.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. // **************************************************************************** // This snippet illustrates simple use of rack & pinion joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createGearWithBoxes(PxPhysics& sdk, const PxBoxGeometry& boxGeom, const PxTransform& transform, PxMaterial& material, int nbShapes) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); PxMat33 m(PxIdentity); for(int i=0;i<nbShapes;i++) { const float coeff = float(i)/float(nbShapes); const float angle = PxPi * 0.5f * coeff; PxShape* shape = sdk.createShape(boxGeom, material, true); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); shape->setLocalPose(localPose); actor->attachShape(*shape); } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRigidDynamic* createRackWithBoxes(PxPhysics& sdk, const PxTransform& transform, PxMaterial& material, int nbTeeth, float rackLength) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); { const PxBoxGeometry boxGeom(rackLength*0.5f, 0.25f, 0.25f); PxShape* shape = sdk.createShape(boxGeom, material, true); actor->attachShape(*shape); } PxMat33 m(PxIdentity); const float angle = PxPi * 0.25f; const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); const float offset = rackLength / float(nbTeeth); localPose.p.x = (offset - rackLength)*0.5f; for(int i=0;i<nbTeeth;i++) { const PxBoxGeometry boxGeom(0.75f, 0.75f, 0.25f); PxShape* shape = sdk.createShape(boxGeom, material, true); shape->setLocalPose(localPose); actor->attachShape(*shape); localPose.p.x += offset; } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRevoluteJoint* gHinge0 = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); const float velocityTarget = 0.5f; const float radius = 3.0f; const float rackLength = 3.0f*10.0f; const int nbPinionTeeth = int(radius)*4; // 'radius' teeth for PI/2 const int nbRackTeeth = 5*3; const PxBoxGeometry boxGeom0(radius, radius, 0.5f); const PxVec3 boxPos0(0.0f, 10.0f, 0.0f); const PxVec3 boxPos1(0.0f, 10.0f+radius+1.5f, 0.0f); PxRigidDynamic* actor0 = createGearWithBoxes(*gPhysics, boxGeom0, PxTransform(boxPos0), *gMaterial, int(radius)); gScene->addActor(*actor0); PxRigidDynamic* actor1 = createRackWithBoxes(*gPhysics, PxTransform(boxPos1), *gMaterial, nbRackTeeth, rackLength); gScene->addActor(*actor1); const PxQuat x2z = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f)); PxRevoluteJoint* hinge = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos0, x2z), actor0, PxTransform(PxVec3(0.0f), x2z)); PxPrismaticJoint* prismatic = PxPrismaticJointCreate(*gPhysics, NULL, PxTransform(boxPos1), actor1, PxTransform(PxVec3(0.0f))); if(1) { hinge->setDriveVelocity(velocityTarget); hinge->setRevoluteJointFlag(PxRevoluteJointFlag::eDRIVE_ENABLED, true); gHinge0 = hinge; } PxRackAndPinionJoint* rackJoint = PxRackAndPinionJointCreate(*gPhysics, actor0, PxTransform(PxVec3(0.0f), x2z), actor1, PxTransform(PxVec3(0.0f))); rackJoint->setJoints(hinge, prismatic); rackJoint->setData(nbRackTeeth, nbPinionTeeth, rackLength); } void stepPhysics(bool /*interactive*/) { if(gHinge0) { static float globalTime = 0.0f; globalTime += 1.0f/60.0f; const float velocityTarget = cosf(globalTime)*3.0f; gHinge0->setDriveVelocity(velocityTarget); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetRackJoint done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,702
C++
31.918803
154
0.726954
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrackjoint/SnippetRackJointRender.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. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); /* if(0) { PxVec3 camPos = sCamera->getEye(); PxVec3 camDir = sCamera->getDir(); printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); }*/ Snippets::startRender(sCamera); PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { const PxVec3 dynColor(1.0f, 0.5f, 0.25f); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), true, dynColor); } Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(7.401237f, 11.224086f, 15.145986f), PxVec3(-0.315603f, -0.041489f, -0.947984f)); Snippets::setupDefault("PhysX Snippet RackJoint", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
3,246
C++
33.542553
136
0.745533