file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
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
|
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;
}
|
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
|
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;
}
|
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
|
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
|
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
|
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
|
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
|
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
|
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;
}
|
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;
}
|
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
|
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;
}
|
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
|
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;
}
|
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
|
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
|
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;
}
|
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;
}
|
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
|
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;
}
|
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
|
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;
}
|
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
|
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
|
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
|
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
|
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);
}
|
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
|
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;
}
|
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;
}
|
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
|
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdelayloadhook/SnippetDelayLoadHook.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 the dll delay load hooks in physx.
//
// The hooks are needed if the application executable either doesn't reside
// in the same directory as the PhysX dlls, or if the PhysX dlls have been renamed.
// Some PhysX dlls delay load the PhysXFoundation, PhysXCommon or PhysXGpu dlls and
// the non-standard names or loactions of these dlls need to be communicated so the
// delay loading can succeed.
//
// This snippet shows how this can be done using the delay load hooks.
//
// In order to show functionality with the renamed dlls some basic physics
// simulation is performed.
// ****************************************************************************
#include <ctype.h>
#include <wtypes.h>
#include "PxPhysicsAPI.h"
// Include the delay load hook headers
#include "common/windows/PxWindowsDelayLoadHook.h"
#include "../snippetcommon/SnippetPrint.h"
#include "../snippetcommon/SnippetPVD.h"
#include "../snippetutils/SnippetUtils.h"
// This snippet uses the default PhysX distro dlls, making the example here somewhat artificial,
// as default locations and default naming makes implementing delay load hooks unnecessary.
#define APP_BIN_DIR "..\\"
#if PX_WIN64
#define DLL_NAME_BITS "64"
#else
#define DLL_NAME_BITS "32"
#endif
#if PX_DEBUG
#define DLL_DIR "debug\\"
#elif PX_CHECKED
#define DLL_DIR "checked\\"
#elif PX_PROFILE
#define DLL_DIR "profile\\"
#else
#define DLL_DIR "release\\"
#endif
const char* foundationLibraryPath = APP_BIN_DIR DLL_DIR "PhysXFoundation_" DLL_NAME_BITS ".dll";
const char* commonLibraryPath = APP_BIN_DIR DLL_DIR "PhysXCommon_" DLL_NAME_BITS ".dll";
const char* physxLibraryPath = APP_BIN_DIR DLL_DIR "PhysX_" DLL_NAME_BITS ".dll";
const char* gpuLibraryPath = APP_BIN_DIR DLL_DIR "PhysXGpu_" DLL_NAME_BITS ".dll";
HMODULE foundationLibrary = NULL;
HMODULE commonLibrary = NULL;
HMODULE physxLibrary = NULL;
using namespace physx;
static PxDefaultAllocator gAllocator;
static PxDefaultErrorCallback gErrorCallback;
static PxFoundation* gFoundation = NULL;
static PxPhysics* gPhysics = NULL;
static PxDefaultCpuDispatcher* gDispatcher = NULL;
PxScene* gScene = NULL;
static PxMaterial* gMaterial = NULL;
static PxPvd* gPvd = NULL;
// typedef the PhysX entry points
typedef PxFoundation*(PxCreateFoundation_FUNC)(PxU32, PxAllocatorCallback&, PxErrorCallback&);
typedef PxPhysics* (PxCreatePhysics_FUNC)(PxU32,PxFoundation&,const PxTolerancesScale& scale,bool,PxPvd*);
typedef void (PxSetPhysXDelayLoadHook_FUNC)(const PxDelayLoadHook* hook);
typedef void (PxSetPhysXCommonDelayLoadHook_FUNC)(const PxDelayLoadHook* hook);
#if PX_SUPPORT_GPU_PHYSX
typedef void (PxSetPhysXGpuLoadHook_FUNC)(const PxGpuLoadHook* hook);
typedef int (PxGetSuggestedCudaDeviceOrdinal_FUNC)(PxErrorCallback& errc);
typedef PxCudaContextManager* (PxCreateCudaContextManager_FUNC)(PxFoundation& foundation, const PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback);
#endif
// set the function pointers to NULL
PxCreateFoundation_FUNC* s_PxCreateFoundation_Func = NULL;
PxCreatePhysics_FUNC* s_PxCreatePhysics_Func = NULL;
PxSetPhysXDelayLoadHook_FUNC* s_PxSetPhysXDelayLoadHook_Func = NULL;
PxSetPhysXCommonDelayLoadHook_FUNC* s_PxSetPhysXCommonDelayLoadHook_Func = NULL;
#if PX_SUPPORT_GPU_PHYSX
PxSetPhysXGpuLoadHook_FUNC* s_PxSetPhysXGpuLoadHook_Func = NULL;
PxGetSuggestedCudaDeviceOrdinal_FUNC* s_PxGetSuggestedCudaDeviceOrdinal_Func = NULL;
PxCreateCudaContextManager_FUNC* s_PxCreateCudaContextManager_Func = NULL;
#endif
bool loadPhysicsExplicitely()
{
// load the dlls
foundationLibrary = LoadLibraryA(foundationLibraryPath);
if(!foundationLibrary)
return false;
commonLibrary = LoadLibraryA(commonLibraryPath);
if(!commonLibrary)
{
FreeLibrary(foundationLibrary);
return false;
}
physxLibrary = LoadLibraryA(physxLibraryPath);
if(!physxLibrary)
{
FreeLibrary(foundationLibrary);
FreeLibrary(commonLibrary);
return false;
}
// get the function pointers
s_PxCreateFoundation_Func = (PxCreateFoundation_FUNC*)GetProcAddress(foundationLibrary, "PxCreateFoundation");
s_PxCreatePhysics_Func = (PxCreatePhysics_FUNC*)GetProcAddress(physxLibrary, "PxCreatePhysics");
s_PxSetPhysXDelayLoadHook_Func = (PxSetPhysXDelayLoadHook_FUNC*)GetProcAddress(physxLibrary, "PxSetPhysXDelayLoadHook");
s_PxSetPhysXCommonDelayLoadHook_Func = (PxSetPhysXCommonDelayLoadHook_FUNC*)GetProcAddress(commonLibrary, "PxSetPhysXCommonDelayLoadHook");
#if PX_SUPPORT_GPU_PHYSX
s_PxSetPhysXGpuLoadHook_Func = (PxSetPhysXGpuLoadHook_FUNC*)GetProcAddress(physxLibrary, "PxSetPhysXGpuLoadHook");
s_PxGetSuggestedCudaDeviceOrdinal_Func = (PxGetSuggestedCudaDeviceOrdinal_FUNC*)GetProcAddress(physxLibrary, "PxGetSuggestedCudaDeviceOrdinal");
s_PxCreateCudaContextManager_Func = (PxCreateCudaContextManager_FUNC*)GetProcAddress(physxLibrary, "PxCreateCudaContextManager");
#endif
// check if we have all required function pointers
if(s_PxCreateFoundation_Func == NULL || s_PxCreatePhysics_Func == NULL || s_PxSetPhysXDelayLoadHook_Func == NULL || s_PxSetPhysXCommonDelayLoadHook_Func == NULL)
return false;
#if PX_SUPPORT_GPU_PHYSX
if(s_PxSetPhysXGpuLoadHook_Func == NULL || s_PxGetSuggestedCudaDeviceOrdinal_Func == NULL || s_PxCreateCudaContextManager_Func == NULL)
return false;
#endif
return true;
}
// unload the dlls
void unloadPhysicsExplicitely()
{
FreeLibrary(physxLibrary);
FreeLibrary(commonLibrary);
FreeLibrary(foundationLibrary);
}
// Overriding the PxDelayLoadHook allows the load of a custom name dll inside PhysX, PhysXCommon and PhysXCooking dlls
struct SnippetDelayLoadHook : public PxDelayLoadHook
{
virtual const char* getPhysXFoundationDllName() const
{
return foundationLibraryPath;
}
virtual const char* getPhysXCommonDllName() const
{
return commonLibraryPath;
}
};
#if PX_SUPPORT_GPU_PHYSX
// Overriding the PxGpuLoadHook allows the load of a custom GPU name dll
struct SnippetGpuLoadHook : public PxGpuLoadHook
{
virtual const char* getPhysXGpuDllName() const
{
return gpuLibraryPath;
}
};
#endif
PxReal stackZ = 10.0f;
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;
}
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)
{
// load the explictely named dlls
const bool isLoaded = loadPhysicsExplicitely();
if (!isLoaded)
return;
gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback);
// set PhysX and PhysXCommon delay load hook, this must be done before the create physics is called, before
// the PhysXFoundation, PhysXCommon delay load happens.
SnippetDelayLoadHook delayLoadHook;
s_PxSetPhysXDelayLoadHook_Func(&delayLoadHook);
s_PxSetPhysXCommonDelayLoadHook_Func(&delayLoadHook);
#if PX_SUPPORT_GPU_PHYSX
// set PhysXGpu load hook
SnippetGpuLoadHook gpuLoadHook;
s_PxSetPhysXGpuLoadHook_Func(&gpuLoadHook);
#endif
gPvd = PxCreatePvd(*gFoundation);
PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10);
gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL);
gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd);
// We setup the delay load hooks first
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*/)
{
if (gScene)
{
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);
unloadPhysicsExplicitely();
printf("SnippetDelayLoadHook 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;
}
|
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdelayloadhook/SnippetDelayLoadHookRender.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 PxScene* gScene;
namespace
{
Snippets::Camera* sCamera;
void renderCallback()
{
stepPhysics(true);
Snippets::startRender(sCamera);
if (gScene)
{
PxU32 nbActors = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC);
if(nbActors)
{
std::vector<PxRigidActor*> actors(nbActors);
gScene->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 Delay Load Hook", sCamera, keyPress, renderCallback, exitCallback);
initPhysics(true);
glutMainLoop();
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/snippets/snippettolerancescale/SnippetToleranceScale.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 concept of PxToleranceScale.
//
// It creates 2 scenes using different units for length and mass.
// Use PVD to replay the scene and see how scaling affects the simulation.
// ********************************************************************************
#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 gStackZ = 10.0f;
PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxReal& mass, const PxVec3& velocity=PxVec3(0))
{
PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f);
dynamic->setAngularDamping(0.5f);
dynamic->setLinearVelocity(velocity);
PxRigidBodyExt::setMassAndUpdateInertia(*dynamic, mass);
gScene->addActor(*dynamic);
return dynamic;
}
void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent, const PxReal& mass)
{
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::setMassAndUpdateInertia(*body, mass);
gScene->addActor(*body);
}
}
shape->release();
}
void initPhysics(bool interactive, const PxTolerancesScale& scale, PxReal scaleMass)
{
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, scale, true, gPvd);
PxReal scaleLength = scale.length;
PxSceneDesc sceneDesc(scale);
sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f) * scaleLength;
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,gStackZ-=10.0f) * scaleLength), 10, 2.0f * scaleLength, 1.0f * scaleMass);
if(!interactive)
createDynamic(PxTransform(PxVec3(0,40,100) * scaleLength), PxSphereGeometry(10 * scaleLength), 100.0f * scaleMass, PxVec3(0,-50,-100) * scaleLength);
}
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);
}
void runSim(const PxTolerancesScale& scale, PxReal scaleMass)
{
static const PxU32 frameCount = 150;
initPhysics(false, scale, scaleMass);
for(PxU32 i=0; i<frameCount; i++)
stepPhysics(false);
cleanupPhysics(false);
}
int snippetMain(int, const char*const*)
{
PxTolerancesScale scale;
// Default
printf("PxToleranceScale (Default).\n");
runSim(scale, 1000.0f);
// Reset position of pyramid stack z coordinate to default
gStackZ = 10.0f;
// Scaled assets
printf("PxToleranceScale (Scaled).\n");
scale.length = 100; // length in cm
scale.speed *= scale.length; // speed in cm/s
runSim(scale, 1.0f);
printf("SnippetToleranceScale done.\n");
return 0;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryReadStreamImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdMemoryStreamImpl.h"
#include "OmniPvdMemoryReadStreamImpl.h"
OmniPvdMemoryReadStreamImpl::OmniPvdMemoryReadStreamImpl()
{
}
OmniPvdMemoryReadStreamImpl::~OmniPvdMemoryReadStreamImpl()
{
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryReadStreamImpl::readBytes(uint8_t* destination, uint64_t nbrBytes)
{
return mMemoryStream->readBytes(destination, nbrBytes);
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryReadStreamImpl::skipBytes(uint64_t nbrBytes)
{
return mMemoryStream->skipBytes(nbrBytes);
}
bool OMNI_PVD_CALL OmniPvdMemoryReadStreamImpl::openStream()
{
return true;
}
bool OMNI_PVD_CALL OmniPvdMemoryReadStreamImpl::closeStream()
{
return true;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdFileReadStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_FILE_READ_STREAM_IMPL_H
#define OMNI_PVD_FILE_READ_STREAM_IMPL_H
#include "OmniPvdFileReadStream.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
class OmniPvdFileReadStreamImpl : public OmniPvdFileReadStream
{
public:
OmniPvdFileReadStreamImpl();
~OmniPvdFileReadStreamImpl();
void OMNI_PVD_CALL setFileName(const char *fileName);
bool OMNI_PVD_CALL openFile();
bool OMNI_PVD_CALL closeFile();
uint64_t OMNI_PVD_CALL readBytes(uint8_t* bytes, uint64_t nbrBytes);
uint64_t OMNI_PVD_CALL skipBytes(uint64_t nbrBytes);
bool OMNI_PVD_CALL openStream();
bool OMNI_PVD_CALL closeStream();
char* mFileName;
bool mFileWasOpened;
FILE* mPFile;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdFileReadStreamImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdFileReadStreamImpl.h"
OmniPvdFileReadStreamImpl::OmniPvdFileReadStreamImpl()
{
mFileName = 0;
mFileWasOpened = false;
mPFile = 0;
}
OmniPvdFileReadStreamImpl::~OmniPvdFileReadStreamImpl()
{
closeFile();
delete[] mFileName;
mFileName = 0;
}
void OMNI_PVD_CALL OmniPvdFileReadStreamImpl::setFileName(const char* fileName)
{
if (!fileName) return;
int n = (int)strlen(fileName) + 1;
if (n < 2) return;
delete[] mFileName;
mFileName = new char[n];
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
strcpy_s(mFileName, n, fileName);
#else
strcpy(mFileName, fileName);
#endif
mFileName[n - 1] = 0;
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::openFile()
{
if (mFileWasOpened)
{
return true;
}
if (!mFileName)
{
return false;
}
mPFile = 0;
mFileWasOpened = true;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
errno_t err = fopen_s(&mPFile, mFileName, "rb");
if (err != 0)
{
mFileWasOpened = false;
}
else
{
fseek(mPFile, 0, SEEK_SET);
}
#else
mPFile = fopen(mFileName, "rb");
if (mPFile)
{
fseek(mPFile, 0, SEEK_SET);
}
else
{
mFileWasOpened = false;
}
#endif
return mFileWasOpened;
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::closeFile()
{
if (mFileWasOpened)
{
fclose(mPFile);
mPFile = 0;
mFileWasOpened = false;
}
return true;
}
uint64_t OMNI_PVD_CALL OmniPvdFileReadStreamImpl::readBytes(uint8_t* bytes, uint64_t nbrBytes)
{
if (mFileWasOpened)
{
size_t result = fread(bytes, 1, nbrBytes, mPFile);
return (int)result;
} else {
return 0;
}
}
uint64_t OMNI_PVD_CALL OmniPvdFileReadStreamImpl::skipBytes(uint64_t nbrBytes)
{
if (mFileWasOpened)
{
fseek(mPFile, (long)nbrBytes, SEEK_CUR);
return 0;
}
else {
return 0;
}
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::openStream()
{
return openFile();
}
bool OMNI_PVD_CALL OmniPvdFileReadStreamImpl::closeStream()
{
return closeFile();
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdWriterImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_WRITER_IMPL_H
#define OMNI_PVD_WRITER_IMPL_H
#include "OmniPvdWriter.h"
#include "OmniPvdLog.h"
class OmniPvdWriterImpl : public OmniPvdWriter {
public:
OmniPvdWriterImpl();
~OmniPvdWriterImpl();
void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction);
void setVersionHelper();
void setVersion(OmniPvdVersionType majorVersion, OmniPvdVersionType minorVersion, OmniPvdVersionType patch);
void OMNI_PVD_CALL setWriteStream(OmniPvdWriteStream& stream);
OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream();
OmniPvdClassHandle OMNI_PVD_CALL registerClass(const char* className, OmniPvdClassHandle baseClass);
OmniPvdAttributeHandle OMNI_PVD_CALL registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value);
OmniPvdAttributeHandle OMNI_PVD_CALL registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements);
OmniPvdAttributeHandle OMNI_PVD_CALL registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle);
OmniPvdAttributeHandle OMNI_PVD_CALL registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle);
OmniPvdAttributeHandle OMNI_PVD_CALL registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType);
void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes);
void OMNI_PVD_CALL createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName);
void OMNI_PVD_CALL destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle);
void OMNI_PVD_CALL startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp);
void OMNI_PVD_CALL stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp);
bool mIsFirstWrite;
OmniPvdLog mLog;
OmniPvdWriteStream* mStream;
int mLastClassHandle;
int mLastAttributeHandle;};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdHelpers.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_HELPERS_H
#define OMNI_PVD_HELPERS_H
#include <stdint.h>
extern uint8_t OmniPvdCompressInt(uint64_t handle, uint8_t *bytes);
extern uint64_t OmniPvdDeCompressInt(uint8_t *bytes, uint8_t maxBytes);
#endif |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdLibraryFunctionsImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdLibraryFunctions.h"
#include "OmniPvdReaderImpl.h"
#include "OmniPvdWriterImpl.h"
#include "OmniPvdFileReadStreamImpl.h"
#include "OmniPvdFileWriteStreamImpl.h"
#include "OmniPvdMemoryStreamImpl.h"
OMNI_PVD_EXPORT OmniPvdReader* OMNI_PVD_CALL createOmniPvdReader()
{
return new OmniPvdReaderImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdReader(OmniPvdReader& reader)
{
OmniPvdReaderImpl* impl = (OmniPvdReaderImpl*)(&reader);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdWriter* OMNI_PVD_CALL createOmniPvdWriter()
{
return new OmniPvdWriterImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdWriter(OmniPvdWriter& writer)
{
OmniPvdWriterImpl* impl = (OmniPvdWriterImpl*)(&writer);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdFileReadStream* OMNI_PVD_CALL createOmniPvdFileReadStream()
{
return new OmniPvdFileReadStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdFileReadStream(OmniPvdFileReadStream& readStream)
{
OmniPvdFileReadStreamImpl* impl = (OmniPvdFileReadStreamImpl*)(&readStream);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdFileWriteStream* OMNI_PVD_CALL createOmniPvdFileWriteStream()
{
return new OmniPvdFileWriteStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdFileWriteStream(OmniPvdFileWriteStream& writeStream)
{
OmniPvdFileWriteStreamImpl* impl = (OmniPvdFileWriteStreamImpl*)(&writeStream);
delete impl;
}
OMNI_PVD_EXPORT OmniPvdMemoryStream* OMNI_PVD_CALL createOmniPvdMemoryStream()
{
return new OmniPvdMemoryStreamImpl();
}
OMNI_PVD_EXPORT void OMNI_PVD_CALL destroyOmniPvdMemoryStream(OmniPvdMemoryStream& memoryStream)
{
OmniPvdMemoryStreamImpl* impl = (OmniPvdMemoryStreamImpl*)(&memoryStream);
delete impl;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryWriteStreamImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdMemoryStreamImpl.h"
#include "OmniPvdMemoryWriteStreamImpl.h"
OmniPvdMemoryWriteStreamImpl::OmniPvdMemoryWriteStreamImpl()
{
}
OmniPvdMemoryWriteStreamImpl::~OmniPvdMemoryWriteStreamImpl()
{
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryWriteStreamImpl::writeBytes(const uint8_t* source, uint64_t nbrBytes)
{
return mMemoryStream->writeBytes(source, nbrBytes);
}
bool OMNI_PVD_CALL OmniPvdMemoryWriteStreamImpl::flush()
{
return mMemoryStream->flush();
}
bool OMNI_PVD_CALL OmniPvdMemoryWriteStreamImpl::openStream()
{
return true;
}
bool OMNI_PVD_CALL OmniPvdMemoryWriteStreamImpl::closeStream()
{
return true;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryStreamImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdMemoryStreamImpl.h"
#include "OmniPvdMemoryReadStreamImpl.h"
#include "OmniPvdMemoryWriteStreamImpl.h"
#include <string.h>
OmniPvdMemoryStreamImpl::OmniPvdMemoryStreamImpl()
{
mReadStream = 0;
mWriteStream = 0;
mBuffer = 0;
mBufferLength = 0;
mWrittenBytes = 0;
mWritePosition = 0;
mReadPosition = 0;
mReadStream = new OmniPvdMemoryReadStreamImpl();
mReadStream->mMemoryStream = this;
mWriteStream = new OmniPvdMemoryWriteStreamImpl();
mWriteStream->mMemoryStream = this;
}
OmniPvdMemoryStreamImpl::~OmniPvdMemoryStreamImpl()
{
delete[] mBuffer;
delete mReadStream;
delete mWriteStream;
}
OmniPvdReadStream* OMNI_PVD_CALL OmniPvdMemoryStreamImpl::getReadStream()
{
return mReadStream;
}
OmniPvdWriteStream* OMNI_PVD_CALL OmniPvdMemoryStreamImpl::getWriteStream()
{
return mWriteStream;
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryStreamImpl::setBufferSize(uint64_t bufferLength)
{
if (bufferLength < mBufferLength)
{
return mBufferLength;
}
delete[] mBuffer;
mBuffer = new uint8_t[bufferLength];
mBufferLength = bufferLength;
mWrittenBytes = 0;
mWritePosition = 0;
mReadPosition = 0;
return bufferLength;
}
uint64_t OMNI_PVD_CALL OmniPvdMemoryStreamImpl::readBytes(uint8_t* destination, uint64_t nbrBytes)
{
if (mWrittenBytes < 1) return 0;
////////////////////////////////////////////////////////////////////////////////
// Limit the number of bytes requested to requestedReadBytes
////////////////////////////////////////////////////////////////////////////////
uint64_t requestedReadBytes = nbrBytes;
if (requestedReadBytes > mBufferLength)
{
requestedReadBytes = mBufferLength;
}
if (requestedReadBytes > mWrittenBytes)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Separate the reading of bytes into two operations:
// tail bytes : bytes from mReadPosition until maximum the end of the buffer
// head bytes : bytes from start of the buffer until maximum the mReadPosition-1
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Tail bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t tailBytes = mBufferLength - mReadPosition;
if (tailBytes > requestedReadBytes)
{
tailBytes = requestedReadBytes;
}
if (destination)
{
memcpy(destination, mBuffer + mReadPosition, tailBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Head bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t headBytes = requestedReadBytes - tailBytes;
if (destination)
{
memcpy(destination + tailBytes, mBuffer, headBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Update the internal parameters : mReadPosition and mWrittenBytes
////////////////////////////////////////////////////////////////////////////////
mReadPosition += requestedReadBytes;
if (mReadPosition >= mBufferLength)
{
mReadPosition -= mBufferLength;
}
mWrittenBytes -= requestedReadBytes;
return requestedReadBytes;
}
uint64_t OmniPvdMemoryStreamImpl::skipBytes(uint64_t nbrBytes)
{
return readBytes(0, nbrBytes);
}
uint64_t OmniPvdMemoryStreamImpl::writeBytes(const uint8_t* source, uint64_t nbrBytes)
{
if (mWrittenBytes >= mBufferLength)
{
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// Limit the number of bytes requested to requestedWriteBytes
////////////////////////////////////////////////////////////////////////////////
uint64_t requestedWriteBytes = nbrBytes;
if (requestedWriteBytes > mBufferLength)
{
requestedWriteBytes = mBufferLength;
}
uint64_t writeBytesLeft = mBufferLength - mWrittenBytes;
if (requestedWriteBytes > writeBytesLeft)
{
return 0;
//requestedWriteBytes = writeBytesLeft;
}
////////////////////////////////////////////////////////////////////////////////
// Tail bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t tailBytes = mBufferLength - mWritePosition;
if (tailBytes > requestedWriteBytes)
{
tailBytes = requestedWriteBytes;
}
if (source)
{
memcpy(mBuffer + mWritePosition, source, tailBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Head bytes
////////////////////////////////////////////////////////////////////////////////
uint64_t headBytes = requestedWriteBytes - tailBytes;
if (source)
{
memcpy(mBuffer, source + tailBytes, headBytes);
}
////////////////////////////////////////////////////////////////////////////////
// Update the internal parameters : mReadPosition and mWrittenBytes
////////////////////////////////////////////////////////////////////////////////
mWritePosition += requestedWriteBytes;
if (mWritePosition >= mBufferLength)
{
mWritePosition -= mBufferLength;
}
mWrittenBytes += requestedWriteBytes;
return requestedWriteBytes;
}
bool OmniPvdMemoryStreamImpl::flush()
{
return true;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdLog.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdLog.h"
#include <stdarg.h>
#include <stdio.h>
OmniPvdLog::OmniPvdLog()
{
mLogFunction = 0;
}
OmniPvdLog::~OmniPvdLog()
{
}
void OmniPvdLog::setLogFunction(OmniPvdLogFunction logFunction)
{
mLogFunction = logFunction;
}
void OmniPvdLog::outputLine(const char* fmt, ...)
{
if (!mLogFunction) return;
char logLineBuff[2048];
va_list args;
va_start(args, fmt);
vsprintf(logLineBuff, fmt, args);
va_end(args);
mLogFunction(logLineBuff);
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdDefinesInternal.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_DEFINES_INTERNAL_H
#define OMNI_PVD_DEFINES_INTERNAL_H
#include <stdint.h>
// types used to store certain properties in the PVD data stream
typedef uint8_t OmniPvdCommandStorageType;
typedef uint16_t OmniPvdDataTypeStorageType;
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryWriteStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_MEMORY_WRITE_STREAM_IMPL_H
#define OMNI_PVD_MEMORY_WRITE_STREAM_IMPL_H
#include "OmniPvdWriteStream.h"
class OmniPvdMemoryStreamImpl;
class OmniPvdMemoryWriteStreamImpl : public OmniPvdWriteStream
{
public:
OmniPvdMemoryWriteStreamImpl();
~OmniPvdMemoryWriteStreamImpl();
uint64_t OMNI_PVD_CALL writeBytes(const uint8_t* source, uint64_t nbrBytes);
bool OMNI_PVD_CALL flush();
bool OMNI_PVD_CALL openStream();
bool OMNI_PVD_CALL closeStream();
OmniPvdMemoryStreamImpl *mMemoryStream;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryReadStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_MEMORY_READ_STREAM_IMPL_H
#define OMNI_PVD_MEMORY_READ_STREAM_IMPL_H
#include "OmniPvdReadStream.h"
class OmniPvdMemoryStreamImpl;
class OmniPvdMemoryReadStreamImpl : public OmniPvdReadStream
{
public:
OmniPvdMemoryReadStreamImpl();
~OmniPvdMemoryReadStreamImpl();
uint64_t OMNI_PVD_CALL readBytes(uint8_t* destination, uint64_t nbrBytes);
uint64_t OMNI_PVD_CALL skipBytes(uint64_t nbrBytes);
bool OMNI_PVD_CALL openStream();
bool OMNI_PVD_CALL closeStream();
OmniPvdMemoryStreamImpl* mMemoryStream;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdMemoryStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_MEMORY_STREAM_IMPL_H
#define OMNI_PVD_MEMORY_STREAM_IMPL_H
#include "OmniPvdMemoryStream.h"
class OmniPvdMemoryReadStreamImpl;
class OmniPvdMemoryWriteStreamImpl;
class OmniPvdMemoryStreamImpl : public OmniPvdMemoryStream
{
public:
OmniPvdMemoryStreamImpl();
~OmniPvdMemoryStreamImpl();
OmniPvdReadStream* OMNI_PVD_CALL getReadStream();
OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream();
uint64_t OMNI_PVD_CALL setBufferSize(uint64_t bufferLength);
////////////////////////////////////////////////////////////////////////////////
// Read part
////////////////////////////////////////////////////////////////////////////////
uint64_t readBytes(uint8_t* destination, uint64_t nbrBytes);
uint64_t skipBytes(uint64_t nbrBytes);
////////////////////////////////////////////////////////////////////////////////
// Write part
////////////////////////////////////////////////////////////////////////////////
uint64_t writeBytes(const uint8_t* source, uint64_t nbrBytes);
bool flush();
////////////////////////////////////////////////////////////////////////////////
// Read/write streams
////////////////////////////////////////////////////////////////////////////////
OmniPvdMemoryReadStreamImpl *mReadStream;
OmniPvdMemoryWriteStreamImpl *mWriteStream;
////////////////////////////////////////////////////////////////////////////////
// Round robin buffer
////////////////////////////////////////////////////////////////////////////////
uint8_t *mBuffer;
uint64_t mBufferLength;
uint64_t mWrittenBytes;
uint64_t mWritePosition;
uint64_t mReadPosition;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdLog.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_LOG_H
#define OMNI_PVD_LOG_H
#include "OmniPvdDefines.h"
class OmniPvdLog {
public:
OmniPvdLog();
~OmniPvdLog();
void setLogFunction(OmniPvdLogFunction logFunction);
void outputLine(const char* fmt, ...);
OmniPvdLogFunction mLogFunction;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdHelpers.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdHelpers.h"
uint8_t OmniPvdCompressInt(uint64_t handle, uint8_t *bytes) {
uint8_t lastBitGroupIndex = 0;
uint8_t shiftBits = 0;
for (int i = 0; i < 8; i++) {
if ((handle >> shiftBits) & 0x7f) {
lastBitGroupIndex = static_cast<uint8_t>(i);
}
shiftBits += 7;
}
shiftBits = 0;
for (int i = 0; i <= lastBitGroupIndex; i++) {
uint8_t currentBitGroup = (handle >> shiftBits) & 0x7f;
if (i < lastBitGroupIndex) {
currentBitGroup |= 0x80; // Set the continuation flag bit to true
}
bytes[i] = currentBitGroup;
shiftBits += 7;
}
return lastBitGroupIndex;
}
uint64_t OmniPvdDeCompressInt(uint8_t *bytes, uint8_t maxBytes) {
if (maxBytes > 8) {
maxBytes = 8;
}
uint64_t decompressedInt = 0;
uint8_t continueFlag = 1;
uint8_t readBytes = 0;
uint8_t shiftBits = 0;
while (continueFlag && (readBytes < maxBytes)) {
const uint8_t currentByte = *bytes;
uint64_t decompressedBits = currentByte & 0x7f;
continueFlag = currentByte & 0x80;
decompressedInt |= (decompressedBits << shiftBits);
shiftBits += 7;
if (continueFlag) {
bytes++;
}
}
return decompressedInt;
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdReaderImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdDefinesInternal.h"
#include "OmniPvdReaderImpl.h"
#include <inttypes.h>
OmniPvdReaderImpl::OmniPvdReaderImpl()
{
mMajorVersion = OMNI_PVD_VERSION_MAJOR;
mMinorVersion = OMNI_PVD_VERSION_MINOR;
mPatch = OMNI_PVD_VERSION_PATCH;
mDataBuffer = 0;
mDataBuffAllocatedLen = 0;
mCmdAttributeDataPtr = 0;
mIsReadingStarted = false;
mReadBaseClassHandle = 1;
}
OmniPvdReaderImpl::~OmniPvdReaderImpl()
{
mCmdAttributeDataPtr = 0;
delete[] mDataBuffer;
mDataBuffer = 0;
mDataBuffAllocatedLen = 0;
}
void OMNI_PVD_CALL OmniPvdReaderImpl::setLogFunction(OmniPvdLogFunction logFunction)
{
mLog.setLogFunction(logFunction);
}
void OMNI_PVD_CALL OmniPvdReaderImpl::setReadStream(OmniPvdReadStream& stream)
{
mStream = &stream;
mStream->openStream();
}
bool OMNI_PVD_CALL OmniPvdReaderImpl::startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch)
{
if (mIsReadingStarted)
{
return true;
}
if (mStream)
{
mStream->readBytes((uint8_t*)&majorVersion, sizeof(OmniPvdVersionType));
mStream->readBytes((uint8_t*)&minorVersion, sizeof(OmniPvdVersionType));
mStream->readBytes((uint8_t*)&patch, sizeof(OmniPvdVersionType));
mCmdMajorVersion = majorVersion;
mCmdMinorVersion = minorVersion;
mCmdPatch = patch;
if ((mCmdMajorVersion == 0) && (mCmdMinorVersion < 3))
{
mCmdBaseClassHandle = 0;
mReadBaseClassHandle = 0;
}
else
{
mCmdBaseClassHandle = 0;
mReadBaseClassHandle = 1;
}
mLog.outputLine("OmniPvdRuntimeReaderImpl::startReading majorVersion(%lu), minorVersion(%lu), patch(%lu)", static_cast<unsigned long>(majorVersion), static_cast<unsigned long>(minorVersion), static_cast<unsigned long>(patch));
if (majorVersion > mMajorVersion)
{
mLog.outputLine("[parser] major version too new\n");
return false;
}
else if (majorVersion == mMajorVersion)
{
if (minorVersion > mMinorVersion)
{
mLog.outputLine("[parser] minor version too new\n");
return false;
}
else if (minorVersion == mMinorVersion)
{
if (patch > mPatch)
{
mLog.outputLine("[parser] patch too new\n");
return false;
}
}
}
mIsReadingStarted = true;
return true;
}
else {
return false;
}
}
static OmniPvdDataType::Enum readDataType(OmniPvdReadStream& stream)
{
OmniPvdDataTypeStorageType dataType;
stream.readBytes((uint8_t*)&dataType, sizeof(OmniPvdDataTypeStorageType));
return static_cast<OmniPvdDataType::Enum>(dataType);
}
OmniPvdCommand::Enum OMNI_PVD_CALL OmniPvdReaderImpl::getNextCommand()
{
OmniPvdCommand::Enum cmdType = OmniPvdCommand::eINVALID;
if (!mIsReadingStarted)
{
if (!startReading(mCmdMajorVersion, mCmdMinorVersion, mCmdPatch))
{
return cmdType;
}
}
if (mStream) {
OmniPvdCommandStorageType command;
if (mStream->readBytes(&command, sizeof(OmniPvdCommandStorageType)))
{
switch (command) {
case OmniPvdCommand::eREGISTER_CLASS:
{
cmdType = OmniPvdCommand::eREGISTER_CLASS;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
////////////////////////////////////////////////////////////////////////////////
// Skip reading the base class if the stream is older or equal to (0,2,x)
////////////////////////////////////////////////////////////////////////////////
if (mReadBaseClassHandle)
{
mStream->readBytes((uint8_t*)&mCmdBaseClassHandle, sizeof(OmniPvdClassHandle));
}
mStream->readBytes((uint8_t*)&mCmdClassNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdClassName, mCmdClassNameLen);
mCmdClassName[mCmdClassNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register class (handle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), mCmdClassName);
}
break;
case OmniPvdCommand::eREGISTER_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mCmdAttributeDataType = readDataType(*mStream);
if (mCmdAttributeDataType == OmniPvdDataType::eENUM_VALUE)
{
mStream->readBytes((uint8_t*)&mCmdEnumValue, sizeof(OmniPvdEnumValueType));
}
else if (mCmdAttributeDataType == OmniPvdDataType::eFLAGS_WORD)
{
mStream->readBytes((uint8_t*)&mCmdEnumClassHandle, sizeof(OmniPvdClassHandle));
}
else
{
mCmdEnumValue = 0;
mStream->readBytes((uint8_t*)&mCmdAttributeNbElements, sizeof(uint32_t));
}
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register attribute (classHandle: %llu, handle: %llu, dataType: %llu, nrFields: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataType), static_cast<unsigned long long>(mCmdAttributeNbElements), mCmdAttributeName);
}
break;
case OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register class attribute (classHandle: %llu, handle: %llu, classAttributeHandle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeClassHandle), mCmdAttributeName);
}
break;
case OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
mCmdAttributeDataType = readDataType(*mStream);
mStream->readBytes((uint8_t*)&mCmdAttributeNameLen, sizeof(uint16_t));
mStream->readBytes((uint8_t*)mCmdAttributeName, mCmdAttributeNameLen);
mCmdAttributeName[mCmdAttributeNameLen] = 0; // trailing zero
mLog.outputLine("[parser] register attributeSet (classHandle: %llu, handle: %llu, dataType: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataType), mCmdAttributeName);
}
break;
case OmniPvdCommand::eSET_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eSET_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] set attribute (contextHandle:%llu, objectHandle: %llu, handle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] add to attributeSet (contextHandle:%llu, objectHandle: %llu, attributeHandle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE:
{
cmdType = OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdAttributeHandleDepth, sizeof(uint8_t));
uint32_t* attributeHandleStack = mCmdAttributeHandleStack;
for (int i = 0; i < mCmdAttributeHandleDepth; i++) {
mStream->readBytes((uint8_t*)&mCmdAttributeHandle, sizeof(OmniPvdAttributeHandle));
attributeHandleStack++;
}
mStream->readBytes((uint8_t*)&mCmdAttributeDataLen, sizeof(uint32_t));
readLongDataFromStream(mCmdAttributeDataLen);
mLog.outputLine("[parser] remove from attributeSet (contextHandle:%llu, objectHandle: %llu, handle: %llu, dataLen: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle), static_cast<unsigned long long>(mCmdAttributeHandle), static_cast<unsigned long long>(mCmdAttributeDataLen));
}
break;
case OmniPvdCommand::eCREATE_OBJECT:
{
cmdType = OmniPvdCommand::eCREATE_OBJECT;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdClassHandle, sizeof(OmniPvdClassHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mStream->readBytes((uint8_t*)&mCmdObjectNameLen, sizeof(uint16_t));
if (mCmdObjectNameLen) {
mStream->readBytes((uint8_t*)mCmdObjectName, mCmdObjectNameLen);
}
mCmdObjectName[mCmdObjectNameLen] = 0; // trailing zero
mLog.outputLine("[parser] create object (contextHandle: %llu, classHandle: %llu, objectHandle: %llu, name: %s)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdClassHandle), static_cast<unsigned long long>(mCmdObjectHandle), mCmdObjectName);
}
break;
case OmniPvdCommand::eDESTROY_OBJECT:
{
cmdType = OmniPvdCommand::eDESTROY_OBJECT;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdObjectHandle, sizeof(OmniPvdObjectHandle));
mLog.outputLine("[parser] destroy object (contextHandle: %llu, objectHandle: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdObjectHandle));
}
break;
case OmniPvdCommand::eSTART_FRAME:
{
cmdType = OmniPvdCommand::eSTART_FRAME;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdFrameTimeStart, sizeof(uint64_t));
mLog.outputLine("[parser] start frame (contextHandle: %llu, timeStamp: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdFrameTimeStart));
}
break;
case OmniPvdCommand::eSTOP_FRAME:
{
cmdType = OmniPvdCommand::eSTOP_FRAME;
mStream->readBytes((uint8_t*)&mCmdContextHandle, sizeof(OmniPvdContextHandle));
mStream->readBytes((uint8_t*)&mCmdFrameTimeStop, sizeof(uint64_t));
mLog.outputLine("[parser] stop frame (contextHandle: %llu, timeStamp: %llu)\n", static_cast<unsigned long long>(mCmdContextHandle), static_cast<unsigned long long>(mCmdFrameTimeStop));
}
break;
default:
{
}
break;
}
return cmdType;
} else {
return cmdType;
}
}
else {
return cmdType;
}
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getMajorVersion()
{
return mCmdMajorVersion;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getMinorVersion()
{
return mCmdMinorVersion;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getPatch()
{
return mCmdPatch;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getContextHandle()
{
return mCmdContextHandle;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getClassHandle()
{
return mCmdClassHandle;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getBaseClassHandle()
{
return mCmdBaseClassHandle;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeHandle() {
return mCmdAttributeHandle;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getObjectHandle() {
return mCmdObjectHandle;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getClassName() {
return mCmdClassName;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeName() {
return mCmdAttributeName;
}
const char* OMNI_PVD_CALL OmniPvdReaderImpl::getObjectName() {
return mCmdObjectName;
}
const uint8_t* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataPointer() {
return mCmdAttributeDataPtr;
}
OmniPvdDataType::Enum OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataType() {
return mCmdAttributeDataType;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeDataLength() {
return mCmdAttributeDataLen;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeNumberElements() {
return mCmdAttributeNbElements;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeClassHandle() {
return mCmdAttributeClassHandle;
}
uint8_t OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeNumberHandles() {
return mCmdAttributeHandleDepth;
}
uint32_t* OMNI_PVD_CALL OmniPvdReaderImpl::getAttributeHandles() {
return mCmdAttributeHandleStack;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getFrameTimeStart() {
return mCmdFrameTimeStart;
}
uint64_t OMNI_PVD_CALL OmniPvdReaderImpl::getFrameTimeStop() {
return mCmdFrameTimeStop;
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdReaderImpl::getEnumClassHandle()
{
return mCmdEnumClassHandle;
}
uint32_t OMNI_PVD_CALL OmniPvdReaderImpl::getEnumValue()
{
return mCmdEnumValue;
}
void OmniPvdReaderImpl::readLongDataFromStream(uint32_t streamByteLen) {
if (streamByteLen < 1) return;
if (streamByteLen > mDataBuffAllocatedLen) {
delete[] mDataBuffer;
mDataBuffAllocatedLen = (uint32_t)(streamByteLen * 1.3f);
mDataBuffer = new uint8_t[mDataBuffAllocatedLen];
mCmdAttributeDataPtr = mDataBuffer;
}
mStream->readBytes(mCmdAttributeDataPtr, streamByteLen);
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdFileWriteStreamImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_FILE_WRITE_STREAM_IMPL_H
#define OMNI_PVD_FILE_WRITE_STREAM_IMPL_H
#include "OmniPvdFileWriteStream.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
class OmniPvdFileWriteStreamImpl : public OmniPvdFileWriteStream {
public:
OmniPvdFileWriteStreamImpl();
~OmniPvdFileWriteStreamImpl();
void OMNI_PVD_CALL setFileName(const char *fileName);
bool OMNI_PVD_CALL openFile();
bool OMNI_PVD_CALL closeFile();
uint64_t OMNI_PVD_CALL writeBytes(const uint8_t* bytes, uint64_t nbrBytes);
bool OMNI_PVD_CALL flush();
bool OMNI_PVD_CALL openStream();
bool OMNI_PVD_CALL closeStream();
char *mFileName;
bool mFileWasOpened;
FILE *mPFile;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdWriterImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdDefinesInternal.h"
#include "OmniPvdWriterImpl.h"
#include "OmniPvdCommands.h"
#include <string.h>
OmniPvdWriterImpl::OmniPvdWriterImpl()
{
mLastClassHandle = 0;
mLastAttributeHandle = 0;
mIsFirstWrite = true;
mStream = 0;
}
OmniPvdWriterImpl::~OmniPvdWriterImpl()
{
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setLogFunction(OmniPvdLogFunction logFunction)
{
mLog.setLogFunction(logFunction);
}
void OmniPvdWriterImpl::setVersionHelper()
{
if (mStream && mIsFirstWrite)
{
const OmniPvdVersionType omniPvdVersionMajor = OMNI_PVD_VERSION_MAJOR;
const OmniPvdVersionType omniPvdVersionMinor = OMNI_PVD_VERSION_MINOR;
const OmniPvdVersionType omniPvdVersionPatch = OMNI_PVD_VERSION_PATCH;
setVersion(omniPvdVersionMajor, omniPvdVersionMinor, omniPvdVersionPatch);
}
}
void OmniPvdWriterImpl::setVersion(OmniPvdVersionType majorVersion, OmniPvdVersionType minorVersion, OmniPvdVersionType patch)
{
if (mStream && mIsFirstWrite)
{
if (!mStream->openStream())
{
return;
}
mStream->writeBytes((const uint8_t*)&majorVersion, sizeof(OmniPvdVersionType));
mStream->writeBytes((const uint8_t*)&minorVersion, sizeof(OmniPvdVersionType));
mStream->writeBytes((const uint8_t*)&patch, sizeof(OmniPvdVersionType));
mLog.outputLine("OmniPvdRuntimeWriterImpl::setVersion majorVersion(%lu), minorVersion(%lu), patch(%lu)", static_cast<unsigned long>(majorVersion), static_cast<unsigned long>(minorVersion), static_cast<unsigned long>(patch));
mIsFirstWrite = false;
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setWriteStream(OmniPvdWriteStream& stream)
{
mLog.outputLine("OmniPvdRuntimeWriterImpl::setWriteStream");
mStream = &stream;
}
OmniPvdWriteStream* OMNI_PVD_CALL OmniPvdWriterImpl::getWriteStream()
{
return mStream;
}
static void writeCommand(OmniPvdWriteStream& stream, OmniPvdCommand::Enum command)
{
const OmniPvdCommandStorageType commandTmp = static_cast<OmniPvdCommandStorageType>(command);
stream.writeBytes((const uint8_t*)&commandTmp, sizeof(OmniPvdCommandStorageType));
}
OmniPvdClassHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerClass(const char* className, OmniPvdClassHandle baseClass)
{
setVersionHelper();
if (mStream)
{
mLog.outputLine("OmniPvdWriterImpl::registerClass className(%s)", className);
int classNameLen = (int)strlen(className);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_CLASS);
mLastClassHandle++;
mStream->writeBytes((const uint8_t*)&mLastClassHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&baseClass, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&classNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)className, classNameLen);
return mLastClassHandle;
} else {
return 0;
}
}
static void writeDataType(OmniPvdWriteStream& stream, OmniPvdDataType::Enum attributeDataType)
{
const OmniPvdDataTypeStorageType dataType = static_cast<OmniPvdDataTypeStorageType>(attributeDataType);
stream.writeBytes((const uint8_t*)&dataType, sizeof(OmniPvdDataTypeStorageType));
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements)
{
setVersionHelper();
if (mStream) {
mLog.outputLine("OmniPvdWriterImpl::registerAttribute classHandle(%llu), attributeName(%s), attributeDataType(%d), nbrFields(%llu)", static_cast<unsigned long long>(classHandle), attributeName, static_cast<int>(attributeDataType), static_cast<unsigned long long>(nbElements));
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, attributeDataType);
mStream->writeBytes((const uint8_t*)&nbElements, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle)
{
setVersionHelper();
if (mStream) {
mLog.outputLine("OmniPvdWriterImpl::registerFlagsAttribute classHandle(%llu), enumClassHandle(%llu), attributeName(%s)", static_cast<unsigned long long>(classHandle), static_cast<unsigned long long>(enumClassHandle), attributeName);
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, OmniPvdDataType::eFLAGS_WORD);
mStream->writeBytes((const uint8_t*)&enumClassHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value)
{
setVersionHelper();
if (mStream) {
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, OmniPvdDataType::eENUM_VALUE);
mStream->writeBytes((const uint8_t*)&value, sizeof(OmniPvdEnumValueType));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle)
{
setVersionHelper();
if (mStream)
{
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_CLASS_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
mStream->writeBytes((const uint8_t*)&classAttributeHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else {
return 0;
}
}
OmniPvdAttributeHandle OMNI_PVD_CALL OmniPvdWriterImpl::registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType)
{
setVersionHelper();
if (mStream)
{
int attribNameLen = (int)strlen(attributeName);
writeCommand(*mStream, OmniPvdCommand::eREGISTER_UNIQUE_LIST_ATTRIBUTE);
mLastAttributeHandle++;
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&mLastAttributeHandle, sizeof(OmniPvdAttributeHandle));
writeDataType(*mStream, attributeDataType);
mStream->writeBytes((const uint8_t*)&attribNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)attributeName, attribNameLen);
return mLastAttributeHandle;
}
else
{
return 0;
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSET_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eADD_TO_UNIQUE_LIST_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
mStream->writeBytes((const uint8_t*)&nbAttributeHandles, sizeof(uint8_t));
for (int i = 0; i < nbAttributeHandles; i++)
{
mStream->writeBytes((const uint8_t*)attributeHandles, sizeof(OmniPvdAttributeHandle));
attributeHandles++;
}
mStream->writeBytes((const uint8_t*)&nbrBytes, sizeof(uint32_t));
mStream->writeBytes((const uint8_t*)data, nbrBytes);
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eCREATE_OBJECT);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&classHandle, sizeof(OmniPvdClassHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
int objectNameLen = 0;
if (objectName)
{
objectNameLen = (int)strlen(objectName);
mStream->writeBytes((const uint8_t*)&objectNameLen, sizeof(uint16_t));
mStream->writeBytes((const uint8_t*)objectName, objectNameLen);
}
else
{
mStream->writeBytes((const uint8_t*)&objectNameLen, sizeof(uint16_t));
}
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eDESTROY_OBJECT);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&objectHandle, sizeof(OmniPvdObjectHandle));
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSTART_FRAME);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&timeStamp, sizeof(uint64_t));
}
}
void OMNI_PVD_CALL OmniPvdWriterImpl::stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp)
{
setVersionHelper();
if (mStream)
{
writeCommand(*mStream, OmniPvdCommand::eSTOP_FRAME);
mStream->writeBytes((const uint8_t*)&contextHandle, sizeof(OmniPvdContextHandle));
mStream->writeBytes((const uint8_t*)&timeStamp, sizeof(uint64_t));
}
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdReaderImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_RUNTIME_READER_IMPL_H
#define OMNI_PVD_RUNTIME_READER_IMPL_H
#include "OmniPvdReader.h"
#include "OmniPvdLog.h"
class OmniPvdReaderImpl : public OmniPvdReader {
public:
OmniPvdReaderImpl();
~OmniPvdReaderImpl();
void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction);
void OMNI_PVD_CALL setReadStream(OmniPvdReadStream& stream);
bool OMNI_PVD_CALL startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch);
OmniPvdCommand::Enum OMNI_PVD_CALL getNextCommand();
OmniPvdVersionType OMNI_PVD_CALL getMajorVersion();
OmniPvdVersionType OMNI_PVD_CALL getMinorVersion();
OmniPvdVersionType OMNI_PVD_CALL getPatch();
OmniPvdContextHandle OMNI_PVD_CALL getContextHandle();
OmniPvdObjectHandle OMNI_PVD_CALL getObjectHandle();
OmniPvdClassHandle OMNI_PVD_CALL getClassHandle();
OmniPvdClassHandle OMNI_PVD_CALL getBaseClassHandle();
OmniPvdAttributeHandle OMNI_PVD_CALL getAttributeHandle();
const char* OMNI_PVD_CALL getClassName();
const char* OMNI_PVD_CALL getAttributeName();
const char* OMNI_PVD_CALL getObjectName();
const uint8_t* OMNI_PVD_CALL getAttributeDataPointer();
OmniPvdDataType::Enum OMNI_PVD_CALL getAttributeDataType();
uint32_t OMNI_PVD_CALL getAttributeDataLength();
uint32_t OMNI_PVD_CALL getAttributeNumberElements();
OmniPvdClassHandle OMNI_PVD_CALL getAttributeClassHandle();
uint8_t OMNI_PVD_CALL getAttributeNumberHandles();
OmniPvdAttributeHandle* OMNI_PVD_CALL getAttributeHandles();
uint64_t OMNI_PVD_CALL getFrameTimeStart();
uint64_t OMNI_PVD_CALL getFrameTimeStop();
OmniPvdClassHandle OMNI_PVD_CALL getEnumClassHandle();
uint32_t OMNI_PVD_CALL getEnumValue();
// Internal helper
void readLongDataFromStream(uint32_t streamByteLen);
OmniPvdLog mLog;
OmniPvdReadStream *mStream;
OmniPvdVersionType mMajorVersion;
OmniPvdVersionType mMinorVersion;
OmniPvdVersionType mPatch;
OmniPvdVersionType mCmdMajorVersion;
OmniPvdVersionType mCmdMinorVersion;
OmniPvdVersionType mCmdPatch;
OmniPvdContextHandle mCmdContextHandle;
OmniPvdObjectHandle mCmdObjectHandle;
uint32_t mCmdClassHandle;
uint32_t mCmdBaseClassHandle;
uint32_t mCmdAttributeHandle;
////////////////////////////////////////////////////////////////////////////////
// TODO : take care of buffer length limit at read time!
////////////////////////////////////////////////////////////////////////////////
char mCmdClassName[1000];
char mCmdAttributeName[1000];
char mCmdObjectName[1000];
uint16_t mCmdClassNameLen;
uint16_t mCmdAttributeNameLen;
uint16_t mCmdObjectNameLen;
uint8_t* mCmdAttributeDataPtr;
OmniPvdDataType::Enum mCmdAttributeDataType;
uint32_t mCmdAttributeDataLen;
uint32_t mCmdAttributeNbElements;
OmniPvdEnumValueType mCmdEnumValue;
OmniPvdClassHandle mCmdEnumClassHandle;
OmniPvdClassHandle mCmdAttributeClassHandle;
OmniPvdAttributeHandle mCmdAttributeHandleStack[32];
uint8_t mCmdAttributeHandleDepth;
uint64_t mCmdFrameTimeStart;
uint64_t mCmdFrameTimeStop;
uint8_t *mDataBuffer;
uint32_t mDataBuffAllocatedLen;
bool mIsReadingStarted;
uint8_t mReadBaseClassHandle;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/src/OmniPvdFileWriteStreamImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "OmniPvdFileWriteStreamImpl.h"
OmniPvdFileWriteStreamImpl::OmniPvdFileWriteStreamImpl()
{
mFileName = 0;
mFileWasOpened = false;
mPFile = 0;
}
OmniPvdFileWriteStreamImpl::~OmniPvdFileWriteStreamImpl()
{
closeFile();
delete[] mFileName;
mFileName = 0;
}
void OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::setFileName(const char* fileName)
{
if (!fileName) return;
int n = (int)strlen(fileName) + 1;
if (n < 2) return;
delete[] mFileName;
mFileName = new char[n];
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
strcpy_s(mFileName, n, fileName);
#else
strcpy(mFileName, fileName);
#endif
mFileName[n - 1] = 0;
}
bool OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::openFile()
{
if (mFileWasOpened)
{
return true;
}
if (!mFileName)
{
return false;
}
mPFile = 0;
mFileWasOpened = true;
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
errno_t err = fopen_s(&mPFile, mFileName, "wb");
if (err != 0)
{
mFileWasOpened = false;
}
#else
mPFile = fopen(mFileName, "wb");
#endif
return mFileWasOpened;
}
bool OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::closeFile()
{
if (mFileWasOpened)
{
fclose(mPFile);
mFileWasOpened = false;
}
return true;
}
uint64_t OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::writeBytes(const uint8_t *bytes, uint64_t nbrBytes)
{
size_t result = 0;
if (mFileWasOpened)
{
result = fwrite(bytes, 1, nbrBytes, mPFile);
result++;
}
return result;
}
bool OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::flush()
{
return true;
}
bool OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::openStream()
{
return openFile();
}
bool OMNI_PVD_CALL OmniPvdFileWriteStreamImpl::closeStream()
{
return closeFile();
}
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/PVDRuntime.cmake | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#
# Build Server Test template
#
# Include here after the directories are defined so that the platform specific file can use the variables.
include(${PHYSX_ROOT_DIR}/pvdruntime/${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/PVDRuntime.cmake)
SET(PVDRUNTIME_HEADERS
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdLibraryFunctions.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdCommands.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdDefines.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdReader.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdWriter.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdReadStream.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdWriteStream.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdFileReadStream.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdFileWriteStream.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdMemoryStream.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdLibraryHelpers.h
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdLoader.h
)
SOURCE_GROUP(include FILES ${PVDRUNTIME_HEADERS})
SET(PVDRUNTIME_HEADERS_USER
${PHYSX_ROOT_DIR}/pvdruntime/include/OmniPvdLoader.h
)
INSTALL(FILES ${PVDRUNTIME_HEADERS} ${PVDRUNTIME_HEADERS_USER} DESTINATION pvdruntime/include)
SET(PVDRUNTIME_SOURCES
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdDefinesInternal.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdHelpers.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdHelpers.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdLibraryFunctionsImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdLog.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdLog.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdReaderImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdReaderImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdWriterImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdWriterImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdFileReadStreamImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdFileReadStreamImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdFileWriteStreamImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdFileWriteStreamImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryStreamImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryStreamImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryReadStreamImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryReadStreamImpl.cpp
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryWriteStreamImpl.h
${PHYSX_ROOT_DIR}/pvdruntime/src/OmniPvdMemoryWriteStreamImpl.cpp
)
SOURCE_GROUP(src FILES ${PVDRUNTIME_SOURCES})
add_library(PVDRuntime SHARED
${PVDRUNTIME_HEADERS}
${PVDRUNTIME_SOURCES}
)
TARGET_INCLUDE_DIRECTORIES(PVDRuntime
PRIVATE ${PHYSX_ROOT_DIR}/pvdruntime/include
PRIVATE ${PHYSX_ROOT_DIR}/pvdruntime/src
)
TARGET_COMPILE_DEFINITIONS(PVDRuntime
PRIVATE ${PVDRUNTME_COMPILE_DEFS}
)
SET_TARGET_PROPERTIES(PVDRuntime PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PX_EXE_OUTPUT_DIRECTORY_DEBUG}
RUNTIME_OUTPUT_DIRECTORY_PROFILE ${PX_EXE_OUTPUT_DIRECTORY_PROFILE}
RUNTIME_OUTPUT_DIRECTORY_CHECKED ${PX_EXE_OUTPUT_DIRECTORY_CHECKED}
RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PX_EXE_OUTPUT_DIRECTORY_RELEASE}
OUTPUT_NAME PVDRuntime
)
TARGET_LINK_LIBRARIES(PVDRuntime
PUBLIC ${PVDRUNTIME_PLATFORM_LINKED_LIBS})
IF(PX_GENERATE_SOURCE_DISTRO)
LIST(APPEND SOURCE_DISTRO_FILE_LIST ${PVDRUNTIME_HEADERS})
LIST(APPEND SOURCE_DISTRO_FILE_LIST ${PVDRUNTIME_SOURCES})
ENDIF() |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/CMakeLists.txt | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
cmake_minimum_required(VERSION 3.7)
project(PVDRuntime C CXX)
set(PVDRuntimeBuilt 1 CACHE INTERNAL "PVDRuntimeBuilt")
# This is required to be defined by external callers!
IF(NOT DEFINED PHYSX_ROOT_DIR)
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable wasn't set.")
ENDIF()
IF(NOT EXISTS ${PHYSX_ROOT_DIR})
MESSAGE(FATAL_ERROR "PHYSX_ROOT_DIR variable was invalid.")
ENDIF()
INCLUDE(NvidiaBuildOptions)
IF(CMAKE_CONFIGURATION_TYPES)
SET(CMAKE_CONFIGURATION_TYPES debug checked profile release)
SET(CMAKE_CONFIGURATION_TYPES "${CMAKE_CONFIGURATION_TYPES}" CACHE STRING
"Reset config to what we need"
FORCE)
# Need to define these at least once.
SET(CMAKE_EXE_LINKER_FLAGS_CHECKED "")
SET(CMAKE_EXE_LINKER_FLAGS_PROFILE "")
SET(CMAKE_SHARED_LINKER_FLAGS_CHECKED "")
SET(CMAKE_SHARED_LINKER_FLAGS_PROFILE "")
# Build PDBs for all configurations
SET(CMAKE_EXE_LINKER_FLAGS "/DEBUG")
SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
ENDIF()
SET(PROJECT_CMAKE_FILES_DIR compiler/cmake)
SET(PLATFORM_CMAKELISTS ${PHYSX_ROOT_DIR}/pvdruntime/${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/CMakeLists.txt)
IF(NOT EXISTS ${PLATFORM_CMAKELISTS})
MESSAGE(FATAL_ERROR "Unable to find platform CMakeLists.txt for ${TARGET_BUILD_PLATFORM} at ${PLATFORM_CMAKELISTS}")
ENDIF()
# Include the platform specific CMakeLists
INCLUDE(${PHYSX_ROOT_DIR}/pvdruntime/${PROJECT_CMAKE_FILES_DIR}/${TARGET_BUILD_PLATFORM}/CMakeLists.txt)
# Set folder Server to all Server projects
SET_PROPERTY(TARGET PVDRuntime PROPERTY FOLDER "PVDRuntime")
INSTALL(
TARGETS PVDRuntime
EXPORT PhysXSDK
DESTINATION $<$<CONFIG:debug>:${PX_ROOT_LIB_DIR}/debug>$<$<CONFIG:release>:${PX_ROOT_LIB_DIR}/release>$<$<CONFIG:checked>:${PX_ROOT_LIB_DIR}/checked>$<$<CONFIG:profile>:${PX_ROOT_LIB_DIR}/profile>
)
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/windows/PVDRuntime.cmake | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#
# Build ServerTest template
#
#IF(PX_CLOUD_GENERATE_STATIC_LIBRARIES)
# SET(GRIDSERVER_CLOUD_LIBTYPE CLOUD_STATIC_LIB)
#ENDIF()
SET(PVDRUNTIME_COMPILE_DEFS
# Common to all configurations
WIN32;WIN64;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;_WINSOCK_DEPRECATED_NO_WARNINGS;${PHYSX_LIBTYPE_DEFS};
$<$<CONFIG:debug>:${PHYSX_WINDOWS_DEBUG_COMPILE_DEFS};>
$<$<CONFIG:checked>:${PHYSX_WINDOWS_CHECKED_COMPILE_DEFS};>
$<$<CONFIG:profile>:${PHYSX_WINDOWS_PROFILE_COMPILE_DEFS};>
$<$<CONFIG:release>:${PHYSX_WINDOWS_RELEASE_COMPILE_DEFS};>
)
SET(PVDRUNTIME_PLATFORM_LINKED_LIBS
)
INSTALL(FILES $<TARGET_PDB_FILE:PVDRuntime>
DESTINATION $<$<CONFIG:debug>:${PX_ROOT_LIB_DIR}/debug>$<$<CONFIG:release>:${PX_ROOT_LIB_DIR}/release>$<$<CONFIG:checked>:${PX_ROOT_LIB_DIR}/checked>$<$<CONFIG:profile>:${PX_ROOT_LIB_DIR}/profile> OPTIONAL) |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/windows/CMakeLists.txt | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
IF(NOT DEFINED PHYSX_WINDOWS_COMPILE_DEFS)
MESSAGE(FATAL ERROR "Cloud uses the PhysX compile defs, and they're not defined when they need to be.")
ENDIF()
IF (NOT DEFINED PHYSX_CXX_FLAGS)
MESSAGE(FATAL ERROR "Cloud uses the PhysX CXX flags, and they're not defined when they need to be.")
ENDIF()
# Get the CXX Flags from the Cached variables set by the PhysX CMakeLists
SET(CMAKE_CXX_FLAGS "${PHYSX_CXX_FLAGS} /wd4514 /wd4820 /wd4127 /wd4710 /wd4711 /wd4577 /EHsc")
SET(CMAKE_CXX_FLAGS_DEBUG "${PHYSX_CXX_FLAGS_DEBUG}")
SET(CMAKE_CXX_FLAGS_CHECKED "${PHYSX_CXX_FLAGS_CHECKED}")
SET(CMAKE_CXX_FLAGS_PROFILE "${PHYSX_CXX_FLAGS_PROFILE}")
SET(CMAKE_CXX_FLAGS_RELEASE "${PHYSX_CXX_FLAGS_RELEASE}")
# Build PDBs for all configurations
SET(CMAKE_SHARED_LINKER_FLAGS "/DEBUG")
# Include all of the projects
INCLUDE(PVDRuntime.cmake)
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/linux/PVDRuntime.cmake | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#
# Build ServerTest template
#
SET(PVDRUNTIME_COMPILE_DEFS
# Common to all configurations
${PHYSX_LINUX_COMPILE_DEFS};${PHYSX_LIBTYPE_DEFS};
$<$<CONFIG:debug>:${PHYSX_LINUX_DEBUG_COMPILE_DEFS};>
$<$<CONFIG:checked>:${PHYSX_LINUX_CHECKED_COMPILE_DEFS};>
$<$<CONFIG:profile>:${PHYSX_LINUX_PROFILE_COMPILE_DEFS};>
$<$<CONFIG:release>:${PHYSX_LINUX_RELEASE_COMPILE_DEFS};>
)
SET(PVDRUNTIME_PLATFORM_LINKED_LIBS
)
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/compiler/cmake/linux/CMakeLists.txt | ## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in the
## documentation and/or other materials provided with the distribution.
## * Neither the name of NVIDIA CORPORATION nor the names of its
## contributors may be used to endorse or promote products derived
## from this software without specific prior written permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
## PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
## OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
IF(NOT DEFINED PHYSX_LINUX_COMPILE_DEFS)
MESSAGE(FATAL ERROR "Cloud uses the PhysX compile defs, and they're not defined when they need to be.")
ENDIF()
IF (NOT DEFINED PHYSX_CXX_FLAGS)
MESSAGE(FATAL ERROR "Cloud uses the PhysX CXX flags, and they're not defined when they need to be.")
ENDIF()
# Get the CXX Flags from the Cached variables set by the PhysX CMakeLists
# Include all of the projects
INCLUDE(PVDRuntime.cmake)
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdFileWriteStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_FILE_WRITE_STREAM_H
#define OMNI_PVD_FILE_WRITE_STREAM_H
#include "OmniPvdWriteStream.h"
/**
* @brief Used to abstract a file write stream
*
* Used to set the filename, opening and closing it.
*/
class OmniPvdFileWriteStream : public OmniPvdWriteStream
{
public:
virtual ~OmniPvdFileWriteStream()
{
}
/**
* @brief Sets the file name of the file to write to
*
* @param fileName The file name of the file to open
*/
virtual void OMNI_PVD_CALL setFileName(const char* fileName) = 0;
/**
* @brief Opens the file
*
* @return True if the file opening was successfull
*/
virtual bool OMNI_PVD_CALL openFile() = 0;
/**
* @brief Closes the file
*
* @return True if the file closing was successfull
*/
virtual bool OMNI_PVD_CALL closeFile() = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdCommands.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_COMMANDS_H
#define OMNI_PVD_COMMANDS_H
struct OmniPvdCommand
{
enum Enum
{
eINVALID,
eREGISTER_CLASS,
eREGISTER_ENUM,
eREGISTER_ATTRIBUTE,
eREGISTER_CLASS_ATTRIBUTE,
eREGISTER_UNIQUE_LIST_ATTRIBUTE,
eSET_ATTRIBUTE,
eADD_TO_UNIQUE_LIST_ATTRIBUTE,
eREMOVE_FROM_UNIQUE_LIST_ATTRIBUTE,
eCREATE_OBJECT,
eDESTROY_OBJECT,
eSTART_FRAME,
eSTOP_FRAME
};
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdLoader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#ifndef OMNI_PVD_LOADER_H
#define OMNI_PVD_LOADER_H
#include "OmniPvdWriter.h"
#include "OmniPvdReader.h"
#include "OmniPvdLibraryFunctions.h"
#include <stdio.h>
#ifdef OMNI_PVD_WIN
#ifndef _WINDOWS_ // windows already included otherwise
#include <foundation/windows/PxWindowsInclude.h>
#endif
#elif defined(__linux__)
#include <dlfcn.h>
#endif
class OmniPvdLoader
{
public:
OmniPvdLoader();
~OmniPvdLoader();
bool loadOmniPvd(const char *libFile);
void unloadOmniPvd();
void* mLibraryHandle;
createOmniPvdWriterFp mCreateOmniPvdWriter;
destroyOmniPvdWriterFp mDestroyOmniPvdWriter;
createOmniPvdReaderFp mCreateOmniPvdReader;
destroyOmniPvdReaderFp mDestroyOmniPvdReader;
createOmniPvdFileReadStreamFp mCreateOmniPvdFileReadStream;
destroyOmniPvdFileReadStreamFp mDestroyOmniPvdFileReadStream;
createOmniPvdFileWriteStreamFp mCreateOmniPvdFileWriteStream;
destroyOmniPvdFileWriteStreamFp mDestroyOmniPvdFileWriteStream;
createOmniPvdMemoryStreamFp mCreateOmniPvdMemoryStream;
destroyOmniPvdMemoryStreamFp mDestroyOmniPvdMemoryStream;
};
inline OmniPvdLoader::OmniPvdLoader()
{
mLibraryHandle = 0;
mCreateOmniPvdWriter = 0;
mDestroyOmniPvdWriter = 0;
mCreateOmniPvdReader = 0;
mDestroyOmniPvdReader = 0;
mCreateOmniPvdFileReadStream = 0;
mDestroyOmniPvdFileReadStream = 0;
mCreateOmniPvdFileWriteStream = 0;
mDestroyOmniPvdFileWriteStream = 0;
mCreateOmniPvdMemoryStream = 0;
mDestroyOmniPvdMemoryStream = 0;
}
inline OmniPvdLoader::~OmniPvdLoader()
{
unloadOmniPvd();
}
inline bool OmniPvdLoader::loadOmniPvd(const char *libFile)
{
#ifdef OMNI_PVD_WIN
mLibraryHandle = LoadLibraryA(libFile);
#elif defined(__linux__)
mLibraryHandle = dlopen(libFile, RTLD_NOW);
#endif
if (mLibraryHandle)
{
#ifdef OMNI_PVD_WIN
mCreateOmniPvdWriter = (createOmniPvdWriterFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdWriter");
mDestroyOmniPvdWriter = (destroyOmniPvdWriterFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdWriter");
mCreateOmniPvdReader = (createOmniPvdReaderFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdReader");
mDestroyOmniPvdReader = (destroyOmniPvdReaderFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdReader");
mCreateOmniPvdFileReadStream = (createOmniPvdFileReadStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdFileReadStream");
mDestroyOmniPvdFileReadStream = (destroyOmniPvdFileReadStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdFileReadStream");
mCreateOmniPvdFileWriteStream = (createOmniPvdFileWriteStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdFileWriteStream");
mDestroyOmniPvdFileWriteStream = (destroyOmniPvdFileWriteStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdFileWriteStream");
mCreateOmniPvdMemoryStream = (createOmniPvdMemoryStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "createOmniPvdMemoryStream");
mDestroyOmniPvdMemoryStream = (destroyOmniPvdMemoryStreamFp)GetProcAddress((HINSTANCE)mLibraryHandle, "destroyOmniPvdMemoryStream");
#elif defined(__linux__)
mCreateOmniPvdWriter = (createOmniPvdWriterFp)dlsym(mLibraryHandle, "createOmniPvdWriter");
mDestroyOmniPvdWriter = (destroyOmniPvdWriterFp)dlsym(mLibraryHandle, "destroyOmniPvdWriter");
mCreateOmniPvdReader = (createOmniPvdReaderFp)dlsym(mLibraryHandle, "createOmniPvdReader");
mDestroyOmniPvdReader = (destroyOmniPvdReaderFp)dlsym(mLibraryHandle, "destroyOmniPvdReader");
mCreateOmniPvdFileReadStream = (createOmniPvdFileReadStreamFp)dlsym(mLibraryHandle, "createOmniPvdFileReadStream");
mDestroyOmniPvdFileReadStream = (destroyOmniPvdFileReadStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdFileReadStream");
mCreateOmniPvdFileWriteStream = (createOmniPvdFileWriteStreamFp)dlsym(mLibraryHandle, "createOmniPvdFileWriteStream");
mDestroyOmniPvdFileWriteStream = (destroyOmniPvdFileWriteStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdFileWriteStream");
mCreateOmniPvdMemoryStream = (createOmniPvdMemoryStreamFp)dlsym(mLibraryHandle, "createOmniPvdMemoryStream");
mDestroyOmniPvdMemoryStream = (destroyOmniPvdMemoryStreamFp)dlsym(mLibraryHandle, "destroyOmniPvdMemoryStream");
#endif
if ((!mCreateOmniPvdWriter) ||
(!mDestroyOmniPvdWriter) ||
(!mCreateOmniPvdReader) ||
(!mDestroyOmniPvdReader) ||
(!mCreateOmniPvdFileReadStream) ||
(!mDestroyOmniPvdFileReadStream) ||
(!mCreateOmniPvdFileWriteStream) ||
(!mDestroyOmniPvdFileWriteStream) ||
(!mCreateOmniPvdMemoryStream) ||
(!mDestroyOmniPvdMemoryStream)
)
{
#ifdef OMNI_PVD_WIN
FreeLibrary((HINSTANCE)mLibraryHandle);
#elif defined(__linux__)
dlclose(mLibraryHandle);
#endif
mLibraryHandle = 0;
return false;
}
}
else {
return false;
}
return true;
}
inline void OmniPvdLoader::unloadOmniPvd()
{
if (mLibraryHandle)
{
#ifdef OMNI_PVD_WIN
FreeLibrary((HINSTANCE)mLibraryHandle);
#elif defined(__linux__)
dlclose(mLibraryHandle);
#endif
mLibraryHandle = 0;
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdReader.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_READER_H
#define OMNI_PVD_READER_H
#include "OmniPvdDefines.h"
#include "OmniPvdCommands.h"
#include "OmniPvdReadStream.h"
/**
* @brief Used to read debug information from an OmniPvdReadStream
*
* Using the getNextCommand function in a while loop for example one can traverse the stream one command after another. Given the command, different functions below will be available.
*
* Using the OmniPvdCommand::Enum one can determine the type of command and like that use the appropriate get functions to extract the payload from the command.
*/
class OmniPvdReader
{
public:
virtual ~OmniPvdReader()
{
}
/**
* @brief Sets the log function to print the internal debug messages of the OmniPVD Reader instance
*
* @param logFunction The function pointer to receive the log messages
*/
virtual void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction) = 0;
/**
* @brief Sets the read stream that contains the OmniPVD API command stream
*
* @param stream The OmniPvdReadStream that holds the stream of API calls/notifications
*/
virtual void OMNI_PVD_CALL setReadStream(OmniPvdReadStream& stream) = 0;
/**
* @brief Extracts the versions from the binary file to read and tests if the file is older or equal to that of the reader.
*
* @param majorVersion The major versions of the stream
* @param minorVersion The minor versions of the stream
* @param patch The patch number of the stream
* @return If the reading was possible to start or not
*/
virtual bool OMNI_PVD_CALL startReading(OmniPvdVersionType& majorVersion, OmniPvdVersionType& minorVersion, OmniPvdVersionType& patch) = 0;
/**
* @brief The heartbeat function of the reader class. As long as the command that is returned is not equal to OmniPvdCommand::eINVALID, then one can safely extract the data fields from the command.
*
* @return The command enum type
*/
virtual OmniPvdCommand::Enum OMNI_PVD_CALL getNextCommand() = 0;
/**
* @brief Returns the major version of the stream
*
* @return The major version
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getMajorVersion() = 0;
/**
* @brief Returns the minor version of the stream
*
* @return The minor version
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getMinorVersion() = 0;
/**
* @brief Returns the patch number of the stream
*
* @return The patch value
*/
virtual OmniPvdVersionType OMNI_PVD_CALL getPatch() = 0;
/**
* @brief Returns the context handle of the latest commmnd, if it had one, else 0
*
* @return The context handle of the latest command
*/
virtual OmniPvdContextHandle OMNI_PVD_CALL getContextHandle() = 0;
/**
* @brief Returns the object handle of the latest commmnd, if it had one, else 0
*
* @return The object handle of the latest command
*/
virtual OmniPvdObjectHandle OMNI_PVD_CALL getObjectHandle() = 0;
/**
* @brief Returns the class handle of the latest commmnd, if it had one, else 0
*
* @return The class handle of the latest command
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getClassHandle() = 0;
/**
* @brief Returns the base class handle of the latest commmnd, if it had one, else 0
*
* @return The base class handle of the latest command
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getBaseClassHandle() = 0;
/**
* @brief Returns the attribute handle of the latest commmnd, if it had one, else 0
*
* @return The attribute handle of the latest command
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL getAttributeHandle() = 0;
/**
* @brief Returns the class name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the class name
*/
virtual const char* OMNI_PVD_CALL getClassName() = 0;
/**
* @brief Returns the attribute name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the attribute name
*/
virtual const char* OMNI_PVD_CALL getAttributeName() = 0;
/**
* @brief Returns the object name of the latest commmnd, if it had one, else a null terminated string of length 0
*
* @return The string containing the object name
*/
virtual const char* OMNI_PVD_CALL getObjectName() = 0;
/**
* @brief Returns the attribute data pointer, the data is undefined if the last command did not contain attribute data
*
* @return The array containing the attribute data
*/
virtual const uint8_t* OMNI_PVD_CALL getAttributeDataPointer() = 0;
/**
* @brief Returns the attribute data type, the data is undefined if the last command did not contain attribute data
*
* @return The attribute data type
*/
virtual OmniPvdDataType::Enum OMNI_PVD_CALL getAttributeDataType() = 0;
/**
* @brief Returns the attribute data length, the data length of the last command
*
* @return The attribute data length
*/
virtual uint32_t OMNI_PVD_CALL getAttributeDataLength() = 0;
/**
* @brief Returns the number of elements contained in the last set operation
*
* @return The number of elements
*/
virtual uint32_t OMNI_PVD_CALL getAttributeNumberElements() = 0;
/**
* @brief Returns the numberclass handle of the attribute class
*
* @return The attibute class handle
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getAttributeClassHandle() = 0;
/**
* @brief Returns the frame start value
*
* @return The frame ID value
*/
virtual uint64_t OMNI_PVD_CALL getFrameTimeStart() = 0;
/**
* @brief Returns the frame stop value
*
* @return The frame ID value
*/
virtual uint64_t OMNI_PVD_CALL getFrameTimeStop() = 0;
/**
* @brief Returns the class handle containing the enum values
*
* @return The enum class handle
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL getEnumClassHandle() = 0;
/**
* @brief Returns the enum value for a specific flag
*
* @return The enum value
*/
virtual OmniPvdEnumValueType OMNI_PVD_CALL getEnumValue() = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdLibraryFunctions.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_LIBRARY_FUNCTIONS_H
#define OMNI_PVD_LIBRARY_FUNCTIONS_H
#include "OmniPvdDefines.h"
class OmniPvdReader;
class OmniPvdWriter;
class OmniPvdFileReadStream;
class OmniPvdFileWriteStream;
class OmniPvdMemoryStream;
typedef OmniPvdReader* (OMNI_PVD_CALL *createOmniPvdReaderFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdReaderFp)(OmniPvdReader& reader);
typedef OmniPvdWriter* (OMNI_PVD_CALL *createOmniPvdWriterFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdWriterFp)(OmniPvdWriter& writer);
typedef OmniPvdFileReadStream* (OMNI_PVD_CALL *createOmniPvdFileReadStreamFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdFileReadStreamFp)(OmniPvdFileReadStream& fileReadStream);
typedef OmniPvdFileWriteStream* (OMNI_PVD_CALL *createOmniPvdFileWriteStreamFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdFileWriteStreamFp)(OmniPvdFileWriteStream& fileWriteStream);
typedef OmniPvdMemoryStream* (OMNI_PVD_CALL *createOmniPvdMemoryStreamFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdMemoryStreamFp)(OmniPvdMemoryStream& memoryStream);
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdMemoryStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_MEMORY_STREAM_H
#define OMNI_PVD_MEMORY_STREAM_H
#include "OmniPvdReadStream.h"
#include "OmniPvdWriteStream.h"
/**
* @brief Used to abstract a memory read/write stream
*
* Used to get the read and write streams.
*/
class OmniPvdMemoryStream
{
public:
virtual ~OmniPvdMemoryStream()
{
}
/**
* @brief Used to get the read stream
*
* @return The read stream
*/
virtual OmniPvdReadStream* OMNI_PVD_CALL getReadStream() = 0;
/**
* @brief Used to get the write stream
*
* @return The write stream
*/
virtual OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream() = 0;
/**
* @brief Sets the buffer size in bytes of the memory streams
*
* @return The actually allocated length of the memory stream
*/
virtual uint64_t OMNI_PVD_CALL setBufferSize(uint64_t bufferLength) = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdWriteStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_WRITE_STREAM_H
#define OMNI_PVD_WRITE_STREAM_H
#include "OmniPvdDefines.h"
/**
* @brief Used to abstract a memory write stream
*
* Allows to write bytes as well as open/close the stream.
*/
class OmniPvdWriteStream
{
public:
virtual ~OmniPvdWriteStream()
{
}
/**
* @brief Write n bytes to the shared memory buffer
*
* @param bytes pointer to the bytes to write
* @param nbrBytes The requested number of bytes to write
* @return The actual number of bytes written
*/
virtual uint64_t OMNI_PVD_CALL writeBytes(const uint8_t* bytes, uint64_t nbrBytes) = 0;
/**
* @brief Flushes the writes
*
* @return The success of the operation
*/
virtual bool OMNI_PVD_CALL flush() = 0;
/**
* @brief Opens the stream
*
* @return The success of the operation
*/
virtual bool OMNI_PVD_CALL openStream() = 0;
/**
* @brief Closes the stream
*
* @return The success of the operation
*/
virtual bool OMNI_PVD_CALL closeStream() = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdReadStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_READ_STREAM_H
#define OMNI_PVD_READ_STREAM_H
#include "OmniPvdDefines.h"
/**
* @brief Used to abstract a memory read stream
*
* Allows to read and skip bytes as well as open/close it.
*/
class OmniPvdReadStream
{
public:
virtual ~OmniPvdReadStream()
{
}
/**
* @brief Read n bytes from the shared memory buffer
*
* @param bytes Reads n bytes into the destination pointer
* @param nbrBytes The requested number of bytes to read
* @return The actual number of bytes read
*/
virtual uint64_t OMNI_PVD_CALL readBytes(uint8_t* bytes, uint64_t nbrBytes) = 0;
/**
* @brief Skip n bytes from the shared memory buffer
*
* @param nbrBytes The requested number of bytes to skip
* @return The actual number of bytes skipped
*/
virtual uint64_t OMNI_PVD_CALL skipBytes(uint64_t nbrBytes) = 0;
/**
* @brief Opens the read stream
*
* @return True if it succeeded
*/
virtual bool OMNI_PVD_CALL openStream() = 0;
/**
* @brief Closes the read stream
*
* @return True if it succeeded
*/
virtual bool OMNI_PVD_CALL closeStream() = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdWriter.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_WRITER_H
#define OMNI_PVD_WRITER_H
#include "OmniPvdDefines.h"
#include "OmniPvdWriteStream.h"
/**
* @brief Used to write debug information to an OmniPvdWriteStream
*
* Allows the registration of OmniPVD classes and attributes, in a similar fashion to an object oriented language. A registration returns a unique identifier or handle.
*
* Once classes and attributes have been registered, one can create for example object instances of a class and set the values of the attributes of a specific object.
*
* Objects can be grouped by context using the context handle. The context handle is a user-specified handle which is passed to the set functions and object creation and destruction functions.
*
* Each context can have its own notion of time. The current time of a context can be exported with calls to the startFrame and stopFrame functions.
*/
class OmniPvdWriter
{
public:
virtual ~OmniPvdWriter()
{
}
/**
* @brief Sets the log function to print the internal debug messages of the OmniPVD API
*
* @param logFunction The function pointer to receive the log messages
*/
virtual void OMNI_PVD_CALL setLogFunction(OmniPvdLogFunction logFunction) = 0;
/**
* @brief Sets the write stream to receive the API command stream
*
* @param writeStream The OmniPvdWriteStream to receive the stream of API calls/notifications
*/
virtual void OMNI_PVD_CALL setWriteStream(OmniPvdWriteStream& writeStream) = 0;
/**
* @brief Gets the pointer to the write stream
*
* @return A pointer to the write stream
*/
virtual OmniPvdWriteStream* OMNI_PVD_CALL getWriteStream() = 0;
/**
* @brief Registers an OmniPVD class
*
* Returns a unique handle to a class, which can be used to register class attributes and express object lifetimes with the createObject and destroyObject functions. Class inheritance can be described by calling registerClass with a base class handle. Derived classes inherit the attributes of the parent classes.
*
* @param className The class name
* @param baseClassHandle The handle to the base class. This handle is obtained by pre-registering the base class. Defaults to 0 which means the class has no parent class
* @return A unique class handle for the registered class
*
* @see OmniPvdWriter::registerAttribute()
* @see OmniPvdWriter::registerEnumValue()
* @see OmniPvdWriter::registerFlagsAttribute()
* @see OmniPvdWriter::registerClassAttribute()
* @see OmniPvdWriter::registerUniqueListAttribute()
* @see OmniPvdWriter::createObject()
*/
virtual OmniPvdClassHandle OMNI_PVD_CALL registerClass(const char* className, OmniPvdClassHandle baseClassHandle = 0) = 0;
/**
* @brief Registers an enum name and corresponding value for a pre-registered class.
*
* Registering enums happens in two steps. First, registerClass() is called with the name of the enum. This returns a class handle, which is used in a second step for the enum value registration with registerEnumValue(). If an enum has multiple values, registerEnumValue() has to be called with the different values.
*
* Note that enums differ from usual classes because their attributes, the enum values, do not change over time and there is no need to call setAttribute().
*
* @param classHandle The handle from the registerClass() call
* @param attributeName The name of the enum value
* @param value The value of the enum value
* @return A unique attribute handle for the registered enum value
*
* @see OmniPvdWriter::registerClass()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerEnumValue(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdEnumValueType value) = 0;
/**
* @brief Registers an attribute.
*
* The class handle is obtained from a previous call to registerClass(). After registering an attribute, one gets an attribute handle which can be used to set data values of an attribute with setAttribute(). All attributes are treated as arrays, even if the attribute has only a single data item. Set nbElements to 0 to indicate that the array has a variable length.
*
* @param classHandle The handle from the registerClass() call
* @param attributeName The attribute name
* @param attributeDataType The attribute data type
* @param nbElements The number of elements in the array. Set this to 0 to indicate a variable length array
* @return A unique attribute handle for the registered attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType, uint32_t nbElements) = 0;
/**
* @brief Registers an attribute which is a flag.
*
* Use this function to indicate that a pre-registered class has a flag attribute, i.e., the attribute is a pre-registered enum.
*
* The returned attribute handle can be used in setAttribute() to set an object's flags.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param enumClassHandle The handle from the registerClass() call of the enum
* @return A unique attribute handle for the registered flags attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerFlagsAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle enumClassHandle) = 0;
/**
* @brief Registers an attribute which is a class.
*
* Use this function to indicate that a pre-registered class has an attribute which is a pre-registered class.
*
* The returned attribute handle can be used in setAttribute() to set an object's class attribute.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param classAttributeHandle The handle from the registerClass() call of the class attribute
* @return A unique handle for the registered class attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::setAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerClassAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdClassHandle classAttributeHandle) = 0;
/**
* @brief Registers an attribute which can hold a list of unique items.
*
* The returned attribute handle can be used in calls to addToUniqueListAttribute() and removeFromUniqueListAttribute(), to add an item to and remove it from the list, respectively.
*
* @param classHandle The handle from the registerClass() call of the class
* @param attributeName The attribute name
* @param attributeDataType The data type of the items which will get added to the list attribute
* @return A unique handle for the registered list attribute
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::addToUniqueListAttribute()
* @see OmniPvdWriter::removeFromUniqueListAttribute()
*/
virtual OmniPvdAttributeHandle OMNI_PVD_CALL registerUniqueListAttribute(OmniPvdClassHandle classHandle, const char* attributeName, OmniPvdDataType::Enum attributeDataType) = 0;
/**
* @brief Sets an attribute value.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the element(s) to remove from the set
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerAttribute()
*/
virtual void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t *data, uint32_t nbrBytes) = 0;
/**
* @brief Sets an attribute value.
*
* See other setAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerAttribute() call
* @param data The pointer to the data
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerAttribute()
*/
inline void OMNI_PVD_CALL setAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t *data, uint32_t nbrBytes)
{
setAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Adds an item to a unique list attribute.
*
* A unique list attribute is defined like a set in mathematics, where each element must be unique.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the item to add to the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
virtual void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes) = 0;
/**
* @brief Adds an item to a unique list attribute.
*
* See other addToUniqueListAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerUniqueListAttribute() call
* @param data The pointer to the data of the item to add to the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
inline void OMNI_PVD_CALL addToUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t* data, uint32_t nbrBytes)
{
addToUniqueListAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Removes an item from a uniqe list attribute
*
* A uniqe list attribute is defined like a set in mathematics, where each element must be unique.
*
* Since an attribute can be part of a nested construct of class attributes, the method
* expects an array of attribute handles as input to uniquely identify the attribute.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandles The attribute handles containing all class attribute handles of a nested class
* construct. The last one has to be the handle from the registerUniqueListAttribute() call.
* @param nbAttributeHandles The number of attribute handles provided in attributeHandles
* @param data The pointer to the data of the item to remove from the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
virtual void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, const OmniPvdAttributeHandle* attributeHandles, uint8_t nbAttributeHandles, const uint8_t* data, uint32_t nbrBytes) = 0;
/**
* @brief Removes an item from a uniqe list attribute
*
* See other removeFromUniqueListAttribute method for details. This special version covers the case where the
* attribute is not part of a class attribute construct.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param attributeHandle The handle from the registerUniqueListAttribute() call
* @param data The pointer to the data of the item to remove from the list
* @param nbrBytes The number of bytes to be written
*
* @see OmniPvdWriter::registerUniqueListAttribute()
*/
inline void OMNI_PVD_CALL removeFromUniqueListAttribute(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle, OmniPvdAttributeHandle attributeHandle, const uint8_t* data, uint32_t nbrBytes)
{
removeFromUniqueListAttribute(contextHandle, objectHandle, &attributeHandle, 1, data, nbrBytes);
}
/**
* @brief Creates an object creation event
*
* Indicates that an object is created. One can freely choose a context handle for grouping objects.
*
* The class handle is obtained from a registerClass() call. The object handle should be unique, but as it's not tracked by the OmniPVD API, it's important this is set to a valid handle such as the object's physical memory address.
*
* The object name can be freely choosen or not set.
*
* Create about object destruction event by calling destroyObject().
*
* @param contextHandle The user-defined context handle for grouping objects
* @param classHandle The handle from the registerClass() call
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
* @param objectName The user-defined name of the object. Can be the empty string
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::destroyObject()
*/
virtual void OMNI_PVD_CALL createObject(OmniPvdContextHandle contextHandle, OmniPvdClassHandle classHandle, OmniPvdObjectHandle objectHandle, const char* objectName) = 0;
/**
* @brief Creates an object destruction event
*
* Use this to indicate that an object is destroyed. Use the same user-defined context and object handles as were used in the create object calls.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param objectHandle The user-defined unique handle of the object. E.g. its physical memory address
*
* @see OmniPvdWriter::registerClass()
* @see OmniPvdWriter::createObject()
*/
virtual void OMNI_PVD_CALL destroyObject(OmniPvdContextHandle contextHandle, OmniPvdObjectHandle objectHandle) = 0;
/**
* @brief Creates a frame start event
*
* Time or frames are counted separatly per user-defined context.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param timeStamp The timestamp of the frame start event
*/
virtual void OMNI_PVD_CALL startFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp) = 0;
/**
* @brief Creates a stop frame event
*
* Time is counted separately per user-defined context.
*
* @param contextHandle The user-defined context handle for grouping objects
* @param timeStamp The timestamp of the frame stop event
*/
virtual void OMNI_PVD_CALL stopFrame(OmniPvdContextHandle contextHandle, uint64_t timeStamp) = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdLibraryHelpers.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#ifndef OMNI_PVD_LIBRARY_FUNCTIONS_H
#define OMNI_PVD_LIBRARY_FUNCTIONS_H
#include "OmniPvdDefines.h"
class OmniPvdReader;
class OmniPvdWriter;
typedef OmniPvdReader* (OMNI_PVD_CALL *createOmniPvdReaderFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdReaderFp)(OmniPvdReader *reader);
typedef OmniPvdWriter* (OMNI_PVD_CALL *createOmniPvdWriterFp)();
typedef void (OMNI_PVD_CALL *destroyOmniPvdWriterFp)(OmniPvdWriter *writer);
#endif |
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdFileReadStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_FILE_READ_STREAM_H
#define OMNI_PVD_FILE_READ_STREAM_H
#include "OmniPvdReadStream.h"
/**
* @brief Used to abstract a file read stream
*
* Used to set the filename, opening and closing it.
*/
class OmniPvdFileReadStream : public OmniPvdReadStream
{
public:
virtual ~OmniPvdFileReadStream()
{
}
/**
* @brief Sets the file name of the file to read from
*
* @param fileName The file name of the file to open
*/
virtual void OMNI_PVD_CALL setFileName(const char* fileName) = 0;
/**
* @brief Opens the file
*
* @return True if the file opening was successfull
*/
virtual bool OMNI_PVD_CALL openFile() = 0;
/**
* @brief Closes the file
*
* @return True if the file closing was successfull
*/
virtual bool OMNI_PVD_CALL closeFile() = 0;
};
#endif
|
NVIDIA-Omniverse/PhysX/physx/pvdruntime/include/OmniPvdDefines.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef OMNI_PVD_DEFINES_H
#define OMNI_PVD_DEFINES_H
#define OMNI_PVD_VERSION_MAJOR 0
#define OMNI_PVD_VERSION_MINOR 3
#define OMNI_PVD_VERSION_PATCH 0
////////////////////////////////////////////////////////////////////////////////
// Versions so far : (major, minor, patch), top one is newest
//
// [0, 3, 0]
// writes/read out the base class handle in the class registration call
// backwards compatible with [0, 2, 0] and [0, 1, 42]
// [0, 2, 0]
// intermediate version was never official, no real change, but there are many files with this version
// [0, 1, 42]
// no proper base class written/read in the class registration call
//
////////////////////////////////////////////////////////////////////////////////
#include <stdint.h>
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#define OMNI_PVD_WIN
#define OMNI_PVD_CALL __cdecl
#define OMNI_PVD_EXPORT extern "C" __declspec(dllexport)
#else
#ifdef __cdecl__
#define OMNI_PVD_CALL __attribute__((__cdecl__))
#else
#define OMNI_PVD_CALL
#endif
#if __GNUC__ >= 4
#define OMNI_PVD_EXPORT extern "C" __attribute__((visibility("default")))
#else
#define OMNI_PVD_EXPORT extern "C"
#endif
#endif
typedef uint64_t OmniPvdObjectHandle;
typedef uint64_t OmniPvdContextHandle;
typedef uint32_t OmniPvdClassHandle;
typedef uint32_t OmniPvdAttributeHandle;
typedef uint32_t OmniPvdVersionType;
typedef uint32_t OmniPvdEnumValueType;
typedef void (OMNI_PVD_CALL *OmniPvdLogFunction)(char *logLine);
struct OmniPvdDataType
{
enum Enum
{
eINT8,
eINT16,
eINT32,
eINT64,
eUINT8,
eUINT16,
eUINT32,
eUINT64,
eFLOAT32,
eFLOAT64,
eSTRING,
eOBJECT_HANDLE,
eENUM_VALUE,
eFLAGS_WORD
};
};
template<uint32_t tType>
inline uint32_t getOmniPvdDataTypeSize() { return 0; }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT8>() { return sizeof(int8_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT16>() { return sizeof(int16_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT32>() { return sizeof(int32_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eINT64>() { return sizeof(int64_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT8>() { return sizeof(uint8_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT16>() { return sizeof(uint16_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT32>() { return sizeof(uint32_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eUINT64>() { return sizeof(uint64_t); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT32>() { return sizeof(float); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLOAT64>() { return sizeof(double); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eSTRING>() { return 0; }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eOBJECT_HANDLE>() { return sizeof(OmniPvdObjectHandle); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eENUM_VALUE>() { return sizeof(OmniPvdEnumValueType); }
template<>
inline uint32_t getOmniPvdDataTypeSize<OmniPvdDataType::eFLAGS_WORD>() { return sizeof(OmniPvdClassHandle); }
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physxgpu/include/PxPhysXGpu.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSX_GPU_H
#define PX_PHYSX_GPU_H
#include "task/PxTask.h"
#include "foundation/PxPinnedArray.h"
#include "common/PxPhysXCommonConfig.h"
#include "PxSceneDesc.h"
#include "cudamanager/PxCudaContextManager.h"
#include "PxSparseGridParams.h"
namespace physx
{
class PxFoundation;
class PxCudaContextManagerDesc;
class PxvNphaseImplementationContext;
class PxsContext;
class PxsKernelWranglerManager;
class PxvNphaseImplementationFallback;
struct PxgDynamicsMemoryConfig;
class PxsMemoryManager;
class PxsHeapMemoryAllocatorManager;
class PxsSimulationController;
class PxsSimulationControllerCallback;
class PxDelayLoadHook;
class PxParticleBuffer;
class PxParticleAndDiffuseBuffer;
class PxParticleClothBuffer;
class PxParticleRigidBuffer;
class PxIsosurfaceExtractor;
class PxSparseGridIsosurfaceExtractor;
struct PxIsosurfaceParams;
class PxAnisotropyGenerator;
class PxSmoothedPositionGenerator;
class PxParticleNeighborhoodProvider;
class PxPhysicsGpu;
struct PxvSimStats;
namespace Bp
{
class BroadPhase;
class AABBManagerBase;
class BoundsArray;
}
namespace Dy
{
class Context;
}
namespace IG
{
class IslandSim;
class SimpleIslandManager;
}
namespace Cm
{
class FlushPool;
}
/**
\brief Interface to create and run CUDA enabled PhysX features.
The methods of this interface are expected not to be called concurrently.
Also they are expected to not be called concurrently with any tasks spawned before the end pipeline ... TODO make clear.
*/
class PxPhysXGpu
{
protected:
virtual ~PxPhysXGpu() {}
PxPhysXGpu() {}
public:
/**
\brief Closes this instance of the interface.
*/
virtual void release() = 0;
virtual PxParticleBuffer* createParticleBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxNumParticles, PxU32 maxVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
virtual PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager, PxU64* memStat, void (*onParticleBufferRelease)(PxParticleBuffer* buffer)) = 0;
/**
Create GPU memory manager.
*/
virtual PxsMemoryManager* createGpuMemoryManager(PxCudaContextManager* cudaContextManager) = 0;
virtual PxsHeapMemoryAllocatorManager* createGpuHeapMemoryAllocatorManager(
const PxU32 heapCapacity,
PxsMemoryManager* memoryManager,
const PxU32 gpuComputeVersion) = 0;
/**
Create GPU kernel wrangler manager. If a kernel wrangler manager already exists, then that one will be returned.
The kernel wrangler manager should not be deleted. It will automatically be deleted when the PxPhysXGpu singleton gets released.
*/
virtual PxsKernelWranglerManager* getGpuKernelWranglerManager(
PxCudaContextManager* cudaContextManager) = 0;
/**
Create GPU broadphase.
*/
virtual Bp::BroadPhase* createGpuBroadPhase(
PxsKernelWranglerManager* gpuKernelWrangler,
PxCudaContextManager* cudaContextManager,
const PxU32 gpuComputeVersion,
const PxgDynamicsMemoryConfig& config,
PxsHeapMemoryAllocatorManager* heapMemoryManager, PxU64 contextID) = 0;
/**
Create GPU aabb manager.
*/
virtual Bp::AABBManagerBase* createGpuAABBManager(
PxsKernelWranglerManager* gpuKernelWrangler,
PxCudaContextManager* cudaContextManager,
const PxU32 gpuComputeVersion,
const PxgDynamicsMemoryConfig& config,
PxsHeapMemoryAllocatorManager* heapMemoryManager,
Bp::BroadPhase& bp,
Bp::BoundsArray& boundsArray,
PxFloatArrayPinned& contactDistance,
PxU32 maxNbAggregates, PxU32 maxNbShapes,
PxVirtualAllocator& allocator,
PxU64 contextID,
PxPairFilteringMode::Enum kineKineFilteringMode,
PxPairFilteringMode::Enum staticKineFilteringMode) = 0;
/**
Create GPU narrow phase context.
*/
virtual PxvNphaseImplementationContext* createGpuNphaseImplementationContext(PxsContext& context,
PxsKernelWranglerManager* gpuKernelWrangler,
PxvNphaseImplementationFallback* fallbackForUnsupportedCMs,
const PxgDynamicsMemoryConfig& gpuDynamicsConfig, void* contactStreamBase, void* patchStreamBase, void* forceAndIndiceStreamBase,
PxBoundsArrayPinned& bounds, IG::IslandSim* islandSim,
physx::Dy::Context* dynamicsContext, const PxU32 gpuComputeVersion, PxsHeapMemoryAllocatorManager* heapMemoryManager,
bool useGpuBP) = 0;
/**
Create GPU simulation controller.
*/
virtual PxsSimulationController* createGpuSimulationController(PxsKernelWranglerManager* gpuWranglerManagers,
PxCudaContextManager* cudaContextManager,
Dy::Context* dynamicContext, PxvNphaseImplementationContext* npContext, Bp::BroadPhase* bp,
const bool useGpuBroadphase, IG::SimpleIslandManager* simpleIslandSim,
PxsSimulationControllerCallback* callback, const PxU32 gpuComputeVersion, PxsHeapMemoryAllocatorManager* heapMemoryManager,
const PxU32 maxSoftBodyContacts, const PxU32 maxFemClothContacts, const PxU32 maxParticleContacts, const PxU32 maxHairContacts) = 0;
/**
Create GPU dynamics context.
*/
virtual Dy::Context* createGpuDynamicsContext(Cm::FlushPool& taskPool, PxsKernelWranglerManager* gpuKernelWragler,
PxCudaContextManager* cudaContextManager,
const PxgDynamicsMemoryConfig& config, IG::SimpleIslandManager* islandManager, const PxU32 maxNumPartitions, const PxU32 maxNumStaticPartitions,
const bool enableStabilization, const bool useEnhancedDeterminism, const PxReal maxBiasCoefficient,
const PxU32 gpuComputeVersion, PxvSimStats& simStats, PxsHeapMemoryAllocatorManager* heapMemoryManager,
const bool frictionEveryIteration, PxSolverType::Enum solverType, const PxReal lengthScale, bool enableDirectGPUAPI) = 0;
};
}
/**
Create PxPhysXGpu interface class.
*/
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxPhysXGpu* PX_CALL_CONV PxCreatePhysXGpu();
/**
Create a cuda context manager. Set launchSynchronous to true for Cuda to report the actual point of failure.
*/
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxCudaContextManager* PX_CALL_CONV PxCreateCudaContextManager(physx::PxFoundation& foundation, const physx::PxCudaContextManagerDesc& desc, physx::PxProfilerCallback* profilerCallback = NULL, bool launchSynchronous = false);
/**
Set profiler callback.
*/
PX_C_EXPORT PX_PHYSX_GPU_API void PX_CALL_CONV PxSetPhysXGpuProfilerCallback(physx::PxProfilerCallback* profilerCallback);
/**
Query the device ordinal - depends on control panel settings.
*/
PX_C_EXPORT PX_PHYSX_GPU_API int PX_CALL_CONV PxGetSuggestedCudaDeviceOrdinal(physx::PxErrorCallback& errc);
// Implementation of the corresponding functions from PxGpu.h/cpp in the GPU shared library
PX_C_EXPORT PX_PHYSX_GPU_API void PX_CALL_CONV PxGpuCudaRegisterFunction(int moduleIndex, const char* functionName);
PX_C_EXPORT PX_PHYSX_GPU_API void** PX_CALL_CONV PxGpuCudaRegisterFatBinary(void* fatBin);
#if PX_SUPPORT_GPU_PHYSX
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxKernelIndex* PX_CALL_CONV PxGpuGetCudaFunctionTable();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxU32 PX_CALL_CONV PxGpuGetCudaFunctionTableSize();
PX_C_EXPORT PX_PHYSX_GPU_API void** PX_CALL_CONV PxGpuGetCudaModuleTable();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxU32 PX_CALL_CONV PxGpuGetCudaModuleTableSize();
PX_C_EXPORT PX_PHYSX_GPU_API physx::PxPhysicsGpu* PX_CALL_CONV PxGpuCreatePhysicsGpu();
#endif
#endif // PX_PHYSX_GPU_H
|
NVIDIA-Omniverse/PhysX/physx/source/immediatemode/src/NpImmediateMode.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "PxImmediateMode.h"
#include "PxBroadPhase.h"
#include "../../lowleveldynamics/src/DyBodyCoreIntegrator.h"
#include "../../lowleveldynamics/src/DyContactPrep.h"
#include "../../lowleveldynamics/src/DyCorrelationBuffer.h"
#include "../../lowleveldynamics/src/DyConstraintPrep.h"
#include "../../lowleveldynamics/src/DySolverControl.h"
#include "../../lowleveldynamics/src/DySolverContext.h"
#include "../../lowlevel/common/include/collision/PxcContactMethodImpl.h"
#include "../../lowleveldynamics/src/DyTGSContactPrep.h"
#include "../../lowleveldynamics/src/DyTGS.h"
#include "../../lowleveldynamics/src/DyConstraintPartition.h"
#include "../../lowleveldynamics/src/DyArticulationCpuGpu.h"
#include "GuPersistentContactManifold.h"
#include "NpConstraint.h"
#include "common/PxProfileZone.h"
// PT: just for Dy::DY_ARTICULATION_MAX_SIZE
#include "../../lowleveldynamics/include/DyFeatherstoneArticulation.h"
#include "../../lowlevel/common/include/utils/PxcScratchAllocator.h"
using namespace physx;
using namespace Dy;
using namespace immediate;
void immediate::PxConstructSolverBodies(const PxRigidBodyData* inRigidData, PxSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity, PxReal dt, bool gyroscopicForces)
{
PX_ASSERT((size_t(inRigidData) & 0xf) == 0);
PX_ASSERT((size_t(outSolverBodyData) & 0xf) == 0);
for(PxU32 a=0; a<nbBodies; a++)
{
const PxRigidBodyData& rigidData = inRigidData[a];
PxVec3 lv = rigidData.linearVelocity, av = rigidData.angularVelocity;
Dy::bodyCoreComputeUnconstrainedVelocity(gravity, dt, rigidData.linearDamping, rigidData.angularDamping, 1.0f, rigidData.maxLinearVelocitySq, rigidData.maxAngularVelocitySq, lv, av, false);
Dy::copyToSolverBodyData(lv, av, rigidData.invMass, rigidData.invInertia, rigidData.body2World, -rigidData.maxDepenetrationVelocity, rigidData.maxContactImpulse,
PX_INVALID_NODE, PX_MAX_F32, outSolverBodyData[a], 0, dt, gyroscopicForces);
}
}
void immediate::PxConstructStaticSolverBody(const PxTransform& globalPose, PxSolverBodyData& solverBodyData)
{
PX_ASSERT((size_t(&solverBodyData) & 0xf) == 0);
const PxVec3 zero(0.0f);
Dy::copyToSolverBodyData(zero, zero, 0.0f, zero, globalPose, -PX_MAX_F32, PX_MAX_F32, PX_INVALID_NODE, PX_MAX_F32, solverBodyData, 0, 0.0f, false);
}
void immediate::PxIntegrateSolverBodies(PxSolverBodyData* solverBodyData, PxSolverBody* solverBody, const PxVec3* linearMotionVelocity, const PxVec3* angularMotionState, PxU32 nbBodiesToIntegrate, PxReal dt)
{
PX_ASSERT((size_t(solverBodyData) & 0xf) == 0);
PX_ASSERT((size_t(solverBody) & 0xf) == 0);
for(PxU32 i=0; i<nbBodiesToIntegrate; ++i)
{
PxVec3 lmv = linearMotionVelocity[i];
PxVec3 amv = angularMotionState[i];
Dy::integrateCore(lmv, amv, solverBody[i], solverBodyData[i], dt, 0);
}
}
namespace
{
// PT: local structure to provide a ctor for the PxArray below, I don't want to make it visible to the regular PhysX code
struct immArticulationJointCore : Dy::ArticulationJointCore
{
immArticulationJointCore() : Dy::ArticulationJointCore(PxTransform(PxIdentity), PxTransform(PxIdentity))
{
}
};
// PT: this class makes it possible to call the FeatherstoneArticulation protected functions from here.
class immArticulation : public FeatherstoneArticulation
{
public:
immArticulation(const PxArticulationDataRC& data);
~immArticulation();
PX_FORCE_INLINE void immSolveInternalConstraints(PxReal dt, PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, PxReal elapsedTime, bool velocityIteration, bool isTGS)
{
// PT: TODO: revisit the TGS coeff (PX-4516)
FeatherstoneArticulation::solveInternalConstraints(dt, invDt, impulses, DeltaV, velocityIteration, isTGS, elapsedTime, isTGS ? 0.7f : DY_ARTICULATION_PGS_BIAS_COEFFICIENT);
}
PX_FORCE_INLINE void immComputeUnconstrainedVelocitiesTGS(PxReal dt, PxReal totalDt, PxReal invDt, PxReal /*invTotalDt*/, const PxVec3& gravity, PxReal invLengthScale)
{
mArticulationData.setDt(totalDt);
Cm::SpatialVectorF* Z = mTempZ.begin();
Cm::SpatialVectorF* deltaV = mTempDeltaV.begin();
FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale);
setupInternalConstraints(mArticulationData.getLinks(), mArticulationData.getLinkCount(),
mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE, mArticulationData, Z, dt, totalDt, invDt, true);
}
PX_FORCE_INLINE void immComputeUnconstrainedVelocities(PxReal dt, const PxVec3& gravity, PxReal invLengthScale)
{
mArticulationData.setDt(dt);
Cm::SpatialVectorF* Z = mTempZ.begin();
Cm::SpatialVectorF* deltaV = mTempDeltaV.begin();
FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale);
const PxReal invDt = 1.0f/dt;
setupInternalConstraints(mArticulationData.getLinks(), mArticulationData.getLinkCount(),
mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE, mArticulationData, Z, dt, dt, invDt, false);
}
void allocate(const PxU32 nbLinks);
PxU32 addLink(const PxU32 parent, const PxArticulationLinkDataRC& data);
void complete();
PxArray<Dy::ArticulationLink> mLinks;
PxArray<PxsBodyCore> mBodyCores;
PxArray<immArticulationJointCore> mArticulationJointCores;
PxArticulationFlags mFlags; // PT: PX-1399. Stored in Dy::ArticulationCore for retained mode.
// PT: quick and dirty version, to improve later
struct immArticulationLinkDataRC : PxArticulationLinkDataRC
{
PxArticulationLinkCookie parent;
PxU32 userID;
};
PxArray<immArticulationLinkDataRC> mTemp;
PxArray<Cm::SpatialVectorF> mTempDeltaV;
PxArray<Cm::SpatialVectorF> mTempZ;
bool mImmDirty;
bool mJCalcDirty;
private:
void initJointCore(Dy::ArticulationJointCore& core, const PxArticulationJointDataRC& inboundJoint);
};
class RigidBodyClassification : public RigidBodyClassificationBase
{
public:
RigidBodyClassification(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) : RigidBodyClassificationBase(bodies, bodyCount, bodyStride)
{
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxU32* numConstraintsPerPartition)
{
for (PxU32 a = 0; a < mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
for (PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(body.maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
}
PX_FORCE_INLINE void zeroBodies()
{
for(PxU32 a=0; a<mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
body.maxSolverFrictionProgress = 0;
body.maxSolverNormalProgress = 0;
}
}
PX_FORCE_INLINE void afterClassification() const
{
for(PxU32 a=0; a<mBodySize; a += mBodyStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
}
};
class ExtendedRigidBodyClassification : public ExtendedRigidBodyClassificationBase
{
public:
ExtendedRigidBodyClassification(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations)
: ExtendedRigidBodyClassificationBase(bodies, numBodies, stride, articulations, numArticulations)
{
}
// PT: this version is slightly different from the SDK version, no mArticulationIndex!
//Returns true if it is a dynamic-dynamic constraint; false if it is a dynamic-static or dynamic-kinematic constraint
PX_FORCE_INLINE bool classifyConstraint(const PxSolverConstraintDesc& desc, uintptr_t& indexA, uintptr_t& indexB,
bool& activeA, bool& activeB, PxU32& bodyAProgress, PxU32& bodyBProgress) const
{
bool hasStatic = false;
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mStride;
activeA = indexA < mBodyCount;
hasStatic = !activeA;//desc.bodyADataIndex == 0;
bodyAProgress = activeA ? desc.bodyA->solverProgress : 0;
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
indexA = mBodyCount;
//bodyAProgress = articulationA->getFsDataPtr()->solverProgress;
bodyAProgress = articulationA->solverProgress;
activeA = true;
}
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mStride;
activeB = indexB < mBodyCount;
hasStatic = hasStatic || !activeB;
bodyBProgress = activeB ? desc.bodyB->solverProgress : 0;
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
indexB = mBodyCount;
activeB = true;
bodyBProgress = articulationB->solverProgress;
}
return !hasStatic;
}
PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool& activeA, bool& activeB)
{
if (activeA)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
desc.bodyA->maxSolverFrictionProgress++;
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->maxSolverFrictionProgress++;
}
}
if (activeB)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
desc.bodyB->maxSolverFrictionProgress++;
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->maxSolverFrictionProgress++;
}
}
}
PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const
{
if (activeA)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++);
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
return PxU32(articulationA->maxSolverNormalProgress + articulationA->maxSolverFrictionProgress++);
}
}
else if (activeB)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++);
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
return PxU32(articulationB->maxSolverNormalProgress + articulationB->maxSolverFrictionProgress++);
}
}
return 0xffffffff;
}
PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition)
{
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexA)
{
desc.bodyA->solverProgress = bodyAProgress;
desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition);
}
else
{
Dy::FeatherstoneArticulation* articulationA = getArticulationA(desc);
articulationA->solverProgress = bodyAProgress;
articulationA->maxSolverNormalProgress = PxMax(articulationA->maxSolverNormalProgress, availablePartition);
}
if (PxSolverConstraintDesc::RIGID_BODY == desc.linkIndexB)
{
desc.bodyB->solverProgress = bodyBProgress;
desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition);
}
else
{
Dy::FeatherstoneArticulation* articulationB = getArticulationB(desc);
articulationB->solverProgress = bodyBProgress;
articulationB->maxSolverNormalProgress = PxMax(articulationB->maxSolverNormalProgress, availablePartition);
}
}
PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxU32* numConstraintsPerPartition)
{
for (PxU32 a = 0; a < mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
for (PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(body.maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
for (PxU32 a = 0; a < mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
for (PxU32 b = 0; b < articulation->maxSolverFrictionProgress; ++b)
{
PxU32 partId = PxMin(PxU32(articulation->maxSolverNormalProgress + b), MAX_NUM_PARTITIONS);
numConstraintsPerPartition[partId]++;
}
}
}
PX_FORCE_INLINE void zeroBodies()
{
for(PxU32 a=0; a<mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
body.maxSolverFrictionProgress = 0;
body.maxSolverNormalProgress = 0;
}
for(PxU32 a=0; a<mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
articulation->maxSolverNormalProgress = 0;
}
}
PX_FORCE_INLINE void afterClassification() const
{
for(PxU32 a=0; a<mBodySize; a += mStride)
{
PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies + a);
body.solverProgress = 0;
//Keep the dynamic constraint count but bump the static constraint count back to 0.
//This allows us to place the static constraints in the appropriate place when we see them
//because we know the maximum index for the dynamic constraints...
body.maxSolverFrictionProgress = 0;
}
for(PxU32 a=0; a<mNumArticulations; ++a)
{
Dy::FeatherstoneArticulation* articulation = mArticulations[a];
articulation->solverProgress = 0;
articulation->maxSolverFrictionProgress = 0;
}
}
};
template <typename Classification>
void classifyConstraintDesc(const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxU32* numConstraintsPerPartition)
{
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
PxMemZero(numConstraintsPerPartition, sizeof(PxU32) * (MAX_NUM_PARTITIONS+1));
for(PxU32 i=0; i<numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB);
if(notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
//Write to overflow partition...
numConstraintsPerPartition[availablePartition]++;
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(MAX_NUM_PARTITIONS));
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
partitionsA |= partitionBit;
partitionsB |= partitionBit;
}
numConstraintsPerPartition[availablePartition]++;
availablePartition++;
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition));
}
else
{
//Just count the number of static constraints and store in maxSolverFrictionProgress...
classification.recordStaticConstraint(*_desc, activeA, activeB);
}
}
classification.reserveSpaceForStaticConstraints(numConstraintsPerPartition);
}
template <typename Classification>
void writeConstraintDesc( const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification,
PxU32* accumulatedConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc)
{
const PxSolverConstraintDesc* _desc = descs;
const PxU32 numConstraintsMin1 = numConstraints - 1;
for(PxU32 i=0; i<numConstraints; ++i, _desc++)
{
const PxU32 prefetchOffset = PxMin(numConstraintsMin1 - i, 4u);
PxPrefetchLine(_desc[prefetchOffset].constraint);
PxPrefetchLine(_desc[prefetchOffset].bodyA);
PxPrefetchLine(_desc[prefetchOffset].bodyB);
PxPrefetchLine(_desc + 8);
uintptr_t indexA, indexB;
bool activeA, activeB;
PxU32 partitionsA, partitionsB;
const bool notContainsStatic = classification.classifyConstraint(*_desc, indexA, indexB, activeA, activeB,
partitionsA, partitionsB);
if (notContainsStatic)
{
PxU32 availablePartition;
{
const PxU32 combinedMask = (~partitionsA & ~partitionsB);
availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask);
if (availablePartition == MAX_NUM_PARTITIONS)
{
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[availablePartition]++] = *_desc;
continue;
}
const PxU32 partitionBit = (1u << availablePartition);
partitionsA |= partitionBit;
partitionsB |= partitionBit;
}
classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition+1));
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[availablePartition]++] = *_desc;
}
else
{
//Just count the number of static constraints and store in maxSolverFrictionProgress...
//KS - TODO - handle registration of static contacts with articulations here!
PxU32 index = classification.getStaticContactWriteIndex(*_desc, activeA, activeB);
eaOrderedConstraintDesc[accumulatedConstraintsPerPartition[index]++] = *_desc;
}
}
}
template <typename Classification>
PxU32 BatchConstraints(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxConstraintBatchHeader* outBatchHeaders,
PxSolverConstraintDesc* outOrderedConstraintDescs, Classification& classification)
{
if(!nbConstraints)
return 0;
PxU32 constraintsPerPartition[MAX_NUM_PARTITIONS + 1];
classification.zeroBodies();
classifyConstraintDesc(solverConstraintDescs, nbConstraints, classification, constraintsPerPartition);
PxU32 accumulation = 0;
for (PxU32 a = 0; a < MAX_NUM_PARTITIONS + 1; ++a)
{
PxU32 count = constraintsPerPartition[a];
constraintsPerPartition[a] = accumulation;
accumulation += count;
}
classification.afterClassification();
writeConstraintDesc(solverConstraintDescs, nbConstraints, classification, constraintsPerPartition, outOrderedConstraintDescs);
PxU32 numHeaders = 0;
PxU32 currentPartition = 0;
PxU32 maxJ = nbConstraints == 0 ? 0 : constraintsPerPartition[0];
const PxU32 maxBatchPartition = MAX_NUM_PARTITIONS;
for (PxU32 a = 0; a < nbConstraints;)
{
PxConstraintBatchHeader& header = outBatchHeaders[numHeaders++];
header.startIndex = a;
PxU32 loopMax = PxMin(maxJ - a, 4u);
PxU16 j = 0;
if (loopMax > 0)
{
j = 1;
PxSolverConstraintDesc& desc = outOrderedConstraintDescs[a];
if(isArticulationConstraint(desc))
loopMax = 1;
if (currentPartition < maxBatchPartition)
{
for (; j < loopMax && desc.constraintLengthOver16 == outOrderedConstraintDescs[a + j].constraintLengthOver16
&& !isArticulationConstraint(outOrderedConstraintDescs[a + j]); ++j);
}
header.stride = j;
header.constraintType = desc.constraintLengthOver16;
}
if (maxJ == (a + j) && maxJ != nbConstraints)
{
currentPartition++;
maxJ = constraintsPerPartition[currentPartition];
}
a += j;
}
return numHeaders;
}
}
PxU32 immediate::PxBatchConstraints(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxSolverBody* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations, PxU32 nbArticulations)
{
PX_ASSERT((size_t(solverBodies) & 0xf) == 0);
if(!nbArticulations)
{
RigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxSolverBody));
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
else
{
ExtendedRigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxSolverBody), reinterpret_cast<Dy::FeatherstoneArticulation**>(articulations), nbArticulations);
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
}
bool immediate::PxCreateContactConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold,
PxReal correlationDistance, PxSpatialVector* ZV)
{
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PX_ASSERT(bounceThreshold < 0.0f);
PX_ASSERT(frictionOffsetThreshold > 0.0f);
PX_ASSERT(correlationDistance > 0.0f);
Dy::CorrelationBuffer cb;
PxU32 currentContactDescIdx = 0;
const PxReal dt = 1.0f / invDt;
for(PxU32 i=0; i<nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
if (batchHeader.stride == 4)
{
PxU32 totalContacts = contactDescs[currentContactDescIdx].numContacts + contactDescs[currentContactDescIdx + 1].numContacts +
contactDescs[currentContactDescIdx + 2].numContacts + contactDescs[currentContactDescIdx + 3].numContacts;
if (totalContacts <= 64)
{
state = Dy::createFinalizeSolverContacts4(cb,
contactDescs + currentContactDescIdx,
invDt,
dt,
bounceThreshold,
frictionOffsetThreshold,
correlationDistance,
allocator);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(ZV);
for(PxU32 a=0; a<batchHeader.stride; ++a)
{
Dy::createFinalizeSolverContacts(contactDescs[currentContactDescIdx + a], cb, invDt, dt, bounceThreshold,
frictionOffsetThreshold, correlationDistance, allocator, Z);
}
}
if(contactDescs[currentContactDescIdx].desc->constraint)
{
PxU8 type = *contactDescs[currentContactDescIdx].desc->constraint;
if(type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for(PxU32 c=1; c<batchHeader.stride; ++c)
{
if (*contactDescs[currentContactDescIdx + c].desc->constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
break;
}
}
}
batchHeader.constraintType = type;
}
currentContactDescIdx += batchHeader.stride;
}
return true;
}
bool immediate::PxCreateJointConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxSpatialVector* ZV, PxReal dt, PxReal invDt)
{
PX_ASSERT(dt > 0.0f);
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PxU32 currentDescIdx = 0;
for(PxU32 i=0; i<nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
PxU8 type = DY_SC_TYPE_BLOCK_1D;
if (batchHeader.stride == 4)
{
PxU32 totalRows = 0;
PxU32 maxRows = 0;
bool batchable = true;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
if (jointDescs[currentDescIdx + a].numRows == 0)
{
batchable = false;
break;
}
totalRows += jointDescs[currentDescIdx + a].numRows;
maxRows = PxMax(maxRows, jointDescs[currentDescIdx + a].numRows);
}
if (batchable)
{
state = Dy::setupSolverConstraint4
(jointDescs + currentDescIdx,
dt, invDt, totalRows,
allocator, maxRows);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
type = DY_SC_TYPE_RB_1D;
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(ZV);
for(PxU32 a=0; a<batchHeader.stride; ++a)
{
// PT: TODO: And "isExtended" is already computed in Dy::ConstraintHelper::setupSolverConstraint
PxSolverConstraintDesc& desc = *jointDescs[currentDescIdx + a].desc;
const bool isExtended = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
if(isExtended)
type = DY_SC_TYPE_EXT_1D;
Dy::ConstraintHelper::setupSolverConstraint(jointDescs[currentDescIdx + a], allocator, dt, invDt, Z);
}
}
batchHeader.constraintType = type;
currentDescIdx += batchHeader.stride;
}
return true;
}
template<class LeafTestT, class ParamsT>
static bool PxCreateJointConstraintsWithShadersT(PxConstraintBatchHeader* batchHeaders, const PxU32 nbHeaders, ParamsT* params, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxSpatialVector* Z, PxReal dt, PxReal invDt)
{
Px1DConstraint allRows[Dy::MAX_CONSTRAINT_ROWS * 4];
//Runs shaders to fill in rows...
PxU32 currentDescIdx = 0;
for(PxU32 i=0; i<nbHeaders; i++)
{
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
for(PxU32 a=0; a<batchHeader.stride; a++)
{
PxSolverConstraintPrepDesc& desc = jointDescs[currentDescIdx + a];
PxConstraintSolverPrep prep;
const void* constantBlock;
const bool useExtendedLimits = LeafTestT::getData(params, currentDescIdx + a, &prep, &constantBlock);
PX_ASSERT(prep);
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_cA2w, unused_cB2w;
//TAG:solverprepcall
const PxU32 constraintCount = prep(rows,
desc.body0WorldOffset,
Dy::MAX_CONSTRAINT_ROWS,
desc.invMassScales,
constantBlock,
desc.bodyFrame0, desc.bodyFrame1,
useExtendedLimits,
unused_cA2w, unused_cB2w);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
PxCreateJointConstraints(&batchHeader, 1, jointDescs + currentDescIdx, allocator, Z, dt, invDt);
currentDescIdx += batchHeader.stride;
}
return true; //KS - TODO - do some error reporting/management...
}
namespace
{
class PxConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxConstraint** constraints, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
NpConstraint* npConstraint = static_cast<NpConstraint*>(constraints[i]);
const Sc::ConstraintCore& core = npConstraint->getCore();
if (npConstraint->isDirty())
{
core.getPxConnector()->prepareData();
npConstraint->markClean();
}
*prep = core.getPxConnector()->getPrep();
*constantBlock = core.getPxConnector()->getConstantBlock();
return core.getFlags() & PxConstraintFlag::eENABLE_EXTENDED_LIMITS;
}
};
}
bool immediate::PxCreateJointConstraintsWithShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxConstraint** constraints, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z)
{
return PxCreateJointConstraintsWithShadersT<PxConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, Z, dt, invDt);
}
bool immediate::PxCreateJointConstraintsWithImmediateShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxImmediateConstraint* constraints, PxSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z)
{
class immConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxImmediateConstraint* constraints_, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
const PxImmediateConstraint& ic = constraints_[i];
*prep = ic.prep;
*constantBlock = ic.constantBlock;
return false;
}
};
return PxCreateJointConstraintsWithShadersT<immConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, Z, dt, invDt);
}
/*static*/ PX_FORCE_INLINE bool PxIsZero(const PxSolverBody* bodies, PxU32 nbBodies)
{
for(PxU32 i=0; i<nbBodies; i++)
{
if( !bodies[i].linearVelocity.isZero() ||
!bodies[i].angularState.isZero())
return false;
}
return true;
}
void immediate::PxSolveConstraints(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
const PxSolverBody* solverBodies, PxVec3* linearMotionVelocity, PxVec3* angularMotionVelocity, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt, float invDt, PxU32 nbSolverArticulations, PxArticulationHandle* solverArticulations, PxSpatialVector* pxZ, PxSpatialVector* pxDeltaV)
{
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
PX_ASSERT(PxIsZero(solverBodies, nbSolverBodies)); //Ensure that solver body velocities have been zeroed before solving
PX_ASSERT((size_t(solverBodies) & 0xf) == 0);
const Dy::SolveBlockMethod* solveTable = Dy::getSolveBlockTable();
const Dy::SolveBlockMethod* solveConcludeTable = Dy::getSolverConcludeBlockTable();
const Dy::SolveWriteBackBlockMethod* solveWritebackTable = Dy::getSolveWritebackBlockTable();
Dy::SolverContext cache;
cache.mThresholdStreamIndex = 0;
cache.mThresholdStreamLength = 0xFFFFFFF;
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(pxZ);
Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(pxDeltaV);
cache.Z = Z;
cache.deltaV = deltaV;
Dy::FeatherstoneArticulation** articulations = reinterpret_cast<Dy::FeatherstoneArticulation**>(solverArticulations);
struct PGS
{
static PX_FORCE_INLINE void solveArticulationInternalConstraints(float dt_, float invDt_, PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** solverArticulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_, bool velIter_)
{
while(nbSolverArticulations_--)
{
immArticulation* immArt = static_cast<immArticulation*>(*solverArticulations_++);
immArt->immSolveInternalConstraints(dt_, invDt_, Z_, deltaV_, 0.0f, velIter_, false);
}
}
static PX_FORCE_INLINE void runIter(const PxConstraintBatchHeader* batchHeaders_, PxU32 nbBatchHeaders_, const PxSolverConstraintDesc* solverConstraintDescs_,
PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** articulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_,
const Dy::SolveBlockMethod* solveTable_, Dy::SolverContext& solverCache_, float dt_, float invDt_, bool doFriction, bool velIter_)
{
solverCache_.doFriction = doFriction;
for(PxU32 a=0; a<nbBatchHeaders_; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders_[a];
solveTable_[batch.constraintType](solverConstraintDescs_ + batch.startIndex, batch.stride, solverCache_);
}
solveArticulationInternalConstraints(dt_, invDt_, nbSolverArticulations_, articulations_, Z_, deltaV_, velIter_);
}
};
for(PxU32 i=nbPositionIterations; i>1; --i)
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveTable, cache, dt, invDt, i <= 3, false);
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveConcludeTable, cache, dt, invDt, true, false);
//Save motion velocities...
for(PxU32 a=0; a<nbSolverBodies; a++)
{
linearMotionVelocity[a] = solverBodies[a].linearVelocity;
angularMotionVelocity[a] = solverBodies[a].angularState;
}
for(PxU32 a=0; a<nbSolverArticulations; a++)
FeatherstoneArticulation::saveVelocity(reinterpret_cast<Dy::FeatherstoneArticulation*>(solverArticulations[a]), deltaV);
for(PxU32 i=nbVelocityIterations; i>1; --i)
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveTable, cache, dt, invDt, true, true);
PGS::runIter(batchHeaders, nbBatchHeaders, solverConstraintDescs, nbSolverArticulations, articulations, Z, deltaV, solveWritebackTable, cache, dt, invDt, true, true);
}
static void createCache(Gu::Cache& cache, PxGeometryType::Enum geomType0, PxGeometryType::Enum geomType1, PxCacheAllocator& allocator)
{
if(gEnablePCMCaching[geomType0][geomType1])
{
if(geomType0 <= PxGeometryType::eCONVEXMESH && geomType1 <= PxGeometryType::eCONVEXMESH)
{
if(geomType0 == PxGeometryType::eSPHERE || geomType1 == PxGeometryType::eSPHERE)
{
Gu::PersistentContactManifold* manifold = PX_PLACEMENT_NEW(allocator.allocateCacheData(sizeof(Gu::SpherePersistentContactManifold)), Gu::SpherePersistentContactManifold)();
cache.setManifold(manifold);
}
else
{
Gu::PersistentContactManifold* manifold = PX_PLACEMENT_NEW(allocator.allocateCacheData(sizeof(Gu::LargePersistentContactManifold)), Gu::LargePersistentContactManifold)();
cache.setManifold(manifold);
}
cache.getManifold().clearManifold();
}
else
{
//ML: raised 1 to indicate the manifold is multiManifold which is for contact gen in mesh/height field
//cache.manifold = 1;
cache.setMultiManifold(NULL);
}
}
else
{
//cache.manifold = 0;
cache.mCachedData = NULL;
cache.mManifoldFlags = 0;
}
}
bool immediate::PxGenerateContacts( const PxGeometry* const * geom0, const PxGeometry* const * geom1, const PxTransform* pose0, const PxTransform* pose1, PxCache* contactCache, PxU32 nbPairs,
PxContactRecorder& contactRecorder, PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxCacheAllocator& allocator)
{
PX_ASSERT(meshContactMargin > 0.0f);
PX_ASSERT(toleranceLength > 0.0f);
PX_ASSERT(contactDistance > 0.0f);
PxContactBuffer contactBuffer;
PxTransform32 transform0;
PxTransform32 transform1;
for (PxU32 i = 0; i < nbPairs; ++i)
{
contactBuffer.count = 0;
PxGeometryType::Enum type0 = geom0[i]->getType();
PxGeometryType::Enum type1 = geom1[i]->getType();
const PxGeometry* tempGeom0 = geom0[i];
const PxGeometry* tempGeom1 = geom1[i];
const bool bSwap = type0 > type1;
if (bSwap)
{
PxSwap(tempGeom0, tempGeom1);
PxSwap(type0, type1);
transform1 = pose0[i];
transform0 = pose1[i];
}
else
{
transform0 = pose0[i];
transform1 = pose1[i];
}
//Now work out which type of PCM we need...
Gu::Cache& cache = static_cast<Gu::Cache&>(contactCache[i]);
bool needsMultiManifold = type1 > PxGeometryType::eCONVEXMESH;
Gu::NarrowPhaseParams params(contactDistance, meshContactMargin, toleranceLength);
if (needsMultiManifold)
{
Gu::MultiplePersistentContactManifold multiManifold;
if (cache.isMultiManifold())
{
multiManifold.fromBuffer(reinterpret_cast<PxU8*>(&cache.getMultipleManifold()));
}
else
{
multiManifold.initialize();
}
cache.setMultiManifold(&multiManifold);
//Do collision detection, then write manifold out...
g_PCMContactMethodTable[type0][type1](*tempGeom0, *tempGeom1, transform0, transform1, params, cache, contactBuffer, NULL);
const PxU32 size = (sizeof(Gu::MultiPersistentManifoldHeader) +
multiManifold.mNumManifolds * sizeof(Gu::SingleManifoldHeader) +
multiManifold.mNumTotalContacts * sizeof(Gu::CachedMeshPersistentContact));
PxU8* buffer = allocator.allocateCacheData(size);
multiManifold.toBuffer(buffer);
cache.setMultiManifold(buffer);
}
else
{
//Allocate the type of manifold we need again...
Gu::PersistentContactManifold* oldManifold = NULL;
if (cache.isManifold())
oldManifold = &cache.getManifold();
//Allocates and creates the PCM...
createCache(cache, type0, type1, allocator);
//Copy PCM from old to new manifold...
if (oldManifold)
{
Gu::PersistentContactManifold& manifold = cache.getManifold();
manifold.mRelativeTransform = oldManifold->mRelativeTransform;
manifold.mQuatA = oldManifold->mQuatA;
manifold.mQuatB = oldManifold->mQuatB;
manifold.mNumContacts = oldManifold->mNumContacts;
manifold.mNumWarmStartPoints = oldManifold->mNumWarmStartPoints;
manifold.mAIndice[0] = oldManifold->mAIndice[0]; manifold.mAIndice[1] = oldManifold->mAIndice[1];
manifold.mAIndice[2] = oldManifold->mAIndice[2]; manifold.mAIndice[3] = oldManifold->mAIndice[3];
manifold.mBIndice[0] = oldManifold->mBIndice[0]; manifold.mBIndice[1] = oldManifold->mBIndice[1];
manifold.mBIndice[2] = oldManifold->mBIndice[2]; manifold.mBIndice[3] = oldManifold->mBIndice[3];
PxMemCopy(manifold.mContactPoints, oldManifold->mContactPoints, sizeof(Gu::PersistentContact)*manifold.mNumContacts);
}
g_PCMContactMethodTable[type0][type1](*tempGeom0, *tempGeom1, transform0, transform1, params, cache, contactBuffer, NULL);
}
if (bSwap)
{
for (PxU32 a = 0; a < contactBuffer.count; ++a)
{
contactBuffer.contacts[a].normal = -contactBuffer.contacts[a].normal;
}
}
if (contactBuffer.count != 0)
{
//Record this contact pair...
contactRecorder.recordContacts(contactBuffer.contacts, contactBuffer.count, i);
}
}
return true;
}
immArticulation::immArticulation(const PxArticulationDataRC& data) :
FeatherstoneArticulation(this),
mFlags (data.flags),
mImmDirty (true),
mJCalcDirty (true)
{
// PT: TODO: we only need the flags here, maybe drop the solver desc?
getSolverDesc().initData(NULL, &mFlags);
}
immArticulation::~immArticulation()
{
}
void immArticulation::initJointCore(Dy::ArticulationJointCore& core, const PxArticulationJointDataRC& inboundJoint)
{
core.init(inboundJoint.parentPose, inboundJoint.childPose);
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eMOTION | Dy::ArticulationJointCoreDirtyFlag::eFRAME;
const PxU32* binP = reinterpret_cast<const PxU32*>(inboundJoint.targetPos);
const PxU32* binV = reinterpret_cast<const PxU32*>(inboundJoint.targetVel);
for(PxU32 i=0; i<PxArticulationAxis::eCOUNT; i++)
{
core.initLimit(PxArticulationAxis::Enum(i), inboundJoint.limits[i]);
core.initDrive(PxArticulationAxis::Enum(i), inboundJoint.drives[i]);
// See Sc::ArticulationJointCore::setTargetP and Sc::ArticulationJointCore::setTargetV
if(binP[i]!=0xffffffff)
{
core.targetP[i] = inboundJoint.targetPos[i];
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETPOSE;
}
if(binV[i]!=0xffffffff)
{
core.targetV[i] = inboundJoint.targetVel[i];
core.jointDirtyFlag |= Dy::ArticulationJointCoreDirtyFlag::eTARGETVELOCITY;
}
core.armature[i] = inboundJoint.armature[i];
core.jointPos[i] = inboundJoint.jointPos[i];
core.jointVel[i] = inboundJoint.jointVel[i];
core.motion[i] = PxU8(inboundJoint.motion[i]);
}
core.initFrictionCoefficient(inboundJoint.frictionCoefficient);
core.initMaxJointVelocity(inboundJoint.maxJointVelocity);
core.initJointType(inboundJoint.type);
}
void immArticulation::allocate(const PxU32 nbLinks)
{
mLinks.reserve(nbLinks);
mBodyCores.resize(nbLinks);
mArticulationJointCores.resize(nbLinks);
}
PxU32 immArticulation::addLink(const PxU32 parentIndex, const PxArticulationLinkDataRC& data)
{
PX_ASSERT(data.pose.p.isFinite());
PX_ASSERT(data.pose.q.isFinite());
mImmDirty = true;
mJCalcDirty = true;
// Replicate ArticulationSim::addBody
addBody();
const PxU32 index = mLinks.size();
const PxTransform& bodyPose = data.pose;
//
PxsBodyCore* bodyCore = &mBodyCores[index];
{
// PT: this function inits everything but we only need a fraction of the data there for articulations
bodyCore->init( bodyPose, data.inverseInertia, data.inverseMass, 0.0f, 0.0f,
data.linearDamping, data.angularDamping,
data.maxLinearVelocitySq, data.maxAngularVelocitySq, PxActorType::eARTICULATION_LINK);
// PT: TODO: consider exposing all used data to immediate mode API (PX-1398)
// bodyCore->maxPenBias = -1e32f; // <= this one is related to setMaxDepenetrationVelocity
// bodyCore->linearVelocity = PxVec3(0.0f);
// bodyCore->angularVelocity = PxVec3(0.0f);
// bodyCore->linearVelocity = PxVec3(0.0f, 10.0f, 0.0f);
// bodyCore->angularVelocity = PxVec3(0.0f, 10.0f, 0.0f);
bodyCore->cfmScale = data.cfmScale;
}
/* PX_ASSERT((((index==0) && (joint == 0)) && (parent == 0)) ||
(((index!=0) && joint) && (parent && (parent->getArticulation() == this))));*/
// PT: TODO: add ctors everywhere
ArticulationLink& link = mLinks.insert();
// void BodySim::postActorFlagChange(PxU32 oldFlags, PxU32 newFlags)
bodyCore->disableGravity = data.disableGravity;
link.bodyCore = bodyCore;
link.children = 0;
link.mPathToRootStartIndex = 0;
link.mPathToRootCount = 0;
link.mChildrenStartIndex = 0xffffffff;
link.mNumChildren = 0;
const bool isRoot = parentIndex==0xffffffff;
if(!isRoot)
{
link.parent = parentIndex;
//link.pathToRoot = mLinks[parentIndex].pathToRoot | ArticulationBitField(1)<<index;
link.inboundJoint = &mArticulationJointCores[index];
ArticulationLink& parentLink = mLinks[parentIndex];
parentLink.children |= ArticulationBitField(1)<<index;
if(parentLink.mChildrenStartIndex == 0xffffffff)
parentLink.mChildrenStartIndex = index;
parentLink.mNumChildren++;
initJointCore(*link.inboundJoint, data.inboundJoint);
}
else
{
link.parent = DY_ARTICULATION_LINK_NONE;
//link.pathToRoot = 1;
link.inboundJoint = NULL;
}
return index;
}
void immArticulation::complete()
{
// Based on Sc::ArticulationSim::checkResize()
if(!mImmDirty)
return;
mImmDirty = false;
const PxU32 linkSize = mLinks.size();
setupLinks(linkSize, const_cast<ArticulationLink*>(mLinks.begin()));
jcalc<true>(mArticulationData);
mJCalcDirty = false;
initPathToRoot();
mTempDeltaV.resize(linkSize);
mTempZ.resize(linkSize);
}
PxArticulationCookie immediate::PxBeginCreateArticulationRC(const PxArticulationDataRC& data)
{
// PT: we create the same class as before under the hood, we just don't tell users yet. Returning a void pointer/cookie
// means we can prevent them from using the articulation before it's fully completed. We do this because we're going to
// delay the link creation, so we don't want them to call PxAddArticulationLink and expect the link to be here already.
void* memory = PxAlignedAllocator<64>().allocate(sizeof(immArticulation), PX_FL);
PX_PLACEMENT_NEW(memory, immArticulation(data));
return memory;
}
PxArticulationLinkCookie immediate::PxAddArticulationLink(PxArticulationCookie articulation, const PxArticulationLinkCookie* parent, const PxArticulationLinkDataRC& data)
{
if(!articulation)
return PxCreateArticulationLinkCookie();
immArticulation* immArt = reinterpret_cast<immArticulation*>(articulation);
const PxU32 id = immArt->mTemp.size();
// PT: TODO: this is the quick-and-dirty version, we could try something smarter where we don't just batch everything like barbarians
immArticulation::immArticulationLinkDataRC tmp;
static_cast<PxArticulationLinkDataRC&>(tmp) = data;
tmp.userID = id;
tmp.parent = parent ? *parent : PxCreateArticulationLinkCookie();
immArt->mTemp.pushBack(tmp);
// WARNING: cannot be null, snippet uses null for regular rigid bodies (non articulation links)
return PxCreateArticulationLinkCookie(articulation, id);
}
PxArticulationHandle immediate::PxEndCreateArticulationRC(PxArticulationCookie articulation, PxArticulationLinkHandle* handles, PxU32 bufferSize)
{
if(!articulation)
return NULL;
immArticulation* immArt = reinterpret_cast<immArticulation*>(articulation);
PxU32 nbLinks = immArt->mTemp.size();
if(nbLinks!=bufferSize)
return NULL;
immArticulation::immArticulationLinkDataRC* linkData = immArt->mTemp.begin();
{
struct _{ bool operator()(const immArticulation::immArticulationLinkDataRC& data1, const immArticulation::immArticulationLinkDataRC& data2) const
{
if(!data1.parent.articulation)
return true;
if(!data2.parent.articulation)
return false;
return data1.parent.linkId < data2.parent.linkId;
}};
PxSort(linkData, nbLinks, _());
}
PxMemSet(handles, 0, sizeof(PxArticulationLinkHandle)*nbLinks);
immArt->allocate(nbLinks);
while(nbLinks--)
{
const PxU32 userID = linkData->userID;
PxU32 parentID = linkData->parent.linkId;
if(parentID != 0xffffffff)
parentID = handles[parentID].linkId;
const PxU32 realID = immArt->addLink(parentID, *linkData);
handles[userID] = PxArticulationLinkHandle(immArt, realID);
linkData++;
}
immArt->complete();
return immArt;
}
void immediate::PxReleaseArticulation(PxArticulationHandle articulation)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->~immArticulation();
PxAlignedAllocator<64>().deallocate(articulation);
}
PxArticulationCache* immediate::PxCreateArticulationCache(PxArticulationHandle articulation)
{
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
return FeatherstoneArticulation::createCache(immArt->getDofs(), immArt->getBodyCount(), 0);
}
void immediate::PxCopyInternalStateToArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag)
{
immArticulation* immArt = static_cast<immArticulation *>(articulation);
immArt->copyInternalStateToCache(cache, flag, false);
}
void immediate::PxApplyArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag)
{
bool shouldWake = false;
immArticulation* immArt = static_cast<immArticulation *>(articulation);
immArt->applyCache(cache, flag, shouldWake);
}
void immediate::PxReleaseArticulationCache(PxArticulationCache& cache)
{
PxcScratchAllocator* scratchAlloc = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator);
PX_DELETE(scratchAlloc);
cache.scratchAllocator = NULL;
PX_FREE(cache.scratchMemory);
PxArticulationCache* ptr = &cache;
PX_FREE(ptr);
}
void immediate::PxComputeUnconstrainedVelocities(PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt, PxReal invLengthScale)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
if(immArt->mJCalcDirty)
{
immArt->mJCalcDirty = false;
immArt->jcalc<true>(immArt->mArticulationData);
}
immArt->immComputeUnconstrainedVelocities(dt, gravity, invLengthScale);
}
void immediate::PxUpdateArticulationBodies(PxArticulationHandle articulation, PxReal dt)
{
if(!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
FeatherstoneArticulation::updateBodies(immArt, immArt->mTempDeltaV.begin(), dt, true);
}
void immediate::PxComputeUnconstrainedVelocitiesTGS(PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt,
PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal invLengthScale)
{
if (!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
immArt->complete();
if(immArt->mJCalcDirty)
{
immArt->mJCalcDirty = false;
immArt->jcalc<true>(immArt->mArticulationData);
}
immArt->immComputeUnconstrainedVelocitiesTGS(dt, totalDt, invDt, invTotalDt, gravity, invLengthScale);
}
void immediate::PxUpdateArticulationBodiesTGS(PxArticulationHandle articulation, PxReal dt)
{
if (!articulation)
return;
immArticulation* immArt = static_cast<immArticulation*>(articulation);
FeatherstoneArticulation::updateBodies(immArt, immArt->mTempDeltaV.begin(), dt, false);
}
static void copyLinkData(PxArticulationLinkDerivedDataRC& data, const immArticulation* immArt, PxU32 index)
{
data.pose = immArt->mBodyCores[index].body2World;
// data.linearVelocity = immArt->mBodyCores[index].linearVelocity;
// data.angularVelocity = immArt->mBodyCores[index].angularVelocity;
const Cm::SpatialVectorF& velocity = immArt->getArticulationData().getMotionVelocity(index);
data.linearVelocity = velocity.bottom;
data.angularVelocity = velocity.top;
}
static PX_FORCE_INLINE const immArticulation* getFromLink(const PxArticulationLinkHandle& link, PxU32& index)
{
if(!link.articulation)
return NULL;
const immArticulation* immArt = static_cast<const immArticulation*>(link.articulation);
index = link.linkId;
if(index>=immArt->mLinks.size())
return NULL;
return immArt;
}
bool immediate::PxGetLinkData(const PxArticulationLinkHandle& link, PxArticulationLinkDerivedDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
copyLinkData(data, immArt, index);
return true;
}
PxU32 immediate::PxGetAllLinkData(const PxArticulationHandle articulation, PxArticulationLinkDerivedDataRC* data)
{
if(!articulation)
return 0;
const immArticulation* immArt = static_cast<const immArticulation*>(articulation);
const PxU32 nb = immArt->mLinks.size();
if(data)
{
for(PxU32 i=0;i<nb;i++)
copyLinkData(data[i], immArt, i);
}
return nb;
}
bool immediate::PxGetMutableLinkData(const PxArticulationLinkHandle& link , PxArticulationLinkMutableDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
data.inverseInertia = immArt->mBodyCores[index].inverseInertia;
data.inverseMass = immArt->mBodyCores[index].inverseMass;
data.linearDamping = immArt->mBodyCores[index].linearDamping;
data.angularDamping = immArt->mBodyCores[index].angularDamping;
data.maxLinearVelocitySq = immArt->mBodyCores[index].maxLinearVelocitySq;
data.maxAngularVelocitySq = immArt->mBodyCores[index].maxAngularVelocitySq;
data.cfmScale = immArt->mBodyCores[index].cfmScale;
data.disableGravity = immArt->mBodyCores[index].disableGravity!=0;
return true;
}
bool immediate::PxSetMutableLinkData(const PxArticulationLinkHandle& link , const PxArticulationLinkMutableDataRC& data)
{
PxU32 index;
immArticulation* immArt = const_cast<immArticulation*>(getFromLink(link, index));
if(!immArt)
return false;
immArt->mBodyCores[index].inverseInertia = data.inverseInertia; // See Sc::BodyCore::setInverseInertia
immArt->mBodyCores[index].inverseMass = data.inverseMass; // See Sc::BodyCore::setInverseMass
immArt->mBodyCores[index].linearDamping = data.linearDamping; // See Sc::BodyCore::setLinearDamping
immArt->mBodyCores[index].angularDamping = data.angularDamping; // See Sc::BodyCore::setAngularDamping
immArt->mBodyCores[index].maxLinearVelocitySq = data.maxLinearVelocitySq; // See Sc::BodyCore::setMaxLinVelSq
immArt->mBodyCores[index].maxAngularVelocitySq = data.maxAngularVelocitySq; // See Sc::BodyCore::setMaxAngVelSq
immArt->mBodyCores[index].cfmScale = data.cfmScale; // See Sc::BodyCore::setCfmScale
immArt->mBodyCores[index].disableGravity = data.disableGravity; // See BodySim::postActorFlagChange
return true;
}
bool immediate::PxGetJointData(const PxArticulationLinkHandle& link, PxArticulationJointDataRC& data)
{
PxU32 index;
const immArticulation* immArt = getFromLink(link, index);
if(!immArt)
return false;
const Dy::ArticulationJointCore& core = immArt->mArticulationJointCores[index];
data.parentPose = core.parentPose;
data.childPose = core.childPose;
data.frictionCoefficient = core.frictionCoefficient;
data.maxJointVelocity = core.maxJointVelocity;
data.type = PxArticulationJointType::Enum(core.jointType);
for(PxU32 i=0;i<PxArticulationAxis::eCOUNT;i++)
{
data.motion[i] = PxArticulationMotion::Enum(PxU8(core.motion[i]));
data.limits[i] = core.limits[i];
data.drives[i] = core.drives[i];
data.targetPos[i] = core.targetP[i];
data.targetVel[i] = core.targetV[i];
data.armature[i] = core.armature[i];
data.jointPos[i] = core.jointPos[i];
data.jointVel[i] = core.jointVel[i];
}
return true;
}
static bool samePoses(const PxTransform& pose0, const PxTransform& pose1)
{
return (pose0.p == pose1.p) && (pose0.q == pose1.q);
}
// PT: this is not super efficient if you only want to change one parameter. We could consider adding individual, atomic accessors (but that would
// bloat the API) or flags to validate the desired parameters.
bool immediate::PxSetJointData(const PxArticulationLinkHandle& link, const PxArticulationJointDataRC& data)
{
PxU32 index;
immArticulation* immArt = const_cast<immArticulation*>(getFromLink(link, index));
if(!immArt)
return false;
Dy::ArticulationJointCore& core = immArt->mArticulationJointCores[index];
// PT: poses read by jcalc in ArticulationJointCore::setJointFrame. We need to set ArticulationJointCoreDirtyFlag::eFRAME for this.
{
if(!samePoses(core.parentPose, data.parentPose))
{
core.setParentPose(data.parentPose); // PT: also sets ArticulationJointCoreDirtyFlag::eFRAME
immArt->mJCalcDirty = true;
}
if(!samePoses(core.childPose, data.childPose))
{
core.setChildPose(data.childPose); // PT: also sets ArticulationJointCoreDirtyFlag::eFRAME
immArt->mJCalcDirty = true;
}
}
// PT: joint type read by jcalc in computeMotionMatrix, called from ArticulationJointCore::setJointFrame
if(core.jointType!=PxU8(data.type))
{
core.initJointType(data.type);
immArt->mJCalcDirty = true;
}
// PT: TODO: do we need to recompute jcalc for these?
core.frictionCoefficient = data.frictionCoefficient;
core.maxJointVelocity = data.maxJointVelocity;
for(PxU32 i=0;i<PxArticulationAxis::eCOUNT;i++)
{
// PT: we don't need to recompute jcalc for these
core.limits[i] = data.limits[i];
core.drives[i] = data.drives[i];
core.jointPos[i] = data.jointPos[i];
core.jointVel[i] = data.jointVel[i];
// PT: joint motion read by jcalc in computeJointDof. We need to set Dy::ArticulationJointCoreDirtyFlag::eMOTION for this.
if(core.motion[i]!=data.motion[i])
{
core.setMotion(PxArticulationAxis::Enum(i), data.motion[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eMOTION
immArt->mJCalcDirty = true;
}
// PT: targetP read by jcalc in setJointPoseDrive. We need to set ArticulationJointCoreDirtyFlag::eTARGETPOSE for this.
if(core.targetP[i] != data.targetPos[i])
{
core.setTargetP(PxArticulationAxis::Enum(i), data.targetPos[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eTARGETPOSE
immArt->mJCalcDirty = true;
}
// PT: targetV read by jcalc in setJointVelocityDrive. We need to set ArticulationJointCoreDirtyFlag::eTARGETVELOCITY for this.
if(core.targetV[i] != data.targetVel[i])
{
core.setTargetV(PxArticulationAxis::Enum(i), data.targetVel[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eTARGETVELOCITY
immArt->mJCalcDirty = true;
}
// PT: armature read by jcalc in setArmature. We need to set ArticulationJointCoreDirtyFlag::eARMATURE for this.
if(core.armature[i] != data.armature[i])
{
core.setArmature(PxArticulationAxis::Enum(i), data.armature[i]); // PT: also sets ArticulationJointCoreDirtyFlag::eARMATURE
immArt->mJCalcDirty = true;
}
}
return true;
}
namespace physx
{
namespace Dy
{
void copyToSolverBodyDataStep(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold,
PxReal maxAngVelSq, PxU32 lockFlags, bool isKinematic,
PxTGSSolverBodyVel& solverVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData,
PxReal dt, bool gyroscopicForces);
void integrateCoreStep(PxTGSSolverBodyVel& vel, PxTGSSolverBodyTxInertia& txInertia, PxF32 dt);
}
}
void immediate::PxConstructSolverBodiesTGS(const PxRigidBodyData* inRigidData, PxTGSSolverBodyVel* outSolverBodyVel,
PxTGSSolverBodyTxInertia* outSolverBodyTxInertia, PxTGSSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity,
PxReal dt, bool gyroscopicForces)
{
for (PxU32 a = 0; a<nbBodies; a++)
{
const PxRigidBodyData& rigidData = inRigidData[a];
PxVec3 lv = rigidData.linearVelocity, av = rigidData.angularVelocity;
Dy::bodyCoreComputeUnconstrainedVelocity(gravity, dt, rigidData.linearDamping, rigidData.angularDamping, 1.0f, rigidData.maxLinearVelocitySq, rigidData.maxAngularVelocitySq, lv, av, false);
Dy::copyToSolverBodyDataStep(lv, av, rigidData.invMass, rigidData.invInertia, rigidData.body2World, -rigidData.maxDepenetrationVelocity, rigidData.maxContactImpulse, PX_INVALID_NODE,
PX_MAX_F32, rigidData.maxAngularVelocitySq, 0, false, outSolverBodyVel[a], outSolverBodyTxInertia[a], outSolverBodyData[a], dt, gyroscopicForces);
}
}
void immediate::PxConstructStaticSolverBodyTGS(const PxTransform& globalPose, PxTGSSolverBodyVel& solverBodyVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData)
{
const PxVec3 zero(0.0f);
Dy::copyToSolverBodyDataStep(zero, zero, 0.0f, zero, globalPose, -PX_MAX_F32, PX_MAX_F32, PX_INVALID_NODE, PX_MAX_F32, PX_MAX_F32, 0, true, solverBodyVel, solverBodyTxInertia, solverBodyData, 0.0f, false);
}
PxU32 immediate::PxBatchConstraintsTGS(const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxTGSSolverBodyVel* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations, PxU32 nbArticulations)
{
if (!nbArticulations)
{
RigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxTGSSolverBodyVel));
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
else
{
ExtendedRigidBodyClassification classification(reinterpret_cast<PxU8*>(solverBodies), nbBodies, sizeof(PxTGSSolverBodyVel), reinterpret_cast<Dy::FeatherstoneArticulation**>(articulations), nbArticulations);
return BatchConstraints(solverConstraintDescs, nbConstraints, outBatchHeaders, outOrderedConstraintDescs, classification);
}
}
bool immediate::PxCreateContactConstraintsTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxTGSSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal invTotalDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxReal correlationDistance)
{
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
PX_ASSERT(bounceThreshold < 0.0f);
PX_ASSERT(frictionOffsetThreshold > 0.0f);
PX_ASSERT(correlationDistance > 0.0f);
Dy::CorrelationBuffer cb;
PxU32 currentContactDescIdx = 0;
const PxReal biasCoefficient = 2.f*PxSqrt(invTotalDt/invDt);
const PxReal totalDt = 1.f/invTotalDt;
const PxReal dt = 1.f / invDt;
for (PxU32 i = 0; i < nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
if (batchHeader.stride == 4)
{
PxU32 totalContacts = contactDescs[currentContactDescIdx].numContacts + contactDescs[currentContactDescIdx + 1].numContacts +
contactDescs[currentContactDescIdx + 2].numContacts + contactDescs[currentContactDescIdx + 3].numContacts;
if (totalContacts <= 64)
{
state = Dy::createFinalizeSolverContacts4Step(cb,
contactDescs + currentContactDescIdx,
invDt,
totalDt,
invTotalDt,
dt,
bounceThreshold,
frictionOffsetThreshold,
correlationDistance,
biasCoefficient,
allocator);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
Dy::createFinalizeSolverContactsStep(contactDescs[currentContactDescIdx + a], cb, invDt, invTotalDt, totalDt, dt, bounceThreshold,
frictionOffsetThreshold, correlationDistance, biasCoefficient, allocator);
}
}
if(contactDescs[currentContactDescIdx].desc->constraint)
{
PxU8 type = *contactDescs[currentContactDescIdx].desc->constraint;
if (type == DY_SC_TYPE_STATIC_CONTACT)
{
//Check if any block of constraints is classified as type static (single) contact constraint.
//If they are, iterate over all constraints grouped with it and switch to "dynamic" contact constraint
//type if there's a dynamic contact constraint in the group.
for (PxU32 c = 1; c < batchHeader.stride; ++c)
{
if (*contactDescs[currentContactDescIdx + c].desc->constraint == DY_SC_TYPE_RB_CONTACT)
{
type = DY_SC_TYPE_RB_CONTACT;
break;
}
}
}
batchHeader.constraintType = type;
}
currentContactDescIdx += batchHeader.stride;
}
return true;
}
bool immediate::PxCreateJointConstraintsTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders,
PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt,
PxReal invTotalDt, PxReal lengthScale)
{
PX_ASSERT(dt > 0.0f);
PX_ASSERT(invDt > 0.0f && PxIsFinite(invDt));
const PxReal biasCoefficient = 2.f*PxSqrt(dt/totalDt);
PxU32 currentDescIdx = 0;
for (PxU32 i = 0; i < nbHeaders; ++i)
{
Dy::SolverConstraintPrepState::Enum state = Dy::SolverConstraintPrepState::eUNBATCHABLE;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
PxU8 type = DY_SC_TYPE_BLOCK_1D;
if (batchHeader.stride == 4)
{
PxU32 totalRows = 0;
PxU32 maxRows = 0;
bool batchable = true;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
if (jointDescs[currentDescIdx + a].numRows == 0)
{
batchable = false;
break;
}
totalRows += jointDescs[currentDescIdx + a].numRows;
maxRows = PxMax(maxRows, jointDescs[currentDescIdx + a].numRows);
}
if (batchable)
{
state = Dy::setupSolverConstraintStep4
(jointDescs + currentDescIdx,
dt, totalDt, invDt, invTotalDt, totalRows,
allocator, maxRows, lengthScale, biasCoefficient);
}
}
if (state == Dy::SolverConstraintPrepState::eUNBATCHABLE)
{
type = DY_SC_TYPE_RB_1D;
for (PxU32 a = 0; a < batchHeader.stride; ++a)
{
// PT: TODO: And "isExtended" is already computed in Dy::ConstraintHelper::setupSolverConstraint
PxSolverConstraintDesc& desc = *jointDescs[currentDescIdx + a].desc;
const bool isExtended = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
if (isExtended)
type = DY_SC_TYPE_EXT_1D;
Dy::setupSolverConstraintStep(jointDescs[currentDescIdx + a], allocator, dt, totalDt, invDt, invTotalDt, lengthScale, biasCoefficient);
}
}
batchHeader.constraintType = type;
currentDescIdx += batchHeader.stride;
}
return true;
}
template<class LeafTestT, class ParamsT>
static bool PxCreateJointConstraintsWithShadersTGS_T(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, ParamsT* params, PxTGSSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale)
{
Px1DConstraint allRows[Dy::MAX_CONSTRAINT_ROWS * 4];
//Runs shaders to fill in rows...
PxU32 currentDescIdx = 0;
for (PxU32 i = 0; i<nbHeaders; i++)
{
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
PxConstraintBatchHeader& batchHeader = batchHeaders[i];
for (PxU32 a = 0; a<batchHeader.stride; a++)
{
PxTGSSolverConstraintPrepDesc& desc = jointDescs[currentDescIdx + a];
PxConstraintSolverPrep prep;
const void* constantBlock;
const bool useExtendedLimits = LeafTestT::getData(params, currentDescIdx + a, &prep, &constantBlock);
PX_ASSERT(prep);
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
//TAG:solverprepcall
const PxU32 constraintCount = prep(rows,
desc.body0WorldOffset,
Dy::MAX_CONSTRAINT_ROWS,
desc.invMassScales,
constantBlock,
desc.bodyFrame0, desc.bodyFrame1,
useExtendedLimits,
desc.cA2w, desc.cB2w);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
PxCreateJointConstraintsTGS(&batchHeader, 1, jointDescs + currentDescIdx, allocator, dt, totalDt, invDt,
invTotalDt, lengthScale);
currentDescIdx += batchHeader.stride;
}
return true; //KS - TODO - do some error reporting/management...
}
bool immediate::PxCreateJointConstraintsWithShadersTGS(PxConstraintBatchHeader* batchHeaders, const PxU32 nbBatchHeaders, PxConstraint** constraints, PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, const PxReal dt,
const PxReal totalDt, const PxReal invDt, const PxReal invTotalDt, const PxReal lengthScale)
{
return PxCreateJointConstraintsWithShadersTGS_T<PxConstraintAdapter>(batchHeaders, nbBatchHeaders, constraints, jointDescs, allocator, dt, totalDt, invDt, invTotalDt, lengthScale);
}
bool immediate::PxCreateJointConstraintsWithImmediateShadersTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxImmediateConstraint* constraints, PxTGSSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale)
{
class immConstraintAdapter
{
public:
static PX_FORCE_INLINE bool getData(PxImmediateConstraint* constraints_, PxU32 i, PxConstraintSolverPrep* prep, const void** constantBlock)
{
const PxImmediateConstraint& ic = constraints_[i];
*prep = ic.prep;
*constantBlock = ic.constantBlock;
return false;
}
};
return PxCreateJointConstraintsWithShadersTGS_T<immConstraintAdapter>(batchHeaders, nbHeaders, constraints, jointDescs, allocator, dt, totalDt, invDt, invTotalDt, lengthScale);
}
void immediate::PxSolveConstraintsTGS(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
PxTGSSolverBodyVel* solverBodies, PxTGSSolverBodyTxInertia* txInertias, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt, float invDt, PxU32 nbSolverArticulations, PxArticulationHandle* solverArticulations, PxSpatialVector* pxZ, PxSpatialVector* pxDeltaV)
{
PX_ASSERT(nbPositionIterations > 0);
PX_ASSERT(nbVelocityIterations > 0);
const Dy::TGSSolveBlockMethod* solveTable = Dy::g_SolveTGSMethods;
const Dy::TGSSolveConcludeMethod* solveConcludeTable = Dy::g_SolveConcludeTGSMethods;
const Dy::TGSWriteBackMethod* writebackTable = Dy::g_WritebackTGSMethods;
Dy::SolverContext cache;
cache.mThresholdStreamIndex = 0;
cache.mThresholdStreamLength = 0xFFFFFFF;
Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(pxZ);
Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(pxDeltaV);
cache.Z = Z;
cache.deltaV = deltaV;
cache.doFriction = true;
Dy::FeatherstoneArticulation** articulations = reinterpret_cast<Dy::FeatherstoneArticulation**>(solverArticulations);
struct TGS
{
static PX_FORCE_INLINE void solveArticulationInternalConstraints(float dt_, float invDt_, PxU32 nbSolverArticulations_, Dy::FeatherstoneArticulation** solverArticulations_, Cm::SpatialVectorF* Z_, Cm::SpatialVectorF* deltaV_,
PxReal elapsedTime, bool velIter_)
{
while(nbSolverArticulations_--)
{
immArticulation* immArt = static_cast<immArticulation*>(*solverArticulations_++);
immArt->immSolveInternalConstraints(dt_, invDt_, Z_, deltaV_, elapsedTime, velIter_, true);
}
}
};
const PxReal invTotalDt = 1.0f/(dt*nbPositionIterations);
PxReal elapsedTime = 0.0f;
while(nbPositionIterations--)
{
TGS::solveArticulationInternalConstraints(dt, invDt, nbSolverArticulations, articulations, Z, deltaV, elapsedTime, false);
for(PxU32 a=0; a<nbBatchHeaders; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders[a];
if(nbPositionIterations)
solveTable[batch.constraintType](batch, solverConstraintDescs, txInertias, -PX_MAX_F32, elapsedTime, cache);
else
solveConcludeTable[batch.constraintType](batch, solverConstraintDescs, txInertias, elapsedTime, cache);
}
{
for(PxU32 j=0; j<nbSolverBodies; ++j)
Dy::integrateCoreStep(solverBodies[j], txInertias[j], dt);
for(PxU32 j=0; j<nbSolverArticulations; ++j)
{
immArticulation* immArt = static_cast<immArticulation*>(solverArticulations[j]);
immArt->recordDeltaMotion(immArt->getSolverDesc(), dt, deltaV, invTotalDt);
}
}
elapsedTime += dt;
}
for (PxU32 a=0; a<nbSolverArticulations; a++)
{
immArticulation* immArt = static_cast<immArticulation*>(articulations[a]);
immArt->saveVelocityTGS(immArt, invTotalDt);
}
while(nbVelocityIterations--)
{
TGS::solveArticulationInternalConstraints(dt, invDt, nbSolverArticulations, articulations, Z, deltaV, elapsedTime, true);
for(PxU32 a=0; a<nbBatchHeaders; ++a)
{
const PxConstraintBatchHeader& batch = batchHeaders[a];
solveTable[batch.constraintType](batch, solverConstraintDescs, txInertias, 0.0f, elapsedTime, cache);
if(!nbVelocityIterations)
writebackTable[batch.constraintType](batch, solverConstraintDescs, &cache);
}
}
}
void immediate::PxIntegrateSolverBodiesTGS(PxTGSSolverBodyVel* solverBody, PxTGSSolverBodyTxInertia* txInertia, PxTransform* poses, PxU32 nbBodiesToIntegrate, PxReal /*dt*/)
{
for(PxU32 i = 0; i < nbBodiesToIntegrate; ++i)
{
solverBody[i].angularVelocity = txInertia[i].sqrtInvInertia * solverBody[i].angularVelocity;
poses[i].p = txInertia[i].deltaBody2World.p;
poses[i].q = (txInertia[i].deltaBody2World.q * poses[i].q).getNormalized();
}
}
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
#include "BpBroadPhase.h"
#include "PxsHeapMemoryAllocator.h"
#include "PxsKernelWrangler.h"
#include "PxsMemoryManager.h"
PX_COMPILE_TIME_ASSERT(sizeof(Bp::FilterGroup::Enum)==sizeof(PxBpFilterGroup));
PX_IMPLEMENT_OUTPUT_ERROR
PxBpFilterGroup physx::PxGetBroadPhaseStaticFilterGroup()
{
return Bp::getFilterGroup_Statics();
}
PxBpFilterGroup physx::PxGetBroadPhaseDynamicFilterGroup(PxU32 id)
{
return Bp::getFilterGroup_Dynamics(id, false);
}
PxBpFilterGroup physx::PxGetBroadPhaseKinematicFilterGroup(PxU32 id)
{
return Bp::getFilterGroup_Dynamics(id, true);
}
namespace
{
// PT: the Bp::BroadPhase API is quite confusing and the file cannot be included from everywhere
// so let's have a user-friendly wrapper for now.
class ImmCPUBP : public PxBroadPhase, public PxBroadPhaseRegions, public PxUserAllocated
{
public:
ImmCPUBP(const PxBroadPhaseDesc& desc);
virtual ~ImmCPUBP();
virtual bool init(const PxBroadPhaseDesc& desc);
// PxBroadPhase
virtual void release() PX_OVERRIDE;
virtual PxBroadPhaseType::Enum getType() const PX_OVERRIDE;
virtual void getCaps(PxBroadPhaseCaps& caps) const PX_OVERRIDE;
virtual PxBroadPhaseRegions* getRegions() PX_OVERRIDE;
virtual PxAllocatorCallback* getAllocator() PX_OVERRIDE;
virtual PxU64 getContextID() const PX_OVERRIDE;
virtual void setScratchBlock(void* scratchBlock, PxU32 size) PX_OVERRIDE;
virtual void update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchResults(PxBroadPhaseResults& results) PX_OVERRIDE;
//~PxBroadPhase
// PxBroadPhaseRegions
virtual PxU32 getNbRegions() const PX_OVERRIDE;
virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const PX_OVERRIDE;
virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const float* contactDistance) PX_OVERRIDE;
virtual bool removeRegion(PxU32 handle) PX_OVERRIDE;
virtual PxU32 getNbOutOfBoundsObjects() const PX_OVERRIDE;
virtual const PxU32* getOutOfBoundsObjects() const PX_OVERRIDE;
//~PxBroadPhaseRegions
Bp::BroadPhase* mBroadPhase;
PxcScratchAllocator mScratchAllocator;
Bp::BpFilter mFilters;
PxArray<PxBroadPhasePair> mCreatedPairs;
PxArray<PxBroadPhasePair> mDeletedPairs;
const PxU64 mContextID;
void* mAABBManager;
void releaseBP();
};
}
///////////////////////////////////////////////////////////////////////////////
ImmCPUBP::ImmCPUBP(const PxBroadPhaseDesc& desc) :
mBroadPhase (NULL),
mFilters (desc.mDiscardKinematicVsKinematic, desc.mDiscardStaticVsKinematic),
mContextID (desc.mContextID),
mAABBManager(NULL)
{
}
ImmCPUBP::~ImmCPUBP()
{
releaseBP();
}
void ImmCPUBP::releaseBP()
{
PX_RELEASE(mBroadPhase);
}
bool ImmCPUBP::init(const PxBroadPhaseDesc& desc)
{
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxCreateBroadPhase: invalid broadphase descriptor");
const PxU32 maxNbRegions = 0;
const PxU32 maxNbBroadPhaseOverlaps = 0;
const PxU32 maxNbStaticShapes = 0;
const PxU32 maxNbDynamicShapes = 0;
// PT: TODO: unify creation of CPU and GPU BPs (PX-2542)
mBroadPhase = Bp::BroadPhase::create(desc.mType, maxNbRegions, maxNbBroadPhaseOverlaps, maxNbStaticShapes, maxNbDynamicShapes, desc.mContextID);
return mBroadPhase!=NULL;
}
///////////////////////////////////////////////////////////////////////////////
void ImmCPUBP::release()
{
if(mAABBManager)
{
outputError<PxErrorCode::eINVALID_OPERATION>(__LINE__, "ImmCPUBP::release: AABB manager is still present, release the AABB manager first");
return;
}
PX_DELETE_THIS;
}
PxBroadPhaseType::Enum ImmCPUBP::getType() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getType();
}
void ImmCPUBP::getCaps(PxBroadPhaseCaps& caps) const
{
PX_ASSERT(mBroadPhase);
mBroadPhase->getCaps(caps);
}
PxBroadPhaseRegions* ImmCPUBP::getRegions()
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getType() == PxBroadPhaseType::eMBP ? this : NULL;
}
PxAllocatorCallback* ImmCPUBP::getAllocator()
{
return PxGetAllocatorCallback();
}
PxU64 ImmCPUBP::getContextID() const
{
return mContextID;
}
void ImmCPUBP::setScratchBlock(void* scratchBlock, PxU32 size)
{
if(scratchBlock && size)
mScratchAllocator.setBlock(scratchBlock, size);
}
void ImmCPUBP::update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation)
{
PX_PROFILE_ZONE("ImmCPUBP::update", mContextID);
PX_ASSERT(mBroadPhase);
// PT: convert PxBroadPhaseUpdateData to Bp::BroadPhaseUpdateData. Main differences is the two undocumented bools
// added for the GPU version. For now we just set them to true, which may not be the fastest but it should always
// be correct.
// TODO: revisit this / get rid of the bools in the low-level API (PX-2835)
const Bp::BroadPhaseUpdateData defaultUpdateData(
updateData.mCreated, updateData.mNbCreated,
updateData.mUpdated, updateData.mNbUpdated,
updateData.mRemoved, updateData.mNbRemoved,
updateData.mBounds,
reinterpret_cast<const Bp::FilterGroup::Enum*>(updateData.mGroups),
updateData.mDistances, updateData.mCapacity,
mFilters,
true, true);
// PT: preBroadPhase & fetchBroadPhaseResults are only needed for the GPU BP.
// The PxBroadPhase API hides this from users and gives them an easier API that
// deals with these differences under the hood.
mBroadPhase->preBroadPhase(defaultUpdateData); // ### could be skipped for CPU BPs
// PT: BP UPDATE CALL
mBroadPhase->update(&mScratchAllocator, defaultUpdateData, continuation);
mBroadPhase->fetchBroadPhaseResults(); // ### could be skipped for CPU BPs
}
void ImmCPUBP::fetchResults(PxBroadPhaseResults& results)
{
PX_PROFILE_ZONE("ImmCPUBP::fetchResults", mContextID);
PX_ASSERT(mBroadPhase);
// PT: TODO: flags to skip the copies (PX-2929)
if(0)
{
results.mCreatedPairs = reinterpret_cast<const PxBroadPhasePair*>(mBroadPhase->getCreatedPairs(results.mNbCreatedPairs));
results.mDeletedPairs = reinterpret_cast<const PxBroadPhasePair*>(mBroadPhase->getDeletedPairs(results.mNbDeletedPairs));
}
else
{
struct Local
{
static void copyPairs(PxArray<PxBroadPhasePair>& pairs, PxU32 nbPairs, const Bp::BroadPhasePair* bpPairs)
{
pairs.resetOrClear();
const PxBroadPhasePair* src = reinterpret_cast<const PxBroadPhasePair*>(bpPairs);
PxBroadPhasePair* dst = Cm::reserveContainerMemory(pairs, nbPairs);
PxMemCopy(dst, src, sizeof(PxBroadPhasePair)*nbPairs);
}
};
{
PX_PROFILE_ZONE("copyPairs", mContextID);
{
PxU32 nbCreatedPairs;
const Bp::BroadPhasePair* createdPairs = mBroadPhase->getCreatedPairs(nbCreatedPairs);
Local::copyPairs(mCreatedPairs, nbCreatedPairs, createdPairs);
}
{
PxU32 nbDeletedPairs;
const Bp::BroadPhasePair* deletedPairs = mBroadPhase->getDeletedPairs(nbDeletedPairs);
Local::copyPairs(mDeletedPairs, nbDeletedPairs, deletedPairs);
}
}
results.mNbCreatedPairs = mCreatedPairs.size();
results.mNbDeletedPairs = mDeletedPairs.size();
results.mCreatedPairs = mCreatedPairs.begin();
results.mDeletedPairs = mDeletedPairs.begin();
}
// PT: TODO: this function got introduced in the "GRB merge" (CL 20888255) for the SAP but wasn't necessary before,
// and isn't necessary for the other BPs (even the GPU one). That makes no sense and should probably be removed.
//mBroadPhase->deletePairs();
// PT: similarly this is only needed for the SAP. This is also called at the exact same time as "deletePairs" so
// I'm not sure why we used 2 separate functions. It just bloats the API for no reason.
mBroadPhase->freeBuffers();
}
///////////////////////////////////////////////////////////////////////////////
// PT: the following calls are just re-routed to the LL functions. This should only be available/needed for MBP.
PxU32 ImmCPUBP::getNbRegions() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getNbRegions();
}
PxU32 ImmCPUBP::getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex) const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getRegions(userBuffer, bufferSize, startIndex);
}
PxU32 ImmCPUBP::addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* boundsArray, const float* contactDistance)
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->addRegion(region, populateRegion, boundsArray, contactDistance);
}
bool ImmCPUBP::removeRegion(PxU32 handle)
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->removeRegion(handle);
}
PxU32 ImmCPUBP::getNbOutOfBoundsObjects() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getNbOutOfBoundsObjects();
}
const PxU32* ImmCPUBP::getOutOfBoundsObjects() const
{
PX_ASSERT(mBroadPhase);
return mBroadPhase->getOutOfBoundsObjects();
}
///////////////////////////////////////////////////////////////////////////////
#if PX_SUPPORT_GPU_PHYSX
namespace
{
class ImmGPUBP : public ImmCPUBP, public PxAllocatorCallback
{
public:
ImmGPUBP(const PxBroadPhaseDesc& desc);
virtual ~ImmGPUBP();
// PxAllocatorCallback
virtual void* allocate(size_t size, const char* /*typeName*/, const char* filename, int line) PX_OVERRIDE;
virtual void deallocate(void* ptr) PX_OVERRIDE;
//~PxAllocatorCallback
// PxBroadPhase
virtual PxAllocatorCallback* getAllocator() PX_OVERRIDE;
//~PxBroadPhase
// ImmCPUBP
virtual bool init(const PxBroadPhaseDesc& desc) PX_OVERRIDE;
//~ImmCPUBP
PxPhysXGpu* mPxGpu;
PxsMemoryManager* mMemoryManager;
PxsKernelWranglerManager* mGpuWranglerManagers;
PxsHeapMemoryAllocatorManager* mHeapMemoryAllocationManager;
};
}
#endif
///////////////////////////////////////////////////////////////////////////////
#if PX_SUPPORT_GPU_PHYSX
ImmGPUBP::ImmGPUBP(const PxBroadPhaseDesc& desc) :
ImmCPUBP (desc),
mPxGpu (NULL),
mMemoryManager (NULL),
mGpuWranglerManagers (NULL),
mHeapMemoryAllocationManager(NULL)
{
}
ImmGPUBP::~ImmGPUBP()
{
releaseBP(); // PT: must release the BP first, before the base dtor is called
PX_DELETE(mHeapMemoryAllocationManager);
PX_DELETE(mMemoryManager);
//PX_RELEASE(mPxGpu);
PxvReleasePhysXGpu(mPxGpu);
mPxGpu = NULL;
}
void* ImmGPUBP::allocate(size_t size, const char* /*typeName*/, const char* filename, int line)
{
PX_ASSERT(mMemoryManager);
PxVirtualAllocatorCallback* cb = mMemoryManager->getHostMemoryAllocator();
return cb->allocate(size, 0, filename, line);
}
void ImmGPUBP::deallocate(void* ptr)
{
PX_ASSERT(mMemoryManager);
PxVirtualAllocatorCallback* cb = mMemoryManager->getHostMemoryAllocator();
cb->deallocate(ptr);
}
PxAllocatorCallback* ImmGPUBP::getAllocator()
{
return this;
}
bool ImmGPUBP::init(const PxBroadPhaseDesc& desc)
{
PX_ASSERT(desc.mType==PxBroadPhaseType::eGPU);
if(!desc.isValid())
return outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "PxCreateBroadPhase: invalid broadphase descriptor");
PxCudaContextManager* contextManager = desc.mContextManager;
// PT: one issue with PxvGetPhysXGpu is that it creates the whole PxPhysXGpu object, not just the BP. Questionable coupling there.
//mPxGpu = PxCreatePhysXGpu();
mPxGpu = PxvGetPhysXGpu(true);
if(!mPxGpu)
return false;
const PxU32 gpuComputeVersion = 0;
// PT: what's the difference between the "GPU memory manager" and the "GPU heap memory allocator manager" ?
mMemoryManager = mPxGpu->createGpuMemoryManager(contextManager);
if(!mMemoryManager)
return false;
mGpuWranglerManagers = mPxGpu->getGpuKernelWranglerManager(contextManager);
if(!mGpuWranglerManagers)
return false;
PxgDynamicsMemoryConfig gpuDynamicsConfig;
gpuDynamicsConfig.foundLostPairsCapacity = desc.mFoundLostPairsCapacity;
mHeapMemoryAllocationManager = mPxGpu->createGpuHeapMemoryAllocatorManager(gpuDynamicsConfig.heapCapacity, mMemoryManager, gpuComputeVersion);
if(!mHeapMemoryAllocationManager)
return false;
mBroadPhase = mPxGpu->createGpuBroadPhase(mGpuWranglerManagers, contextManager, gpuComputeVersion, gpuDynamicsConfig, mHeapMemoryAllocationManager, desc.mContextID);
return mBroadPhase!=NULL;
}
#endif
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: why don't we even have a PxBroadPhaseDesc in the main Px API by now? (PX-2933)
// The BP parameters are scattered in PxSceneDesc/PxSceneLimits/etc
// The various BP-related APIs are particularly messy.
PxBroadPhase* physx::PxCreateBroadPhase(const PxBroadPhaseDesc& desc)
{
ImmCPUBP* immBP;
if(desc.mType == PxBroadPhaseType::eGPU)
#if PX_SUPPORT_GPU_PHYSX
immBP = PX_NEW(ImmGPUBP)(desc);
#else
return NULL;
#endif
else
immBP = PX_NEW(ImmCPUBP)(desc);
if(!immBP->init(desc))
{
PX_DELETE(immBP);
return NULL;
}
return immBP;
}
namespace
{
// TODO: user-data? (PX-2934)
// TODO: aggregates? (PX-2935)
// TODO: do we really need the bitmaps in this wrapper anyway?
class HighLevelBroadPhaseAPI : public PxAABBManager, public PxUserAllocated
{
public:
HighLevelBroadPhaseAPI(PxBroadPhase& broadphase);
virtual ~HighLevelBroadPhaseAPI();
// PxAABBManager
virtual void release() PX_OVERRIDE { PX_DELETE_THIS; }
virtual void addObject(PxU32 index, const PxBounds3& bounds, PxBpFilterGroup group, float distance) PX_OVERRIDE;
virtual void removeObject(PxU32 index) PX_OVERRIDE;
virtual void updateObject(PxU32 index, const PxBounds3* bounds, const float* distance) PX_OVERRIDE;
virtual void update(PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchResults(PxBroadPhaseResults& results) PX_OVERRIDE;
virtual PxBroadPhase& getBroadPhase() PX_OVERRIDE { return mBroadPhase; }
virtual const PxBounds3* getBounds() const PX_OVERRIDE { return mBounds; }
virtual const float* getDistances() const PX_OVERRIDE { return mDistances; }
virtual const PxBpFilterGroup* getGroups() const PX_OVERRIDE { return mGroups; }
virtual PxU32 getCapacity() const PX_OVERRIDE { return mCapacity; }
//~PxAABBManager
void reserveSpace(PxU32 nbTotalBounds);
PxBroadPhase& mBroadPhase;
PxBounds3* mBounds;
float* mDistances;
PxBpFilterGroup* mGroups;
PxU32 mCapacity; // PT: same capacity for all the above buffers
// PT: TODO: pinned? (PX-2936)
PxBitMap mAddedHandleMap; // PT: indexed by BoundsIndex
PxBitMap mRemovedHandleMap; // PT: indexed by BoundsIndex
PxBitMap mUpdatedHandleMap; // PT: indexed by BoundsIndex
// PT: TODO: pinned? (PX-2936)
PxArray<PxU32> mAddedHandles;
PxArray<PxU32> mUpdatedHandles;
PxArray<PxU32> mRemovedHandles;
const PxU64 mContextID;
};
}
HighLevelBroadPhaseAPI::HighLevelBroadPhaseAPI(PxBroadPhase& broadphase) :
mBroadPhase (broadphase),
mBounds (NULL),
mDistances (NULL),
mGroups (NULL),
mCapacity (0),
mContextID (broadphase.getContextID())
{
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(broadphase);
PX_ASSERT(!baseBP.mAABBManager);
baseBP.mAABBManager = this;
}
HighLevelBroadPhaseAPI::~HighLevelBroadPhaseAPI()
{
PxAllocatorCallback* allocator = mBroadPhase.getAllocator();
if(mDistances)
{
allocator->deallocate(mDistances);
mDistances = NULL;
}
if(mGroups)
{
allocator->deallocate(mGroups);
mGroups = NULL;
}
if(mBounds)
{
allocator->deallocate(mBounds);
mBounds = NULL;
}
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(mBroadPhase);
baseBP.mAABBManager = NULL;
}
void HighLevelBroadPhaseAPI::reserveSpace(PxU32 nbEntriesNeeded)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::reserveSpace", mContextID);
PX_ASSERT(mCapacity<nbEntriesNeeded); // PT: otherwise don't call this function
// PT: allocate more than necessary to minimize the amount of reallocations
nbEntriesNeeded = PxNextPowerOfTwo(nbEntriesNeeded);
// PT: use the allocator provided by the BP, in case we need CUDA-friendly buffers
PxAllocatorCallback* allocator = mBroadPhase.getAllocator();
{
// PT: for bounds we always allocate one more entry to ensure safe SIMD loads
PxBounds3* newBounds = reinterpret_cast<PxBounds3*>(allocator->allocate(sizeof(PxBounds3)*(nbEntriesNeeded+1), "HighLevelBroadPhaseAPI::mBounds", PX_FL));
if(mCapacity && mBounds)
PxMemCopy(newBounds, mBounds, sizeof(PxBounds3)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newBounds[i].setEmpty(); // PT: maybe we could skip this for perf
if(mBounds)
allocator->deallocate(mBounds);
mBounds = newBounds;
}
{
PxBpFilterGroup* newGroups = reinterpret_cast<PxBpFilterGroup*>(allocator->allocate(sizeof(PxBpFilterGroup)*nbEntriesNeeded, "HighLevelBroadPhaseAPI::mGroups", PX_FL));
if(mCapacity && mGroups)
PxMemCopy(newGroups, mGroups, sizeof(PxBpFilterGroup)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newGroups[i] = PX_INVALID_BP_FILTER_GROUP; // PT: maybe we could skip this for perf
if(mGroups)
allocator->deallocate(mGroups);
mGroups = newGroups;
}
{
float* newDistances = reinterpret_cast<float*>(allocator->allocate(sizeof(float)*nbEntriesNeeded, "HighLevelBroadPhaseAPI::mDistances", PX_FL));
if(mCapacity && mDistances)
PxMemCopy(newDistances, mDistances, sizeof(float)*mCapacity);
for(PxU32 i=mCapacity;i<nbEntriesNeeded;i++)
newDistances[i] = 0.0f; // PT: maybe we could skip this for perf
if(mDistances)
allocator->deallocate(mDistances);
mDistances = newDistances;
}
mAddedHandleMap.resize(nbEntriesNeeded);
mRemovedHandleMap.resize(nbEntriesNeeded);
mCapacity = nbEntriesNeeded;
}
// PT: TODO: version with internal index management? (PX-2942)
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::addObject(PxBpIndex index, const PxBounds3& bounds, PxBpFilterGroup group, float distance)
{
PX_ASSERT(group != PX_INVALID_BP_FILTER_GROUP); // PT: we use group == PX_INVALID_BP_FILTER_GROUP to mark removed/invalid entries
const PxU32 nbEntriesNeeded = index + 1;
if(mCapacity<nbEntriesNeeded)
reserveSpace(nbEntriesNeeded);
mBounds[index] = bounds;
mGroups[index] = group;
mDistances[index] = distance;
if(mRemovedHandleMap.test(index))
mRemovedHandleMap.reset(index);
else // PT: for case where an object in the BP gets removed and then we re-add same frame (we don't want to set the add bit in this case)
mAddedHandleMap.set(index);
}
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::removeObject(PxBpIndex index)
{
PX_ASSERT(index < mCapacity);
PX_ASSERT(mGroups[index] != PX_INVALID_BP_FILTER_GROUP);
if(mAddedHandleMap.test(index)) // PT: if object had been added this frame...
mAddedHandleMap.reset(index); // PT: ...then simply revert the previous operation locally (it hasn't been passed to the BP yet).
else
mRemovedHandleMap.set(index); // PT: else we need to remove it from the BP
mBounds[index].setEmpty();
mGroups[index] = PX_INVALID_BP_FILTER_GROUP;
mDistances[index] = 0.0f;
}
// PT: TODO: batched version?
void HighLevelBroadPhaseAPI::updateObject(PxBpIndex index, const PxBounds3* bounds, const float* distance)
{
PX_ASSERT(index < mCapacity);
mUpdatedHandleMap.growAndSet(index);
if(bounds)
mBounds[index] = *bounds;
if(distance)
mDistances[index] = *distance;
}
namespace
{
struct HandleTest_Add
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
PX_ASSERT(bp.mGroups[handle] != PX_INVALID_BP_FILTER_GROUP);
bp.mAddedHandles.pushBack(handle);
}
};
struct HandleTest_Update
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
// PT: TODO: revisit the logic here (PX-2937)
PX_ASSERT(!bp.mRemovedHandleMap.test(handle)); // a handle may only be updated and deleted if it was just added.
if(bp.mAddedHandleMap.test(handle)) // just-inserted handles may also be marked updated, so skip them
return;
PX_ASSERT(bp.mGroups[handle] != PX_INVALID_BP_FILTER_GROUP);
bp.mUpdatedHandles.pushBack(handle);
}
};
struct HandleTest_Remove
{
static PX_FORCE_INLINE void processEntry(HighLevelBroadPhaseAPI& bp, PxU32 handle)
{
PX_ASSERT(bp.mGroups[handle] == PX_INVALID_BP_FILTER_GROUP);
bp.mRemovedHandles.pushBack(handle);
}
};
}
template<class FunctionT, class ParamsT>
static void iterateBitmap(const PxBitMap& bitmap, ParamsT& params)
{
const PxU32* bits = bitmap.getWords();
if(bits)
{
const PxU32 lastSetBit = bitmap.findLast();
for(PxU32 w = 0; w <= lastSetBit >> 5; ++w)
{
for(PxU32 b = bits[w]; b; b &= b-1)
{
const PxU32 index = PxU32(w<<5|PxLowestSetBit(b));
FunctionT::processEntry(params, index);
}
}
}
}
/*static void shuffle(PxArray<PxU32>& handles)
{
PxU32 nb = handles.size();
PxU32* data = handles.begin();
for(PxU32 i=0;i<nb*10;i++)
{
PxU32 id0 = rand() % nb;
PxU32 id1 = rand() % nb;
PxSwap(data[id0], data[id1]);
}
}*/
void HighLevelBroadPhaseAPI::update(PxBaseTask* continuation)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::update", mContextID);
{
PX_PROFILE_ZONE("resetOrClear", mContextID);
mAddedHandles.resetOrClear();
mUpdatedHandles.resetOrClear();
mRemovedHandles.resetOrClear();
}
{
{
PX_PROFILE_ZONE("iterateBitmap added", mContextID);
iterateBitmap<HandleTest_Add>(mAddedHandleMap, *this);
}
{
PX_PROFILE_ZONE("iterateBitmap updated", mContextID);
iterateBitmap<HandleTest_Update>(mUpdatedHandleMap, *this);
}
{
PX_PROFILE_ZONE("iterateBitmap removed", mContextID);
iterateBitmap<HandleTest_Remove>(mRemovedHandleMap, *this);
}
}
// PT: call the low-level BP API
{
PX_PROFILE_ZONE("BP update", mContextID);
/* if(1) // Suffle test
{
shuffle(mAddedHandles);
shuffle(mUpdatedHandles);
shuffle(mRemovedHandles);
}*/
const PxBroadPhaseUpdateData updateData(
mAddedHandles.begin(), mAddedHandles.size(),
mUpdatedHandles.begin(), mUpdatedHandles.size(),
mRemovedHandles.begin(), mRemovedHandles.size(),
mBounds, mGroups, mDistances,
mCapacity);
mBroadPhase.update(updateData, continuation);
}
{
PX_PROFILE_ZONE("clear bitmaps", mContextID);
mAddedHandleMap.clear();
mRemovedHandleMap.clear();
mUpdatedHandleMap.clear();
}
}
void HighLevelBroadPhaseAPI::fetchResults(PxBroadPhaseResults& results)
{
PX_PROFILE_ZONE("HighLevelBroadPhaseAPI::fetchResults", mContextID);
mBroadPhase.fetchResults(results);
}
PxAABBManager* physx::PxCreateAABBManager(PxBroadPhase& bp)
{
// PT: make sure we cannot link a bp to multiple managers
ImmCPUBP& baseBP = static_cast<ImmCPUBP&>(bp);
if(baseBP.mAABBManager)
return NULL;
return PX_NEW(HighLevelBroadPhaseAPI)(bp);
}
|
NVIDIA-Omniverse/PhysX/physx/source/filebuf/include/PsFileBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
#ifndef PSFILEBUFFER_PSFILEBUFFER_H
#define PSFILEBUFFER_PSFILEBUFFER_H
#include "filebuf/PxFileBuf.h"
#include "foundation/PxUserAllocated.h"
#include <stdio.h>
namespace physx
{
namespace general_PxIOStream2
{
//Use this class if you want to use your own allocator
class PxFileBufferBase : public PxFileBuf
{
public:
PxFileBufferBase(const char *fileName,OpenMode mode)
{
mOpenMode = mode;
mFph = NULL;
mFileLength = 0;
mSeekRead = 0;
mSeekWrite = 0;
mSeekCurrent = 0;
switch ( mode )
{
case OPEN_READ_ONLY:
mFph = fopen(fileName,"rb");
break;
case OPEN_WRITE_ONLY:
mFph = fopen(fileName,"wb");
break;
case OPEN_READ_WRITE_NEW:
mFph = fopen(fileName,"wb+");
break;
case OPEN_READ_WRITE_EXISTING:
mFph = fopen(fileName,"rb+");
break;
case OPEN_FILE_NOT_FOUND:
break;
}
if ( mFph )
{
fseek(mFph,0L,SEEK_END);
mFileLength = static_cast<uint32_t>(ftell(mFph));
fseek(mFph,0L,SEEK_SET);
}
else
{
mOpenMode = OPEN_FILE_NOT_FOUND;
}
}
virtual ~PxFileBufferBase()
{
close();
}
virtual void close()
{
if( mFph )
{
fclose(mFph);
mFph = 0;
}
}
virtual SeekType isSeekable(void) const
{
return mSeekType;
}
virtual uint32_t read(void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
setSeekRead();
ret = static_cast<uint32_t>(::fread(buffer,1,size,mFph));
mSeekRead+=ret;
mSeekCurrent+=ret;
}
return ret;
}
virtual uint32_t peek(void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
uint32_t loc = tellRead();
setSeekRead();
ret = static_cast<uint32_t>(::fread(buffer,1,size,mFph));
mSeekCurrent+=ret;
seekRead(loc);
}
return ret;
}
virtual uint32_t write(const void* buffer, uint32_t size)
{
uint32_t ret = 0;
if ( mFph )
{
setSeekWrite();
ret = static_cast<uint32_t>(::fwrite(buffer,1,size,mFph));
mSeekWrite+=ret;
mSeekCurrent+=ret;
if ( mSeekWrite > mFileLength )
{
mFileLength = mSeekWrite;
}
}
return ret;
}
virtual uint32_t tellRead(void) const
{
return mSeekRead;
}
virtual uint32_t tellWrite(void) const
{
return mSeekWrite;
}
virtual uint32_t seekRead(uint32_t loc)
{
mSeekRead = loc;
if ( mSeekRead > mFileLength )
{
mSeekRead = mFileLength;
}
return mSeekRead;
}
virtual uint32_t seekWrite(uint32_t loc)
{
mSeekWrite = loc;
if ( mSeekWrite > mFileLength )
{
mSeekWrite = mFileLength;
}
return mSeekWrite;
}
virtual void flush(void)
{
if ( mFph )
{
::fflush(mFph);
}
}
virtual OpenMode getOpenMode(void) const
{
return mOpenMode;
}
virtual uint32_t getFileLength(void) const
{
return mFileLength;
}
private:
// Moves the actual file pointer to the current read location
void setSeekRead(void)
{
if ( mSeekRead != mSeekCurrent && mFph )
{
if ( mSeekRead >= mFileLength )
{
fseek(mFph,0L,SEEK_END);
}
else
{
fseek(mFph,static_cast<long>(mSeekRead),SEEK_SET);
}
mSeekCurrent = mSeekRead = static_cast<uint32_t>(ftell(mFph));
}
}
// Moves the actual file pointer to the current write location
void setSeekWrite(void)
{
if ( mSeekWrite != mSeekCurrent && mFph )
{
if ( mSeekWrite >= mFileLength )
{
fseek(mFph,0L,SEEK_END);
}
else
{
fseek(mFph,static_cast<long>(mSeekWrite),SEEK_SET);
}
mSeekCurrent = mSeekWrite = static_cast<uint32_t>(ftell(mFph));
}
}
FILE *mFph;
uint32_t mSeekRead;
uint32_t mSeekWrite;
uint32_t mSeekCurrent;
uint32_t mFileLength;
SeekType mSeekType;
OpenMode mOpenMode;
};
//Use this class if you want to use PhysX memory allocator
class PsFileBuffer: public PxFileBufferBase, public PxUserAllocated
{
public:
PsFileBuffer(const char *fileName,OpenMode mode): PxFileBufferBase(fileName, mode) {}
};
}
using namespace general_PxIOStream2;
}
#endif // PSFILEBUFFER_PSFILEBUFFER_H
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThreadContext.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "DyThreadContext.h"
#include "foundation/PxBitUtils.h"
namespace physx
{
namespace Dy
{
ThreadContext::ThreadContext(PxcNpMemBlockPool* memBlockPool):
mFrictionPatchStreamPair(*memBlockPool),
mConstraintBlockManager (*memBlockPool),
mConstraintBlockStream (*memBlockPool),
mNumDifferentBodyConstraints(0),
mNumSelfConstraints(0),
mNumStaticConstraints(0),
mConstraintsPerPartition("ThreadContext::mConstraintsPerPartition"),
mFrictionConstraintsPerPartition("ThreadContext::frictionsConstraintsPerPartition"),
mPartitionNormalizationBitmap("ThreadContext::mPartitionNormalizationBitmap"),
frictionConstraintDescArray("ThreadContext::solverFrictionConstraintArray"),
frictionConstraintBatchHeaders("ThreadContext::frictionConstraintBatchHeaders"),
compoundConstraints("ThreadContext::compoundConstraints"),
orderedContactList("ThreadContext::orderedContactList"),
tempContactList("ThreadContext::tempContactList"),
sortIndexArray("ThreadContext::sortIndexArray"),
mConstraintSize (0),
mAxisConstraintCount(0),
mSelfConstraintBlocks(NULL),
mMaxPartitions(0),
mMaxSolverPositionIterations(0),
mMaxSolverVelocityIterations(0),
mContactDescPtr(NULL),
mFrictionDescPtr(NULL),
mArticulations("ThreadContext::articulations")
{
#if PX_ENABLE_SIM_STATS
mThreadSimStats.clear();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//Defaulted to have space for 16384 bodies
mPartitionNormalizationBitmap.reserve(512);
//Defaulted to have space for 128 partitions (should be more-than-enough)
mConstraintsPerPartition.reserve(128);
}
void ThreadContext::resizeArrays(PxU32 frictionConstraintDescCount, PxU32 articulationCount)
{
// resize resizes smaller arrays to the exact target size, which can generate a lot of churn
frictionConstraintDescArray.forceSize_Unsafe(0);
frictionConstraintDescArray.reserve((frictionConstraintDescCount+63)&~63);
mArticulations.forceSize_Unsafe(0);
mArticulations.reserve(PxMax<PxU32>(PxNextPowerOfTwo(articulationCount), 16));
mArticulations.forceSize_Unsafe(articulationCount);
mContactDescPtr = contactConstraintDescArray;
mFrictionDescPtr = frictionConstraintDescArray.begin();
}
void ThreadContext::reset()
{
// TODO: move these to the PxcNpThreadContext
mFrictionPatchStreamPair.reset();
mConstraintBlockStream.reset();
mContactDescPtr = contactConstraintDescArray;
mFrictionDescPtr = frictionConstraintDescArray.begin();
mAxisConstraintCount = 0;
mMaxSolverPositionIterations = 0;
mMaxSolverVelocityIterations = 0;
mNumDifferentBodyConstraints = 0;
mNumSelfConstraints = 0;
mNumStaticConstraints = 0;
mSelfConstraintBlocks = NULL;
mConstraintSize = 0;
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintsShared.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 DY_SOLVER_CONSTRAINT_SHARED_H
#define DY_SOLVER_CONSTRAINT_SHARED_H
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
namespace physx
{
namespace Dy
{
PX_FORCE_INLINE static FloatV solveDynamicContacts(SolverContactPoint* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
const FloatVArg invMassA, const FloatVArg invMassB, const FloatVArg angDom0, const FloatVArg angDom1, Vec3V& linVel0_, Vec3V& angState0_,
Vec3V& linVel1_, Vec3V& angState1_, PxF32* PX_RESTRICT forceBuffer)
{
Vec3V linVel0 = linVel0_;
Vec3V angState0 = angState0_;
Vec3V linVel1 = linVel1_;
Vec3V angState1 = angState1_;
FloatV accumulatedNormalImpulse = FZero();
const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA);
const Vec3V delLinVel1 = V3Scale(contactNormal, invMassB);
for(PxU32 i=0;i<nbContactPoints;i++)
{
SolverContactPoint& c = contacts[i];
PxPrefetchLine(&contacts[i], 128);
const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW);
const Vec3V rbXn = Vec3V_From_Vec4V(c.rbXn_maxImpulseW);
const FloatV appliedForce = FLoad(forceBuffer[i]);
const FloatV velMultiplier = c.getVelMultiplier();
const FloatV impulseMultiplier = c.getImpulseMultiplier();
/*const FloatV targetVel = c.getTargetVelocity();
const FloatV nScaledBias = c.getScaledBias();*/
const FloatV maxImpulse = c.getMaxImpulse();
//Compute the normal velocity of the constraint.
const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXn));
const Vec3V v1 = V3MulAdd(linVel1, contactNormal, V3Mul(angState1, rbXn));
const FloatV normalVel = V3SumElems(V3Sub(v0, v1));
const FloatV biasedErr = c.getBiasedErr();//FScaleAdd(targetVel, velMultiplier, nScaledBias);
//KS - clamp the maximum force
const FloatV _deltaF = FMax(FNegScaleSub(normalVel, velMultiplier, biasedErr), FNeg(appliedForce));
const FloatV _newForce = FAdd(FMul(impulseMultiplier, appliedForce), _deltaF);
const FloatV newForce = FMin(_newForce, maxImpulse);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
angState1 = V3NegScaleSub(rbXn, FMul(deltaF, angDom1), angState1);
FStore(newForce, &forceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce);
}
linVel0_ = linVel0;
angState0_ = angState0;
linVel1_ = linVel1;
angState1_ = angState1;
return accumulatedNormalImpulse;
}
PX_FORCE_INLINE static FloatV solveStaticContacts(SolverContactPoint* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
const FloatVArg invMassA, const FloatVArg angDom0, Vec3V& linVel0_, Vec3V& angState0_, PxF32* PX_RESTRICT forceBuffer)
{
Vec3V linVel0 = linVel0_;
Vec3V angState0 = angState0_;
FloatV accumulatedNormalImpulse = FZero();
const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA);
for(PxU32 i=0;i<nbContactPoints;i++)
{
SolverContactPoint& c = contacts[i];
PxPrefetchLine(&contacts[i],128);
const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW);
const FloatV appliedForce = FLoad(forceBuffer[i]);
const FloatV velMultiplier = c.getVelMultiplier();
const FloatV impulseMultiplier = c.getImpulseMultiplier();
/*const FloatV targetVel = c.getTargetVelocity();
const FloatV nScaledBias = c.getScaledBias();*/
const FloatV maxImpulse = c.getMaxImpulse();
const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXn));
const FloatV normalVel = V3SumElems(v0);
const FloatV biasedErr = c.getBiasedErr();//FScaleAdd(targetVel, velMultiplier, nScaledBias);
// still lots to do here: using loop pipelining we can interweave this code with the
// above - the code here has a lot of stalls that we would thereby eliminate
const FloatV _deltaF = FMax(FNegScaleSub(normalVel, velMultiplier, biasedErr), FNeg(appliedForce));
const FloatV _newForce = FAdd(FMul(appliedForce, impulseMultiplier), _deltaF);
const FloatV newForce = FMin(_newForce, maxImpulse);
const FloatV deltaF = FSub(newForce, appliedForce);
linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0);
angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0);
FStore(newForce, &forceBuffer[i]);
accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce);
}
linVel0_ = linVel0;
angState0_ = angState0;
return accumulatedNormalImpulse;
}
FloatV solveExtContacts(SolverContactPointExt* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal,
Vec3V& linVel0, Vec3V& angVel0,
Vec3V& linVel1, Vec3V& angVel1,
Vec3V& li0, Vec3V& ai0,
Vec3V& li1, Vec3V& ai1,
PxF32* PX_RESTRICT appliedForceBuffer);
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep4.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace aos;
namespace physx
{
namespace Dy
{
PxcCreateFinalizeSolverContactMethod4 createFinalizeMethods4[3] =
{
createFinalizeSolverContacts4,
createFinalizeSolverContacts4Coulomb1D,
createFinalizeSolverContacts4Coulomb2D
};
inline bool ValidateVec4(const Vec4V v)
{
PX_ALIGN(16, PxVec4 vF);
aos::V4StoreA(v, &vF.x);
return vF.isFinite();
}
static void setupFinalizeSolverConstraints4(PxSolverContactDesc* PX_RESTRICT descs, CorrelationBuffer& c, PxU8* PX_RESTRICT workspace,
PxReal invDtF32, PxReal dtF32, PxReal bounceThresholdF32,
const aos::Vec4VArg invMassScale0, const aos::Vec4VArg invInertiaScale0,
const aos::Vec4VArg invMassScale1, const aos::Vec4VArg invInertiaScale1)
{
//OK, we have a workspace of pre-allocated space to store all 4 descs in. We now need to create the constraints in it
const Vec4V ccdMaxSeparation = aos::V4LoadXYZW(descs[0].maxCCDSeparation, descs[1].maxCCDSeparation, descs[2].maxCCDSeparation, descs[3].maxCCDSeparation);
const Vec4V solverOffsetSlop = aos::V4LoadXYZW(descs[0].offsetSlop, descs[1].offsetSlop, descs[2].offsetSlop, descs[3].offsetSlop);
const Vec4V zero = V4Zero();
const BoolV bFalse = BFFFF();
const BoolV bTrue = BTTTT();
const FloatV fZero = FZero();
const PxU8 flags[4] = { PxU8(descs[0].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[1].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[2].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0),
PxU8(descs[3].hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0) };
bool hasMaxImpulse = descs[0].hasMaxImpulse || descs[1].hasMaxImpulse || descs[2].hasMaxImpulse || descs[3].hasMaxImpulse;
//The block is dynamic if **any** of the constraints have a non-static body B. This allows us to batch static and non-static constraints but we only get a memory/perf
//saving if all 4 are static. This simplifies the constraint partitioning such that it only needs to care about separating contacts and 1D constraints (which it already does)
bool isDynamic = false;
bool hasKinematic = false;
for(PxU32 a = 0; a < 4; ++a)
{
isDynamic = isDynamic || (descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY);
hasKinematic = hasKinematic || descs[a].bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY;
}
const PxU32 constraintSize = isDynamic ? sizeof(SolverContactBatchPointDynamic4) : sizeof(SolverContactBatchPointBase4);
const PxU32 frictionSize = isDynamic ? sizeof(SolverContactFrictionDynamic4) : sizeof(SolverContactFrictionBase4);
PxU8* PX_RESTRICT ptr = workspace;
const Vec4V dom0 = invMassScale0;
const Vec4V dom1 = invMassScale1;
const Vec4V angDom0 = invInertiaScale0;
const Vec4V angDom1 = invInertiaScale1;
const Vec4V maxPenBias = V4Max(V4LoadXYZW(descs[0].data0->penBiasClamp, descs[1].data0->penBiasClamp,
descs[2].data0->penBiasClamp, descs[3].data0->penBiasClamp),
V4LoadXYZW(descs[0].data1->penBiasClamp, descs[1].data1->penBiasClamp,
descs[2].data1->penBiasClamp, descs[3].data1->penBiasClamp));
const Vec4V restDistance = V4LoadXYZW(descs[0].restDistance, descs[1].restDistance, descs[2].restDistance,
descs[3].restDistance);
//load up velocities
Vec4V linVel00 = V4LoadA(&descs[0].data0->linearVelocity.x);
Vec4V linVel10 = V4LoadA(&descs[1].data0->linearVelocity.x);
Vec4V linVel20 = V4LoadA(&descs[2].data0->linearVelocity.x);
Vec4V linVel30 = V4LoadA(&descs[3].data0->linearVelocity.x);
Vec4V linVel01 = V4LoadA(&descs[0].data1->linearVelocity.x);
Vec4V linVel11 = V4LoadA(&descs[1].data1->linearVelocity.x);
Vec4V linVel21 = V4LoadA(&descs[2].data1->linearVelocity.x);
Vec4V linVel31 = V4LoadA(&descs[3].data1->linearVelocity.x);
Vec4V angVel00 = V4LoadA(&descs[0].data0->angularVelocity.x);
Vec4V angVel10 = V4LoadA(&descs[1].data0->angularVelocity.x);
Vec4V angVel20 = V4LoadA(&descs[2].data0->angularVelocity.x);
Vec4V angVel30 = V4LoadA(&descs[3].data0->angularVelocity.x);
Vec4V angVel01 = V4LoadA(&descs[0].data1->angularVelocity.x);
Vec4V angVel11 = V4LoadA(&descs[1].data1->angularVelocity.x);
Vec4V angVel21 = V4LoadA(&descs[2].data1->angularVelocity.x);
Vec4V angVel31 = V4LoadA(&descs[3].data1->angularVelocity.x);
Vec4V linVelT00, linVelT10, linVelT20;
Vec4V linVelT01, linVelT11, linVelT21;
Vec4V angVelT00, angVelT10, angVelT20;
Vec4V angVelT01, angVelT11, angVelT21;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVelT00, linVelT10, linVelT20);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVelT01, linVelT11, linVelT21);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVelT00, angVelT10, angVelT20);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVelT01, angVelT11, angVelT21);
const Vec4V vrelX = V4Sub(linVelT00, linVelT01);
const Vec4V vrelY = V4Sub(linVelT10, linVelT11);
const Vec4V vrelZ = V4Sub(linVelT20, linVelT21);
//Load up masses and invInertia
/*const Vec4V sqrtInvMass0 = V4Merge(FLoad(descs[0].data0->sqrtInvMass), FLoad(descs[1].data0->sqrtInvMass), FLoad(descs[2].data0->sqrtInvMass),
FLoad(descs[3].data0->sqrtInvMass));
const Vec4V sqrtInvMass1 = V4Merge(FLoad(descs[0].data1->sqrtInvMass), FLoad(descs[1].data1->sqrtInvMass), FLoad(descs[2].data1->sqrtInvMass),
FLoad(descs[3].data1->sqrtInvMass));*/
const Vec4V invMass0 = V4LoadXYZW(descs[0].data0->invMass, descs[1].data0->invMass, descs[2].data0->invMass, descs[3].data0->invMass);
const Vec4V invMass1 = V4LoadXYZW(descs[0].data1->invMass, descs[1].data1->invMass, descs[2].data1->invMass, descs[3].data1->invMass);
const Vec4V invMass0D0 = V4Mul(dom0, invMass0);
const Vec4V invMass1D1 = V4Mul(dom1, invMass1);
Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column2));
Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column2));
Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column2));
Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data0->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column2));
Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column2));
Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column2));
Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column2));
Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33
Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].data1->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33
Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column2));
Vec4V invInertia0X0, invInertia0X1, invInertia0X2;
Vec4V invInertia0Y0, invInertia0Y1, invInertia0Y2;
Vec4V invInertia0Z0, invInertia0Z1, invInertia0Z2;
Vec4V invInertia1X0, invInertia1X1, invInertia1X2;
Vec4V invInertia1Y0, invInertia1Y1, invInertia1Y2;
Vec4V invInertia1Z0, invInertia1Z1, invInertia1Z2;
PX_TRANSPOSE_44_34(invInertia00X, invInertia10X, invInertia20X, invInertia30X, invInertia0X0, invInertia0Y0, invInertia0Z0);
PX_TRANSPOSE_44_34(invInertia00Y, invInertia10Y, invInertia20Y, invInertia30Y, invInertia0X1, invInertia0Y1, invInertia0Z1);
PX_TRANSPOSE_44_34(invInertia00Z, invInertia10Z, invInertia20Z, invInertia30Z, invInertia0X2, invInertia0Y2, invInertia0Z2);
PX_TRANSPOSE_44_34(invInertia01X, invInertia11X, invInertia21X, invInertia31X, invInertia1X0, invInertia1Y0, invInertia1Z0);
PX_TRANSPOSE_44_34(invInertia01Y, invInertia11Y, invInertia21Y, invInertia31Y, invInertia1X1, invInertia1Y1, invInertia1Z1);
PX_TRANSPOSE_44_34(invInertia01Z, invInertia11Z, invInertia21Z, invInertia31Z, invInertia1X2, invInertia1Y2, invInertia1Z2);
const FloatV invDt = FLoad(invDtF32);
const FloatV dt = FLoad(dtF32);
const FloatV p8 = FLoad(0.8f);
const Vec4V p84 = V4Splat(p8);
const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32));
const FloatV invDtp8 = FMul(invDt, p8);
const Vec3V bodyFrame00p = V3LoadU(descs[0].bodyFrame0.p);
const Vec3V bodyFrame01p = V3LoadU(descs[1].bodyFrame0.p);
const Vec3V bodyFrame02p = V3LoadU(descs[2].bodyFrame0.p);
const Vec3V bodyFrame03p = V3LoadU(descs[3].bodyFrame0.p);
Vec4V bodyFrame00p4 = Vec4V_From_Vec3V(bodyFrame00p);
Vec4V bodyFrame01p4 = Vec4V_From_Vec3V(bodyFrame01p);
Vec4V bodyFrame02p4 = Vec4V_From_Vec3V(bodyFrame02p);
Vec4V bodyFrame03p4 = Vec4V_From_Vec3V(bodyFrame03p);
Vec4V bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ;
PX_TRANSPOSE_44_34(bodyFrame00p4, bodyFrame01p4, bodyFrame02p4, bodyFrame03p4, bodyFrame0pX, bodyFrame0pY, bodyFrame0pZ);
const Vec3V bodyFrame10p = V3LoadU(descs[0].bodyFrame1.p);
const Vec3V bodyFrame11p = V3LoadU(descs[1].bodyFrame1.p);
const Vec3V bodyFrame12p = V3LoadU(descs[2].bodyFrame1.p);
const Vec3V bodyFrame13p = V3LoadU(descs[3].bodyFrame1.p);
Vec4V bodyFrame10p4 = Vec4V_From_Vec3V(bodyFrame10p);
Vec4V bodyFrame11p4 = Vec4V_From_Vec3V(bodyFrame11p);
Vec4V bodyFrame12p4 = Vec4V_From_Vec3V(bodyFrame12p);
Vec4V bodyFrame13p4 = Vec4V_From_Vec3V(bodyFrame13p);
Vec4V bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ;
PX_TRANSPOSE_44_34(bodyFrame10p4, bodyFrame11p4, bodyFrame12p4, bodyFrame13p4, bodyFrame1pX, bodyFrame1pY, bodyFrame1pZ);
const QuatV bodyFrame00q = QuatVLoadU(&descs[0].bodyFrame0.q.x);
const QuatV bodyFrame01q = QuatVLoadU(&descs[1].bodyFrame0.q.x);
const QuatV bodyFrame02q = QuatVLoadU(&descs[2].bodyFrame0.q.x);
const QuatV bodyFrame03q = QuatVLoadU(&descs[3].bodyFrame0.q.x);
const QuatV bodyFrame10q = QuatVLoadU(&descs[0].bodyFrame1.q.x);
const QuatV bodyFrame11q = QuatVLoadU(&descs[1].bodyFrame1.q.x);
const QuatV bodyFrame12q = QuatVLoadU(&descs[2].bodyFrame1.q.x);
const QuatV bodyFrame13q = QuatVLoadU(&descs[3].bodyFrame1.q.x);
PxU32 frictionPatchWritebackAddrIndex0 = 0;
PxU32 frictionPatchWritebackAddrIndex1 = 0;
PxU32 frictionPatchWritebackAddrIndex2 = 0;
PxU32 frictionPatchWritebackAddrIndex3 = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0;
//PxU32 contactIndex0 = 0, contactIndex1 = 0, contactIndex2 = 0, contactIndex3 = 0;
//OK, we iterate through all friction patch counts in the constraint patch, building up the constraint list etc.
PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches)));
const Vec4V p1 = V4Splat(FLoad(0.0001f));
const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f));
PxU32 contact0 = 0, contact1 = 0, contact2 = 0, contact3 = 0;
PxU32 patch0 = 0, patch1 = 0, patch2 = 0, patch3 = 0;
PxU8 flag = 0;
if(hasMaxImpulse)
flag |= SolverContactHeader4::eHAS_MAX_IMPULSE;
bool hasFinished[4];
for(PxU32 i=0;i<maxPatches;i++)
{
hasFinished[0] = i >= descs[0].numFrictionPatches;
hasFinished[1] = i >= descs[1].numFrictionPatches;
hasFinished[2] = i >= descs[2].numFrictionPatches;
hasFinished[3] = i >= descs[3].numFrictionPatches;
frictionIndex0 = hasFinished[0] ? frictionIndex0 : descs[0].startFrictionPatchIndex + i;
frictionIndex1 = hasFinished[1] ? frictionIndex1 : descs[1].startFrictionPatchIndex + i;
frictionIndex2 = hasFinished[2] ? frictionIndex2 : descs[2].startFrictionPatchIndex + i;
frictionIndex3 = hasFinished[3] ? frictionIndex3 : descs[3].startFrictionPatchIndex + i;
const PxU32 clampedContacts0 = hasFinished[0] ? 0 : c.frictionPatchContactCounts[frictionIndex0];
const PxU32 clampedContacts1 = hasFinished[1] ? 0 : c.frictionPatchContactCounts[frictionIndex1];
const PxU32 clampedContacts2 = hasFinished[2] ? 0 : c.frictionPatchContactCounts[frictionIndex2];
const PxU32 clampedContacts3 = hasFinished[3] ? 0 : c.frictionPatchContactCounts[frictionIndex3];
const PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0];
const PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1];
const PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2];
const PxU32 firstPatch3 = c.correlationListHeads[frictionIndex3];
const PxContactPoint* contactBase0 = descs[0].contacts + c.contactPatches[firstPatch0].start;
const PxContactPoint* contactBase1 = descs[1].contacts + c.contactPatches[firstPatch1].start;
const PxContactPoint* contactBase2 = descs[2].contacts + c.contactPatches[firstPatch2].start;
const PxContactPoint* contactBase3 = descs[3].contacts + c.contactPatches[firstPatch3].start;
const Vec4V restitution = V4Neg(V4LoadXYZW(contactBase0->restitution, contactBase1->restitution, contactBase2->restitution,
contactBase3->restitution));
const Vec4V damping = V4LoadXYZW(contactBase0->damping, contactBase1->damping, contactBase2->damping, contactBase3->damping);
SolverContactHeader4* PX_RESTRICT header = reinterpret_cast<SolverContactHeader4*>(ptr);
ptr += sizeof(SolverContactHeader4);
header->flags[0] = flags[0];
header->flags[1] = flags[1];
header->flags[2] = flags[2];
header->flags[3] = flags[3];
header->flag = flag;
PxU32 totalContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3)));
Vec4V* PX_RESTRICT appliedNormalForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*totalContacts;
PxMemZero(appliedNormalForces, sizeof(Vec4V) * totalContacts);
header->numNormalConstr = PxTo8(totalContacts);
header->numNormalConstr0 = PxTo8(clampedContacts0);
header->numNormalConstr1 = PxTo8(clampedContacts1);
header->numNormalConstr2 = PxTo8(clampedContacts2);
header->numNormalConstr3 = PxTo8(clampedContacts3);
//header->sqrtInvMassA = sqrtInvMass0;
//header->sqrtInvMassB = sqrtInvMass1;
header->invMass0D0 = invMass0D0;
header->invMass1D1 = invMass1D1;
header->angDom0 = angDom0;
header->angDom1 = angDom1;
header->shapeInteraction[0] = getInteraction(descs[0]); header->shapeInteraction[1] = getInteraction(descs[1]);
header->shapeInteraction[2] = getInteraction(descs[2]); header->shapeInteraction[3] = getInteraction(descs[3]);
Vec4V* maxImpulse = reinterpret_cast<Vec4V*>(ptr + constraintSize * totalContacts);
header->restitution = restitution;
Vec4V normal0 = V4LoadA(&contactBase0->normal.x);
Vec4V normal1 = V4LoadA(&contactBase1->normal.x);
Vec4V normal2 = V4LoadA(&contactBase2->normal.x);
Vec4V normal3 = V4LoadA(&contactBase3->normal.x);
Vec4V normalX, normalY, normalZ;
PX_TRANSPOSE_44_34(normal0, normal1, normal2, normal3, normalX, normalY, normalZ);
PX_ASSERT(ValidateVec4(normalX));
PX_ASSERT(ValidateVec4(normalY));
PX_ASSERT(ValidateVec4(normalZ));
header->normalX = normalX;
header->normalY = normalY;
header->normalZ = normalZ;
const Vec4V norVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00)));
const Vec4V norVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01)));
const Vec4V relNorVel = V4Sub(norVel0, norVel1);
//For all correlation heads - need to pull this out I think
//OK, we have a counter for all our patches...
PxU32 finished = (PxU32(hasFinished[0])) |
((PxU32(hasFinished[1])) << 1) |
((PxU32(hasFinished[2])) << 2) |
((PxU32(hasFinished[3])) << 3);
CorrelationListIterator iter0(c, firstPatch0);
CorrelationListIterator iter1(c, firstPatch1);
CorrelationListIterator iter2(c, firstPatch2);
CorrelationListIterator iter3(c, firstPatch3);
//PxU32 contact0, contact1, contact2, contact3;
//PxU32 patch0, patch1, patch2, patch3;
if(!hasFinished[0])
iter0.nextContact(patch0, contact0);
if(!hasFinished[1])
iter1.nextContact(patch1, contact1);
if(!hasFinished[2])
iter2.nextContact(patch2, contact2);
if(!hasFinished[3])
iter3.nextContact(patch3, contact3);
PxU8* p = ptr;
PxU32 contactCount = 0;
PxU32 newFinished =
( PxU32(hasFinished[0] || !iter0.hasNextContact())) |
((PxU32(hasFinished[1] || !iter1.hasNextContact())) << 1) |
((PxU32(hasFinished[2] || !iter2.hasNextContact())) << 2) |
((PxU32(hasFinished[3] || !iter3.hasNextContact())) << 3);
// finished flags are used to be able to handle pairs with varying number
// of contact points in the same loop
BoolV bFinished = BLoad(hasFinished);
while(finished != 0xf)
{
finished = newFinished;
++contactCount;
PxPrefetchLine(p, 384);
PxPrefetchLine(p, 512);
PxPrefetchLine(p, 640);
SolverContactBatchPointBase4* PX_RESTRICT solverContact = reinterpret_cast<SolverContactBatchPointBase4*>(p);
p += constraintSize;
const PxContactPoint& con0 = descs[0].contacts[c.contactPatches[patch0].start + contact0];
const PxContactPoint& con1 = descs[1].contacts[c.contactPatches[patch1].start + contact1];
const PxContactPoint& con2 = descs[2].contacts[c.contactPatches[patch2].start + contact2];
const PxContactPoint& con3 = descs[3].contacts[c.contactPatches[patch3].start + contact3];
//Now we need to splice these 4 contacts into a single structure
{
Vec4V point0 = V4LoadA(&con0.point.x);
Vec4V point1 = V4LoadA(&con1.point.x);
Vec4V point2 = V4LoadA(&con2.point.x);
Vec4V point3 = V4LoadA(&con3.point.x);
Vec4V pointX, pointY, pointZ;
PX_TRANSPOSE_44_34(point0, point1, point2, point3, pointX, pointY, pointZ);
PX_ASSERT(ValidateVec4(pointX));
PX_ASSERT(ValidateVec4(pointY));
PX_ASSERT(ValidateVec4(pointZ));
Vec4V cTargetVel0 = V4LoadA(&con0.targetVel.x);
Vec4V cTargetVel1 = V4LoadA(&con1.targetVel.x);
Vec4V cTargetVel2 = V4LoadA(&con2.targetVel.x);
Vec4V cTargetVel3 = V4LoadA(&con3.targetVel.x);
Vec4V cTargetVelX, cTargetVelY, cTargetVelZ;
PX_TRANSPOSE_44_34(cTargetVel0, cTargetVel1, cTargetVel2, cTargetVel3, cTargetVelX, cTargetVelY, cTargetVelZ);
const Vec4V separation = V4LoadXYZW(con0.separation, con1.separation, con2.separation, con3.separation);
const Vec4V cTargetNorVel = V4MulAdd(cTargetVelX, normalX, V4MulAdd(cTargetVelY, normalY, V4Mul(cTargetVelZ, normalZ)));
const Vec4V raX = V4Sub(pointX, bodyFrame0pX);
const Vec4V raY = V4Sub(pointY, bodyFrame0pY);
const Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ);
const Vec4V rbX = V4Sub(pointX, bodyFrame1pX);
const Vec4V rbY = V4Sub(pointY, bodyFrame1pY);
const Vec4V rbZ = V4Sub(pointZ, bodyFrame1pZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);
rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
PX_ASSERT(ValidateVec4(raX));
PX_ASSERT(ValidateVec4(raY));
PX_ASSERT(ValidateVec4(raZ));
PX_ASSERT(ValidateVec4(rbX));
PX_ASSERT(ValidateVec4(rbY));
PX_ASSERT(ValidateVec4(rbZ));
//raXn = cross(ra, normal) which = Vec3V( a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x);
Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ));
Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX));
Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY));
Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ));
Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX));
Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY));
Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
Vec4V relAng = V4Sub(dotRaXnAngVel0, dotRbXnAngVel1);
const Vec4V slop = V4Mul(solverOffsetSlop, V4Max(V4Sel(V4IsEq(relNorVel, zero), V4Splat(FMax()), V4Div(relAng, relNorVel)), V4One()));
raXnX = V4Sel(V4IsGrtr(slop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(slop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(slop, V4Abs(raXnZ)), zero, raXnZ);
rbXnX = V4Sel(V4IsGrtr(slop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(slop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(slop, V4Abs(rbXnZ)), zero, rbXnZ);
//Re-do this because we need an accurate and updated angular velocity
dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00)));
dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01)));
relAng = V4Sub(dotRaXnAngVel0, dotRbXnAngVel1);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
PX_ASSERT(ValidateVec4(delAngVel0X));
PX_ASSERT(ValidateVec4(delAngVel0Y));
PX_ASSERT(ValidateVec4(delAngVel0Z));
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z)));
Vec4V unitResponse = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
Vec4V vrel = V4Add(relNorVel, relAng);
//The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much
if(isDynamic)
{
SolverContactBatchPointDynamic4* PX_RESTRICT dynamicContact = static_cast<SolverContactBatchPointDynamic4*>(solverContact);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
PX_ASSERT(ValidateVec4(delAngVel1X));
PX_ASSERT(ValidateVec4(delAngVel1Y));
PX_ASSERT(ValidateVec4(delAngVel1Z));
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
unitResponse = V4Add(unitResponse, resp1);
//These are for dynamic-only contacts.
dynamicContact->rbXnX = delAngVel1X;
dynamicContact->rbXnY = delAngVel1Y;
dynamicContact->rbXnZ = delAngVel1Z;
}
const Vec4V penetration = V4Sub(separation, restDistance);
const Vec4V penInvDtPt8 = V4Max(maxPenBias, V4Scale(penetration, invDtp8));
//..././....
const BoolV isCompliant = V4IsGrtr(restitution, zero);
const Vec4V rdt = V4Scale(restitution, dt);
const Vec4V a = V4Scale(V4Add(damping, rdt), dt);
const Vec4V b = V4Scale(V4Mul(restitution, penetration), dt);
const Vec4V x = V4Recip(V4MulAdd(a, unitResponse, V4One()));
const Vec4V velMultiplier = V4Sel(isCompliant, V4Mul(x, a), V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero));
const Vec4V impulseMultiplier = V4Sub(V4One(), V4Sel(isCompliant, x, zero));
Vec4V scaledBias = V4Mul(penInvDtPt8, velMultiplier);
const Vec4V penetrationInvDt = V4Scale(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(zero, restitution), V4IsGrtr(bounceThreshold, vrel)),
V4IsGrtr(V4Neg(vrel), penetrationInvDt));
const BoolV ccdSeparationCondition = V4IsGrtrOrEq(ccdMaxSeparation, penetration);
scaledBias = V4Neg(V4Sel(isCompliant, V4Mul(x, b), V4Sel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias)));
const Vec4V targetVelocity = V4Mul(V4Add(V4Sub(cTargetNorVel, vrel), V4Sel(isGreater2, V4Mul(vrel, restitution), zero)), velMultiplier);
const Vec4V biasedErr = V4Add(targetVelocity, scaledBias);
//These values are present for static and dynamic contacts
solverContact->raXnX = delAngVel0X;
solverContact->raXnY = delAngVel0Y;
solverContact->raXnZ = delAngVel0Z;
solverContact->velMultiplier = V4Sel(bFinished, zero, velMultiplier);
solverContact->biasedErr = V4Sel(bFinished, zero, biasedErr);
solverContact->impulseMultiplier = impulseMultiplier;
//solverContact->scaledBias = V4Max(zero, scaledBias);
solverContact->scaledBias = V4Sel(BOr(bFinished, isCompliant), zero, V4Sel(isGreater2, scaledBias, V4Max(zero, scaledBias)));
if(hasMaxImpulse)
{
maxImpulse[contactCount-1] = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse),
FLoad(con3.maxImpulse));
}
}
// update the finished flags
if (!(finished & 0x1))
{
iter0.nextContact(patch0, contact0);
newFinished |= PxU32(!iter0.hasNextContact());
}
else
bFinished = BSetX(bFinished, bTrue);
if(!(finished & 0x2))
{
iter1.nextContact(patch1, contact1);
newFinished |= (PxU32(!iter1.hasNextContact()) << 1);
}
else
bFinished = BSetY(bFinished, bTrue);
if(!(finished & 0x4))
{
iter2.nextContact(patch2, contact2);
newFinished |= (PxU32(!iter2.hasNextContact()) << 2);
}
else
bFinished = BSetZ(bFinished, bTrue);
if(!(finished & 0x8))
{
iter3.nextContact(patch3, contact3);
newFinished |= (PxU32(!iter3.hasNextContact()) << 3);
}
else
bFinished = BSetW(bFinished, bTrue);
}
ptr = p;
if(hasMaxImpulse)
{
ptr += sizeof(Vec4V) * totalContacts;
}
//OK...friction time :-)
Vec4V maxImpulseScale = V4One();
{
const FrictionPatch& frictionPatch0 = c.frictionPatches[frictionIndex0];
const FrictionPatch& frictionPatch1 = c.frictionPatches[frictionIndex1];
const FrictionPatch& frictionPatch2 = c.frictionPatches[frictionIndex2];
const FrictionPatch& frictionPatch3 = c.frictionPatches[frictionIndex3];
const PxU32 anchorCount0 = frictionPatch0.anchorCount;
const PxU32 anchorCount1 = frictionPatch1.anchorCount;
const PxU32 anchorCount2 = frictionPatch2.anchorCount;
const PxU32 anchorCount3 = frictionPatch3.anchorCount;
const PxU32 clampedAnchorCount0 = hasFinished[0] || (contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount0;
const PxU32 clampedAnchorCount1 = hasFinished[1] || (contactBase1->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount1;
const PxU32 clampedAnchorCount2 = hasFinished[2] || (contactBase2->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount2;
const PxU32 clampedAnchorCount3 = hasFinished[3] || (contactBase3->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount3;
const PxU32 maxAnchorCount = PxMax(clampedAnchorCount0, PxMax(clampedAnchorCount1, PxMax(clampedAnchorCount2, clampedAnchorCount3)));
const PxReal coefficient0 = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount0 == 2) ? 0.5f : 1.f;
const PxReal coefficient1 = (contactBase1->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount1 == 2) ? 0.5f : 1.f;
const PxReal coefficient2 = (contactBase2->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount2 == 2) ? 0.5f : 1.f;
const PxReal coefficient3 = (contactBase3->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && anchorCount3 == 2) ? 0.5f : 1.f;
const Vec4V staticFriction = V4LoadXYZW(contactBase0->staticFriction*coefficient0, contactBase1->staticFriction*coefficient1,
contactBase2->staticFriction*coefficient2, contactBase3->staticFriction*coefficient3);
const Vec4V dynamicFriction = V4LoadXYZW(contactBase0->dynamicFriction*coefficient0, contactBase1->dynamicFriction*coefficient1,
contactBase2->dynamicFriction*coefficient2, contactBase3->dynamicFriction*coefficient3);
PX_ASSERT(totalContacts == contactCount);
header->dynamicFriction = dynamicFriction;
header->staticFriction = staticFriction;
//if(clampedAnchorCount0 != clampedAnchorCount1 || clampedAnchorCount0 != clampedAnchorCount2 || clampedAnchorCount0 != clampedAnchorCount3)
// PxDebugBreak();
//const bool haveFriction = maxAnchorCount != 0;
header->numFrictionConstr = PxTo8(maxAnchorCount*2);
header->numFrictionConstr0 = PxTo8(clampedAnchorCount0*2);
header->numFrictionConstr1 = PxTo8(clampedAnchorCount1*2);
header->numFrictionConstr2 = PxTo8(clampedAnchorCount2*2);
header->numFrictionConstr3 = PxTo8(clampedAnchorCount3*2);
//KS - TODO - extend this if needed
header->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_RB_CONTACT : DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT);
if(maxAnchorCount)
{
//Allocate the shared friction data...
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(ptr);
ptr += sizeof(SolverFrictionSharedData4);
PX_UNUSED(fd);
const BoolV cond = V4IsGrtr(orthoThreshold, V4Abs(normalX));
const Vec4V t0FallbackX = V4Sel(cond, zero, V4Neg(normalY));
const Vec4V t0FallbackY = V4Sel(cond, V4Neg(normalZ), normalX);
const Vec4V t0FallbackZ = V4Sel(cond, normalY, zero);
//const Vec4V dotNormalVrel = V4MulAdd(normalZ, vrelZ, V4MulAdd(normalY, vrelY, V4Mul(normalX, vrelX)));
const Vec4V vrelSubNorVelX = V4NegMulSub(normalX, relNorVel, vrelX);
const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, relNorVel, vrelY);
const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, relNorVel, vrelZ);
const Vec4V lenSqvrelSubNorVelZ = V4MulAdd(vrelSubNorVelX, vrelSubNorVelX, V4MulAdd(vrelSubNorVelY, vrelSubNorVelY, V4Mul(vrelSubNorVelZ, vrelSubNorVelZ)));
const BoolV bcon2 = V4IsGrtr(lenSqvrelSubNorVelZ, p1);
Vec4V t0X = V4Sel(bcon2, vrelSubNorVelX, t0FallbackX);
Vec4V t0Y = V4Sel(bcon2, vrelSubNorVelY, t0FallbackY);
Vec4V t0Z = V4Sel(bcon2, vrelSubNorVelZ, t0FallbackZ);
//Now normalize this...
const Vec4V recipLen = V4Rsqrt(V4MulAdd(t0Z, t0Z, V4MulAdd(t0Y, t0Y, V4Mul(t0X, t0X))));
t0X = V4Mul(t0X, recipLen);
t0Y = V4Mul(t0Y, recipLen);
t0Z = V4Mul(t0Z, recipLen);
Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z));
Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X));
Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y));
PX_ASSERT((uintptr_t(descs[0].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[1].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[2].frictionPtr) & 0xF) == 0);
PX_ASSERT((uintptr_t(descs[3].frictionPtr) & 0xF) == 0);
PxU8* PX_RESTRICT writeback0 = descs[0].frictionPtr + frictionPatchWritebackAddrIndex0*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback1 = descs[1].frictionPtr + frictionPatchWritebackAddrIndex1*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback2 = descs[2].frictionPtr + frictionPatchWritebackAddrIndex2*sizeof(FrictionPatch);
PxU8* PX_RESTRICT writeback3 = descs[3].frictionPtr + frictionPatchWritebackAddrIndex3*sizeof(FrictionPatch);
PxU32 index0 = 0, index1 = 0, index2 = 0, index3 = 0;
fd->broken = bFalse;
fd->frictionBrokenWritebackByte[0] = writeback0;
fd->frictionBrokenWritebackByte[1] = writeback1;
fd->frictionBrokenWritebackByte[2] = writeback2;
fd->frictionBrokenWritebackByte[3] = writeback3;
fd->normalX[0] = t0X;
fd->normalY[0] = t0Y;
fd->normalZ[0] = t0Z;
fd->normalX[1] = t1X;
fd->normalY[1] = t1Y;
fd->normalZ[1] = t1Z;
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(ptr);
ptr += sizeof(Vec4V)*header->numFrictionConstr;
PxMemZero(appliedForces, sizeof(Vec4V) * header->numFrictionConstr);
for(PxU32 j = 0; j < maxAnchorCount; j++)
{
PxPrefetchLine(ptr, 384);
PxPrefetchLine(ptr, 512);
PxPrefetchLine(ptr, 640);
SolverContactFrictionBase4* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionBase4*>(ptr);
ptr += frictionSize;
SolverContactFrictionBase4* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionBase4*>(ptr);
ptr += frictionSize;
index0 = j < clampedAnchorCount0 ? j : index0;
index1 = j < clampedAnchorCount1 ? j : index1;
index2 = j < clampedAnchorCount2 ? j : index2;
index3 = j < clampedAnchorCount3 ? j : index3;
if(j >= clampedAnchorCount0)
maxImpulseScale = V4SetX(maxImpulseScale, fZero);
if(j >= clampedAnchorCount1)
maxImpulseScale = V4SetY(maxImpulseScale, fZero);
if(j >= clampedAnchorCount2)
maxImpulseScale = V4SetZ(maxImpulseScale, fZero);
if(j >= clampedAnchorCount3)
maxImpulseScale = V4SetW(maxImpulseScale, fZero);
t0X = V4Mul(maxImpulseScale, t0X);
t0Y = V4Mul(maxImpulseScale, t0Y);
t0Z = V4Mul(maxImpulseScale, t0Z);
t1X = V4Mul(maxImpulseScale, t1X);
t1Y = V4Mul(maxImpulseScale, t1Y);
t1Z = V4Mul(maxImpulseScale, t1Z);
const Vec3V body0Anchor0 = V3LoadU(frictionPatch0.body0Anchors[index0]);
const Vec3V body0Anchor1 = V3LoadU(frictionPatch1.body0Anchors[index1]);
const Vec3V body0Anchor2 = V3LoadU(frictionPatch2.body0Anchors[index2]);
const Vec3V body0Anchor3 = V3LoadU(frictionPatch3.body0Anchors[index3]);
Vec4V ra0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame00q, body0Anchor0));
Vec4V ra1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame01q, body0Anchor1));
Vec4V ra2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame02q, body0Anchor2));
Vec4V ra3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame03q, body0Anchor3));
Vec4V raX, raY, raZ;
PX_TRANSPOSE_44_34(ra0, ra1, ra2, ra3, raX, raY, raZ);
/*raX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raX)), zero, raX);
raY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raY)), zero, raY);
raZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raZ)), zero, raZ);*/
const Vec4V raWorldX = V4Add(raX, bodyFrame0pX);
const Vec4V raWorldY = V4Add(raY, bodyFrame0pY);
const Vec4V raWorldZ = V4Add(raZ, bodyFrame0pZ);
const Vec3V body1Anchor0 = V3LoadU(frictionPatch0.body1Anchors[index0]);
const Vec3V body1Anchor1 = V3LoadU(frictionPatch1.body1Anchors[index1]);
const Vec3V body1Anchor2 = V3LoadU(frictionPatch2.body1Anchors[index2]);
const Vec3V body1Anchor3 = V3LoadU(frictionPatch3.body1Anchors[index3]);
Vec4V rb0 = Vec4V_From_Vec3V(QuatRotate(bodyFrame10q, body1Anchor0));
Vec4V rb1 = Vec4V_From_Vec3V(QuatRotate(bodyFrame11q, body1Anchor1));
Vec4V rb2 = Vec4V_From_Vec3V(QuatRotate(bodyFrame12q, body1Anchor2));
Vec4V rb3 = Vec4V_From_Vec3V(QuatRotate(bodyFrame13q, body1Anchor3));
Vec4V rbX, rbY, rbZ;
PX_TRANSPOSE_44_34(rb0, rb1, rb2, rb3, rbX, rbY, rbZ);
/*rbX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbX)), zero, rbX);
rbY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbY)), zero, rbY);
rbZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbZ)), zero, rbZ);*/
const Vec4V rbWorldX = V4Add(rbX, bodyFrame1pX);
const Vec4V rbWorldY = V4Add(rbY, bodyFrame1pY);
const Vec4V rbWorldZ = V4Add(rbZ, bodyFrame1pZ);
const Vec4V errorX = V4Sub(raWorldX, rbWorldX);
const Vec4V errorY = V4Sub(raWorldY, rbWorldY);
const Vec4V errorZ = V4Sub(raWorldZ, rbWorldZ);
/*errorX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorX)), zero, errorX);
errorY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorY)), zero, errorY);
errorZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(errorZ)), zero, errorZ);*/
//KS - todo - get this working with per-point friction
const PxU32 contactIndex0 = c.contactID[frictionIndex0][index0];
const PxU32 contactIndex1 = c.contactID[frictionIndex1][index1];
const PxU32 contactIndex2 = c.contactID[frictionIndex2][index2];
const PxU32 contactIndex3 = c.contactID[frictionIndex3][index3];
//Ensure that the contact indices are valid
PX_ASSERT(contactIndex0 == 0xffff || contactIndex0 < descs[0].numContacts);
PX_ASSERT(contactIndex1 == 0xffff || contactIndex1 < descs[1].numContacts);
PX_ASSERT(contactIndex2 == 0xffff || contactIndex2 < descs[2].numContacts);
PX_ASSERT(contactIndex3 == 0xffff || contactIndex3 < descs[3].numContacts);
Vec4V targetVel0 = V4LoadA(contactIndex0 == 0xFFFF ? &contactBase0->targetVel.x : &descs[0].contacts[contactIndex0].targetVel.x);
Vec4V targetVel1 = V4LoadA(contactIndex1 == 0xFFFF ? &contactBase1->targetVel.x : &descs[1].contacts[contactIndex1].targetVel.x);
Vec4V targetVel2 = V4LoadA(contactIndex2 == 0xFFFF ? &contactBase2->targetVel.x : &descs[2].contacts[contactIndex2].targetVel.x);
Vec4V targetVel3 = V4LoadA(contactIndex3 == 0xFFFF ? &contactBase3->targetVel.x : &descs[3].contacts[contactIndex3].targetVel.x);
Vec4V targetVelX, targetVelY, targetVelZ;
PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);
{
Vec4V raXnX = V4NegMulSub(raZ, t0Y, V4Mul(raY, t0Z));
Vec4V raXnY = V4NegMulSub(raX, t0Z, V4Mul(raZ, t0X));
Vec4V raXnZ = V4NegMulSub(raY, t0X, V4Mul(raX, t0Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t0Z, linVelT20, V4MulAdd(t0Y, linVelT10, V4Mul(t0X, linVelT00)));
Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
if(isDynamic)
{
SolverContactFrictionDynamic4* PX_RESTRICT dynamicF0 = static_cast<SolverContactFrictionDynamic4*>(f0);
Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
dynamicF0->rbXnX = delAngVel1X;
dynamicF0->rbXnY = delAngVel1Y;
dynamicF0->rbXnZ = delAngVel1Z;
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, vel1);
}
else if(hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t0Y, V4Mul(rbY, t0Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t0Z, V4Mul(rbZ, t0X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t0X, V4Mul(rbX, t0Y));
const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, dotRbXnAngVel1);
}
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V bias = V4Scale(V4MulAdd(t0Z, errorZ, V4MulAdd(t0Y, errorY, V4Mul(t0X, errorX))), invDt);
Vec4V targetVel = V4MulAdd(t0Z, targetVelZ,V4MulAdd(t0Y, targetVelY, V4Mul(t0X, targetVelX)));
targetVel = V4Sub(targetVel, vrel);
f0->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier));
bias = V4Sub(bias, targetVel);
f0->raXnX = delAngVel0X;
f0->raXnY = delAngVel0Y;
f0->raXnZ = delAngVel0Z;
f0->scaledBias = V4Mul(bias, velMultiplier);
f0->velMultiplier = velMultiplier;
}
{
Vec4V raXnX = V4NegMulSub(raZ, t1Y, V4Mul(raY, t1Z));
Vec4V raXnY = V4NegMulSub(raX, t1Z, V4Mul(raZ, t1X));
Vec4V raXnZ = V4NegMulSub(raY, t1X, V4Mul(raX, t1Y));
raXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnX)), zero, raXnX);
raXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnY)), zero, raXnY);
raXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(raXnZ)), zero, raXnZ);
Vec4V delAngVel0X = V4Mul(invInertia0X0, raXnX);
Vec4V delAngVel0Y = V4Mul(invInertia0X1, raXnX);
Vec4V delAngVel0Z = V4Mul(invInertia0X2, raXnX);
delAngVel0X = V4MulAdd(invInertia0Y0, raXnY, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Y1, raXnY, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Y2, raXnY, delAngVel0Z);
delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, delAngVel0X);
delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, delAngVel0Y);
delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, delAngVel0Z);
const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X)));
Vec4V resp = V4MulAdd(dotDelAngVel0, angDom0, invMass0D0);
const Vec4V tVel0 = V4MulAdd(t1Z, linVelT20, V4MulAdd(t1Y, linVelT10, V4Mul(t1X, linVelT00)));
Vec4V vrel = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0)));
if(isDynamic)
{
SolverContactFrictionDynamic4* PX_RESTRICT dynamicF1 = static_cast<SolverContactFrictionDynamic4*>(f1);
Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
rbXnX = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnX)), zero, rbXnX);
rbXnY = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnY)), zero, rbXnY);
rbXnZ = V4Sel(V4IsGrtr(solverOffsetSlop, V4Abs(rbXnZ)), zero, rbXnZ);
Vec4V delAngVel1X = V4Mul(invInertia1X0, rbXnX);
Vec4V delAngVel1Y = V4Mul(invInertia1X1, rbXnX);
Vec4V delAngVel1Z = V4Mul(invInertia1X2, rbXnX);
delAngVel1X = V4MulAdd(invInertia1Y0, rbXnY, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Y1, rbXnY, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Y2, rbXnY, delAngVel1Z);
delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, delAngVel1X);
delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, delAngVel1Y);
delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, delAngVel1Z);
const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X)));
const Vec4V resp1 = V4MulAdd(dotDelAngVel1, angDom1, invMass1D1);
resp = V4Add(resp, resp1);
dynamicF1->rbXnX = delAngVel1X;
dynamicF1->rbXnY = delAngVel1Y;
dynamicF1->rbXnZ = delAngVel1Z;
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
const Vec4V vel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, vel1);
}
else if(hasKinematic)
{
const Vec4V rbXnX = V4NegMulSub(rbZ, t1Y, V4Mul(rbY, t1Z));
const Vec4V rbXnY = V4NegMulSub(rbX, t1Z, V4Mul(rbZ, t1X));
const Vec4V rbXnZ = V4NegMulSub(rbY, t1X, V4Mul(rbX, t1Y));
const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01)));
const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1)));
vrel = V4Sub(vrel, dotRbXnAngVel1);
}
const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero));
Vec4V bias = V4Scale(V4MulAdd(t1Z, errorZ, V4MulAdd(t1Y, errorY, V4Mul(t1X, errorX))), invDt);
Vec4V targetVel = V4MulAdd(t1Z, targetVelZ,V4MulAdd(t1Y, targetVelY, V4Mul(t1X, targetVelX)));
targetVel = V4Sub(targetVel, vrel);
f1->targetVelocity = V4Neg(V4Mul(targetVel, velMultiplier));
bias = V4Sub(bias, targetVel);
f1->raXnX = delAngVel0X;
f1->raXnY = delAngVel0Y;
f1->raXnZ = delAngVel0Z;
f1->scaledBias = V4Mul(bias, velMultiplier);
f1->velMultiplier = velMultiplier;
}
}
frictionPatchWritebackAddrIndex0++;
frictionPatchWritebackAddrIndex1++;
frictionPatchWritebackAddrIndex2++;
frictionPatchWritebackAddrIndex3++;
}
}
}
}
PX_FORCE_INLINE void computeBlockStreamFrictionByteSizes(const CorrelationBuffer& c,
PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex)
{
// PT: use local vars to remove LHS
PxU32 numFrictionPatches = 0;
for(PxU32 i = frictionPatchStartIndex; i < frictionPatchEndIndex; i++)
{
//Friction patches.
if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
}
PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveFrictionBlockStreams(const CorrelationBuffer& c, PxConstraintAllocator& constraintAllocator, PxU32 frictionPatchStartIndex, PxU32 frictionPatchEndIndex,
FrictionPatch*& _frictionPatches, PxU32& numFrictionPatches)
{
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamFrictionByteSizes(c, frictionPatchByteSize, numFrictionPatches, frictionPatchStartIndex, frictionPatchEndIndex);
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if(frictionPatchByteSize > 0)
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if(0==frictionPatches || (reinterpret_cast<FrictionPatch*>(-1))==frictionPatches)
{
if(0==frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches=NULL;
}
}
}
_frictionPatches = frictionPatches;
//Return true if neither of the two block reservations failed.
return (0==frictionPatchByteSize || frictionPatches);
}
//The persistent friction patch correlation/allocation will already have happenned as this is per-pair.
//This function just computes the size of the combined solve data.
void computeBlockStreamByteSizes4(PxSolverContactDesc* descs,
PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount,
const CorrelationBuffer& c)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PxU32 maxPatches = 0;
PxU32 maxFrictionPatches = 0;
PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES];
PxMemZero(maxContactCount, sizeof(maxContactCount));
PxMemZero(maxFrictionCount, sizeof(maxFrictionCount));
bool hasMaxImpulse = false;
for(PxU32 a = 0; a < 4; ++a)
{
PxU32 axisConstraintCount = 0;
hasMaxImpulse = hasMaxImpulse || descs[a].hasMaxImpulse;
for(PxU32 i = 0; i < descs[a].numFrictionPatches; i++)
{
PxU32 ind = i + descs[a].startFrictionPatchIndex;
const FrictionPatch& frictionPatch = c.frictionPatches[ind];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0
&& frictionPatch.anchorCount != 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[ind]!=0)
{
maxContactCount[i] = PxMax(c.frictionPatchContactCounts[ind], maxContactCount[i]);
axisConstraintCount += c.frictionPatchContactCounts[ind];
if(haveFriction)
{
const PxU32 fricCount = PxU32(c.frictionPatches[ind].anchorCount) * 2;
maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]);
axisConstraintCount += fricCount;
}
}
}
maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches);
_axisConstraintCount[a] = axisConstraintCount;
}
for(PxU32 a = 0; a < maxPatches; ++a)
{
if(maxFrictionCount[a] > 0)
maxFrictionPatches++;
}
PxU32 totalContacts = 0, totalFriction = 0;
for(PxU32 a = 0; a < maxPatches; ++a)
{
totalContacts += maxContactCount[a];
totalFriction += maxFrictionCount[a];
}
//OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need
//Body 2 is considered static if it is either *not dynamic* or *kinematic*
bool hasDynamicBody = false;
for(PxU32 a = 0; a < 4; ++a)
{
hasDynamicBody = hasDynamicBody || ((descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY));
}
const bool isStatic = !hasDynamicBody;
const PxU32 headerSize = sizeof(SolverContactHeader4) * maxPatches + sizeof(SolverFrictionSharedData4) * maxFrictionPatches;
PxU32 constraintSize = isStatic ? (sizeof(SolverContactBatchPointBase4) * totalContacts) + ( sizeof(SolverContactFrictionBase4) * totalFriction) :
(sizeof(SolverContactBatchPointDynamic4) * totalContacts) + (sizeof(SolverContactFrictionDynamic4) * totalFriction);
//Space for the appliedForce buffer
constraintSize += sizeof(Vec4V)*(totalContacts+totalFriction);
//If we have max impulse, reserve a buffer for it
if(hasMaxImpulse)
constraintSize += sizeof(aos::Vec4V) * totalContacts;
_solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
}
static SolverConstraintPrepState::Enum reserveBlockStreams4(PxSolverContactDesc* descs, Dy::CorrelationBuffer& c,
PxU8*& solverConstraint, PxU32* axisConstraintCount,
PxU32& solverConstraintByteSize,
PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(0 == solverConstraintByteSize);
//Compute the sizes of all the buffers.
computeBlockStreamByteSizes4(descs,
solverConstraintByteSize, axisConstraintCount,
c);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
if((constraintBlockByteSize + 16u) > 16384)
return SolverConstraintPrepState::eUNBATCHABLE;
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
}
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
return ((0==constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY;
}
SolverConstraintPrepState::Enum createFinalizeSolverContacts4(
Dy::CorrelationBuffer& c,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
PX_ALIGN(16, PxReal invMassScale0[4]);
PX_ALIGN(16, PxReal invMassScale1[4]);
PX_ALIGN(16, PxReal invInertiaScale0[4]);
PX_ALIGN(16, PxReal invInertiaScale1[4]);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
invMassScale0[a] = blockDesc.invMassScales.linear0;
invMassScale1[a] = blockDesc.invMassScales.linear1;
invInertiaScale0[a] = blockDesc.invMassScales.angular0;
invInertiaScale1[a] = blockDesc.invMassScales.angular1;
blockDesc.startFrictionPatchIndex = c.frictionPatchCount;
if (!(blockDesc.disableStrongFriction))
{
bool valid = getFrictionPatches(c, blockDesc.frictionPtr, blockDesc.frictionCount,
blockDesc.bodyFrame0, blockDesc.bodyFrame1, correlationDistance);
if (!valid)
return SolverConstraintPrepState::eUNBATCHABLE;
}
//Create the contact patches
blockDesc.startContactPatchIndex = c.contactPatchCount;
if (!createContactPatches(c, blockDesc.contacts, blockDesc.numContacts, PXC_SAME_NORMAL))
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex);
bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL,
blockDesc.startContactPatchIndex, blockDesc.startFrictionPatchIndex);
if (overflow)
return SolverConstraintPrepState::eUNBATCHABLE;
growPatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, blockDesc.startFrictionPatchIndex,
frictionOffsetThreshold + blockDescs[a].restDistance);
//Remove the empty friction patches - do we actually need to do this?
for (PxU32 p = c.frictionPatchCount; p > blockDesc.startFrictionPatchIndex; --p)
{
if (c.correlationListHeads[p - 1] == 0xffff)
{
//We have an empty patch...need to bin this one...
for (PxU32 p2 = p; p2 < c.frictionPatchCount; ++p2)
{
c.correlationListHeads[p2 - 1] = c.correlationListHeads[p2];
c.frictionPatchContactCounts[p2 - 1] = c.frictionPatchContactCounts[p2];
}
c.frictionPatchCount--;
}
}
PxU32 numFricPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex;
blockDesc.numFrictionPatches = numFricPatches;
}
FrictionPatch* frictionPatchArray[4];
PxU32 frictionPatchCounts[4];
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
const bool successfulReserve = reserveFrictionBlockStreams(c, constraintAllocator, blockDesc.startFrictionPatchIndex, blockDesc.numFrictionPatches + blockDesc.startFrictionPatchIndex,
frictionPatchArray[a],
frictionPatchCounts[a]);
//KS - TODO - how can we recover if we failed to allocate this memory?
if (!successfulReserve)
{
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//At this point, all the friction data has been calculated, the correlation has been done. Provided this was all successful,
//we are ready to create the batched constraints
PxU8* solverConstraint = NULL;
PxU32 solverConstraintByteSize = 0;
{
PxU32 axisConstraintCount[4];
SolverConstraintPrepState::Enum state = reserveBlockStreams4(blockDescs, c,
solverConstraint, axisConstraintCount,
solverConstraintByteSize,
constraintAllocator);
if (state != SolverConstraintPrepState::eSUCCESS)
return state;
for (PxU32 a = 0; a < 4; ++a)
{
FrictionPatch* frictionPatches = frictionPatchArray[a];
PxSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
blockDesc.frictionPtr = reinterpret_cast<PxU8*>(frictionPatches);
blockDesc.frictionCount = PxTo8(frictionPatchCounts[a]);
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<blockDesc.numFrictionPatches; i++)
{
if (c.correlationListHeads[blockDesc.startFrictionPatchIndex + i] != CorrelationBuffer::LIST_END)
{
//*frictionPatches++ = c.frictionPatches[blockDesc.startFrictionPatchIndex + i];
PxMemCopy(frictionPatches++, &c.frictionPatches[blockDesc.startFrictionPatchIndex + i], sizeof(FrictionPatch));
//PxPrefetchLine(frictionPatches, 256);
}
}
}
blockDesc.axisConstraintCount += PxTo16(axisConstraintCount[a]);
desc.constraint = solverConstraint;
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = blockDesc.contactForces;
}
const Vec4V iMassScale0 = V4LoadA(invMassScale0);
const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0);
const Vec4V iMassScale1 = V4LoadA(invMassScale1);
const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1);
setupFinalizeSolverConstraints4(blockDescs, c, solverConstraint, invDtF32, dtF32, bounceThresholdF32,
iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1);
PX_ASSERT((*solverConstraint == DY_SC_TYPE_BLOCK_RB_CONTACT) || (*solverConstraint == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT));
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
return SolverConstraintPrepState::eSUCCESS;
}
//This returns 1 of 3 states: success, unbatchable or out-of-memory. If the constraint is unbatchable, we must fall back on 4 separate constraint
//prep calls
SolverConstraintPrepState::Enum createFinalizeSolverContacts4(
PxsContactManagerOutput** cmOutputs,
ThreadContext& threadContext,
PxSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator)
{
for (PxU32 a = 0; a < 4; ++a)
{
blockDescs[a].desc->constraintLengthOver16 = 0;
}
PX_ASSERT(cmOutputs[0]->nbContacts && cmOutputs[1]->nbContacts && cmOutputs[2]->nbContacts && cmOutputs[3]->nbContacts);
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
//PxTransform idt = PxTransform(PxIdentity);
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
for (PxU32 a = 0; a < 4; ++a)
{
PxSolverContactDesc& blockDesc = blockDescs[a];
PxSolverConstraintDesc& desc = *blockDesc.desc;
//blockDesc.startContactIndex = buffer.count;
blockDesc.contacts = buffer.contacts + buffer.count;
PxPrefetchLine(desc.bodyA);
PxPrefetchLine(desc.bodyB);
if ((buffer.count + cmOutputs[a]->nbContacts) > 64)
{
return SolverConstraintPrepState::eUNBATCHABLE;
}
bool hasMaxImpulse = false;
bool hasTargetVelocity = false;
//OK...do the correlation here as well...
PxPrefetchLine(blockDescs[a].frictionPtr);
PxPrefetchLine(blockDescs[a].frictionPtr, 64);
PxPrefetchLine(blockDescs[a].frictionPtr, 128);
if (a < 3)
{
PxPrefetchLine(cmOutputs[a]->contactPatches);
PxPrefetchLine(cmOutputs[a]->contactPoints);
}
PxReal invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1;
const PxReal defaultMaxImpulse = PxMin(blockDesc.data0->maxContactImpulse, blockDesc.data1->maxContactImpulse);
PxU32 contactCount = extractContacts(buffer, *cmOutputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, defaultMaxImpulse);
if (contactCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
blockDesc.numContacts = contactCount;
blockDesc.hasMaxImpulse = hasMaxImpulse;
blockDesc.disableStrongFriction = blockDesc.disableStrongFriction || hasTargetVelocity;
blockDesc.invMassScales.linear0 *= invMassScale0;
blockDesc.invMassScales.linear1 *= invMassScale1;
blockDesc.invMassScales.angular0 *= invInertiaScale0;
blockDesc.invMassScales.angular1 *= invInertiaScale1;
//blockDesc.frictionPtr = &blockDescs[a].frictionPtr;
//blockDesc.frictionCount = blockDescs[a].frictionCount;
}
return createFinalizeSolverContacts4(c, blockDescs,
invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold,
correlationDistance, constraintAllocator);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyDynamics.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 DY_DYNAMICS_H
#define DY_DYNAMICS_H
#include "PxvConfig.h"
#include "CmTask.h"
#include "CmPool.h"
#include "PxcThreadCoherentCache.h"
#include "DyThreadContext.h"
#include "PxcConstraintBlockStream.h"
#include "DySolverBody.h"
#include "DyContext.h"
#include "PxsIslandManagerTypes.h"
#include "PxvNphaseImplementationContext.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
}
class PxsRigidBody;
struct PxsBodyCore;
class PxsIslandIndices;
struct PxsIndexedInteraction;
struct PxsIndexedContactManager;
struct PxSolverConstraintDesc;
namespace Cm
{
class SpatialVector;
}
namespace Dy
{
class SolverCore;
struct SolverIslandParams;
class DynamicsContext;
#define SOLVER_PARALLEL_METHOD_ARGS \
DynamicsContext& context, \
SolverIslandParams& params, \
IG::IslandSim& islandSim
/**
\brief Solver body pool (array) that enforces 128-byte alignment for base address of array.
\note This reduces cache misses on platforms with 128-byte-size cache lines by aligning the start of the array to the beginning of a cache line.
*/
class SolverBodyPool : public PxArray<PxSolverBody, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverBody> > >
{
PX_NOCOPY(SolverBodyPool)
public:
SolverBodyPool() {}
};
/**
\brief Solver body data pool (array) that enforces 128-byte alignment for base address of array.
\note This reduces cache misses on platforms with 128-byte-size cache lines by aligning the start of the array to the beginning of a cache line.
*/
class SolverBodyDataPool : public PxArray<PxSolverBodyData, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverBodyData> > >
{
PX_NOCOPY(SolverBodyDataPool)
public:
SolverBodyDataPool() {}
};
class SolverConstraintDescPool : public PxArray<PxSolverConstraintDesc, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverConstraintDesc> > >
{
PX_NOCOPY(SolverConstraintDescPool)
public:
SolverConstraintDescPool() { }
};
/**
\brief Encapsulates an island's context
*/
struct IslandContext
{
//The thread context for this island (set in in the island start task, released in the island end task)
ThreadContext* mThreadContext;
PxsIslandIndices mCounts;
};
/**
\brief Encapsules the data used by the constraint solver.
*/
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class DynamicsContext : public Context
{
PX_NOCOPY(DynamicsContext)
public:
DynamicsContext(PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocator,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal maxBiasCoefficient,
bool frictionEveryIteration,
PxReal lengthScale
);
virtual ~DynamicsContext();
// Context
virtual void destroy() PX_OVERRIDE;
virtual void update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nPhase, PxU32 maxPatchesPerCM, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& changedHandleMap) PX_OVERRIDE;
virtual void mergeResults() PX_OVERRIDE;
virtual void setSimulationController(PxsSimulationController* simulationController ) PX_OVERRIDE { mSimulationController = simulationController; }
virtual PxSolverType::Enum getSolverType() const PX_OVERRIDE { return PxSolverType::ePGS; }
//~Context
/**
\brief Allocates and returns a thread context object.
\return A thread context.
*/
PX_FORCE_INLINE ThreadContext* getThreadContext() { return mThreadContextPool.get(); }
/**
\brief Returns a thread context to the thread context pool.
\param[in] context The thread context to return to the thread context pool.
*/
void putThreadContext(ThreadContext* context) { mThreadContextPool.put(context); }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() { return mTaskPool; }
PX_FORCE_INLINE ThresholdStream& getThresholdStream() { return *mThresholdStream; }
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE PxU32 getKinematicCount() const { return mKinematicCount; }
void updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks);
protected:
#if PX_ENABLE_SIM_STATS
void addThreadStats(const ThreadContext::ThreadSimStats& stats);
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
// Solver helper-methods
/**
\brief Computes the unconstrained velocity for a given PxsRigidBody
\param[in] atom The PxsRigidBody
*/
void computeUnconstrainedVelocity(PxsRigidBody* atom) const;
/**
\brief fills in a PxSolverConstraintDesc from an indexed interaction
\param[in,out] desc The PxSolverConstraintDesc
\param[in] constraint The PxsIndexedInteraction
*/
void setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim,
const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset);
void setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex,
const IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxU32 solverBodyOffset);
/**
\brief Compute the unconstrained velocity for set of bodies in parallel. This function may spawn additional tasks.
\param[in] dt The timestep
\param[in] bodyArray The array of body cores
\param[in] originalBodyArray The array of PxsRigidBody
\param[in] nodeIndexArray The array of island node index
\param[in] bodyCount The number of bodies
\param[out] solverBodyPool The pool of solver bodies. These are synced with the corresponding body in bodyArray.
\param[out] solverBodyDataPool The pool of solver body data. These are synced with the corresponding body in bodyArray
\param[out] motionVelocityArray The motion velocities for the bodies
\param[out] maxSolverPositionIterations The maximum number of position iterations requested by any body in the island
\param[out] maxSolverVelocityIterations The maximum number of velocity iterations requested by any body in the island
\param[out] integrateTask The continuation task for any tasks spawned by this function.
*/
void preIntegrationParallel(
PxF32 dt,
PxsBodyCore*const* bodyArray, // INOUT: core body attributes
PxsRigidBody*const* originalBodyArray, // IN: original body atom names (LEGACY - DON'T deref the ptrs!!)
PxU32 const* nodeIndexArray, // IN: island node index
PxU32 bodyCount, // IN: body count
PxSolverBody* solverBodyPool, // IN: solver atom pool (space preallocated)
PxSolverBodyData* solverBodyDataPool,
Cm::SpatialVector* motionVelocityArray, // OUT: motion velocities
PxU32& maxSolverPositionIterations,
PxU32& maxSolverVelocityIterations,
PxBaseTask& integrateTask
);
/**
\brief Solves an island in parallel.
\param[in] params Solver parameter structure
*/
void solveParallel(SolverIslandParams& params, IG::IslandSim& islandSim, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV);
void integrateCoreParallel(SolverIslandParams& params, Cm::SpatialVectorF* deltaV, IG::IslandSim& islandSim);
/**
\brief Resets the thread contexts
*/
void resetThreadContexts();
/**
\brief Returns the scratch memory allocator.
\return The scratch memory allocator.
*/
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
//Data
/**
\brief Body to represent the world static body.
*/
PX_ALIGN(16, PxSolverBody mWorldSolverBody);
/**
\brief Body data to represent the world static body.
*/
PX_ALIGN(16, PxSolverBodyData mWorldSolverBodyData);
/**
\brief A thread context pool
*/
PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool> mThreadContextPool;
/**
\brief Solver constraint desc array
*/
SolverConstraintDescPool mSolverConstraintDescPool;
/**
\brief Ordered solver constraint desc array (after partitioning)
*/
SolverConstraintDescPool mOrderedSolverConstraintDescPool;
/**
\brief A temporary array of constraint descs used for partitioning
*/
SolverConstraintDescPool mTempSolverConstraintDescPool;
/**
\brief An array of contact constraint batch headers
*/
PxArray<PxConstraintBatchHeader> mContactConstraintBatchHeaders;
/**
\brief Array of motion velocities for all bodies in the scene.
*/
PxArray<Cm::SpatialVector> mMotionVelocityArray;
/**
\brief Array of body core pointers for all bodies in the scene.
*/
PxArray<PxsBodyCore*> mBodyCoreArray;
/**
\brief Array of rigid body pointers for all bodies in the scene.
*/
PxArray<PxsRigidBody*> mRigidBodyArray;
/**
\brief Array of articulation pointers for all articulations in the scene.
*/
PxArray<FeatherstoneArticulation*> mArticulationArray;
/**
\brief Global pool for solver bodies. Kinematic bodies are at the start, and then dynamic bodies
*/
SolverBodyPool mSolverBodyPool;
/**
\brief Global pool for solver body data. Kinematic bodies are at the start, and then dynamic bodies
*/
SolverBodyDataPool mSolverBodyDataPool;
ThresholdStream* mExceededForceThresholdStream[2]; //this store previous and current exceeded force thresholdStream
PxArray<PxU32> mExceededForceThresholdStreamMask;
/**
\brief Interface to the solver core.
\note We currently only support PxsSolverCoreSIMD. Other cores may be added in future releases.
*/
SolverCore* mSolverCore[PxFrictionType::eFRICTION_COUNT];
PxArray<PxU32> mSolverBodyRemapTable; //Remaps from the "active island" index to the index within a solver island
PxArray<PxU32> mNodeIndexArray; //island node index
PxArray<PxsIndexedContactManager> mContactList;
/**
\brief The total number of kinematic bodies in the scene
*/
PxU32 mKinematicCount;
/**
\brief Atomic counter for the number of threshold stream elements.
*/
PxI32 mThresholdStreamOut;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator mOutputIterator;
private:
//private:
PxcScratchAllocator& mScratchAllocator;
Cm::FlushPool& mTaskPool;
PxTaskManager* mTaskManager;
PxU32 mCurrentIndex; // this is the index point to the current exceeded force threshold stream
protected:
friend class PxsSolverStartTask;
friend class PxsSolverAticulationsTask;
friend class PxsSolverSetupConstraintsTask;
friend class PxsSolverCreateFinalizeConstraintsTask;
friend class PxsSolverConstraintPartitionTask;
friend class PxsSolverSetupSolveTask;
friend class PxsSolverIntegrateTask;
friend class PxsSolverEndTask;
friend class PxsSolverConstraintPostProcessTask;
friend class PxsForceThresholdTask;
friend class SolverArticulationUpdateTask;
friend void solveParallel(SOLVER_PARALLEL_METHOD_ARGS);
};
#if PX_VC
#pragma warning(pop)
#endif
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverPFConstraintsBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxFPU.h"
#include "DySolverBody.h"
#include "DySolverContactPF4.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DySolverContact.h"
#include "DyPGS.h"
namespace physx
{
namespace Dy
{
static void solveContactCoulomb4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
const PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
//const PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
//TODO - can I avoid this many tests???
while(currPtr < last)
{
SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
Vec4V* appliedForceBuffer = reinterpret_cast<Vec4V*>(currPtr + hdr->frictionOffset + sizeof(SolverFrictionHeader4));
//PX_ASSERT((PxU8*)appliedForceBuffer < endPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
SolverContact4Dynamic* PX_RESTRICT contacts = reinterpret_cast<SolverContact4Dynamic*>(currPtr);
//const Vec4V dominance1 = V4Neg(__dominance1);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V invMass1D1 = hdr->invMassBDom;
const Vec4V angD0 = hdr->angD0;
const Vec4V angD1 = hdr->angD1;
const Vec4V normalT0 = hdr->normalX;
const Vec4V normalT1 = hdr->normalY;
const Vec4V normalT2 = hdr->normalZ;
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalT0);
const Vec4V normalVel3_tmp2 = V4Mul(linVel1T0, normalT0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalT1, normalVel1_tmp2);
const Vec4V normalVel3_tmp1 = V4MulAdd(linVel1T1, normalT1, normalVel3_tmp2);
Vec4V normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1_tmp1);
Vec4V normalVel3 = V4MulAdd(linVel1T2, normalT2, normalVel3_tmp1);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Dynamic& c = contacts[i];
PxPrefetchLine((&contacts[i+1]));
PxPrefetchLine((&contacts[i+1]), 128);
PxPrefetchLine((&contacts[i+1]), 256);
PxPrefetchLine((&contacts[i+1]), 384);
const Vec4V appliedForce = c.appliedForce;
const Vec4V velMultiplier = c.velMultiplier;
const Vec4V targetVel = c.targetVelocity;
const Vec4V scaledBias = c.scaledBias;
const Vec4V maxImpulse = c.maxImpulse;
const Vec4V raXnT0 = c.raXnX;
const Vec4V raXnT1 = c.raXnY;
const Vec4V raXnT2 = c.raXnZ;
const Vec4V rbXnT0 = c.rbXnX;
const Vec4V rbXnT1 = c.rbXnY;
const Vec4V rbXnT2 = c.rbXnZ;
const Vec4V normalVel2_tmp2 = V4Mul(raXnT0, angState0T0);
const Vec4V normalVel4_tmp2 = V4Mul(rbXnT0, angState1T0);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnT1, angState0T1, normalVel2_tmp2);
const Vec4V normalVel4_tmp1 = V4MulAdd(rbXnT1, angState1T1, normalVel4_tmp2);
const Vec4V normalVel2 = V4MulAdd(raXnT2, angState0T2, normalVel2_tmp1);
const Vec4V normalVel4 = V4MulAdd(rbXnT2, angState1T2, normalVel4_tmp1);
const Vec4V biasedErr = V4MulAdd(targetVel, velMultiplier, V4Neg(scaledBias));
//Linear component - normal * invMass_dom
const Vec4V normalVel_tmp2(V4Add(normalVel1, normalVel2));
const Vec4V normalVel_tmp1(V4Add(normalVel3, normalVel4));
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V _deltaF = V4NegMulSub(normalVel, velMultiplier, biasedErr);
const Vec4V nAppliedForce = V4Neg(appliedForce);
const Vec4V _deltaF2 = V4Max(_deltaF, nAppliedForce);
const Vec4V _newAppliedForce(V4Add(appliedForce, _deltaF2));
const Vec4V newAppliedForce = V4Min(_newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
normalVel1 = V4MulAdd(invMass0D0, deltaF, normalVel1);
normalVel3 = V4NegMulSub(invMass1D1, deltaF, normalVel3);
accumDeltaF = V4Add(deltaF, accumDeltaF);
const Vec4V deltaFAng0 = V4Mul(angD0, deltaF);
const Vec4V deltaFAng1 = V4Mul(angD1, deltaF);
angState0T0 = V4MulAdd(raXnT0, deltaFAng0, angState0T0);
angState1T0 = V4NegMulSub(rbXnT0, deltaFAng1, angState1T0);
angState0T1 = V4MulAdd(raXnT1, deltaFAng0, angState0T1);
angState1T1 = V4NegMulSub(rbXnT1, deltaFAng1, angState1T1);
angState0T2 = V4MulAdd(raXnT2, deltaFAng0, angState0T2);
angState1T2 = V4NegMulSub(rbXnT2, deltaFAng1, angState1T2);
c.appliedForce = newAppliedForce;
appliedForceBuffer[i] = newAppliedForce;
}
const Vec4V accumDeltaF0 = V4Mul(accumDeltaF, invMass0D0);
const Vec4V accumDeltaF1 = V4Mul(accumDeltaF, invMass1D1);
linVel0T0 = V4MulAdd(normalT0, accumDeltaF0, linVel0T0);
linVel1T0 = V4NegMulSub(normalT0, accumDeltaF1, linVel1T0);
linVel0T1 = V4MulAdd(normalT1, accumDeltaF0, linVel0T1);
linVel1T1 = V4NegMulSub(normalT1, accumDeltaF1, linVel1T1);
linVel0T2 = V4MulAdd(normalT2, accumDeltaF0, linVel0T2);
linVel1T2 = V4NegMulSub(normalT2, accumDeltaF1, linVel1T2);
}
PX_ASSERT(currPtr == last);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void solveContactCoulomb4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
const PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
//TODO - can I avoid this many tests???
while(currPtr < last)
{
SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader4*>(currPtr);
Vec4V* appliedForceBuffer = reinterpret_cast<Vec4V*>(currPtr + hdr->frictionOffset + sizeof(SolverFrictionHeader4));
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
SolverContact4Base* PX_RESTRICT contacts = reinterpret_cast<SolverContact4Base*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V angD0 = hdr->angD0;
const Vec4V normalT0 = hdr->normalX;
const Vec4V normalT1 = hdr->normalY;
const Vec4V normalT2 = hdr->normalZ;
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalT0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalT1, normalVel1_tmp2);
Vec4V normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1_tmp1);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Base& c = contacts[i];
PxPrefetchLine((&contacts[i+1]));
PxPrefetchLine((&contacts[i+1]), 128);
PxPrefetchLine((&contacts[i+1]), 256);
const Vec4V appliedForce = c.appliedForce;
const Vec4V velMultiplier = c.velMultiplier;
const Vec4V targetVel = c.targetVelocity;
const Vec4V scaledBias = c.scaledBias;
const Vec4V maxImpulse = c.maxImpulse;
const Vec4V raXnT0 = c.raXnX;
const Vec4V raXnT1 = c.raXnY;
const Vec4V raXnT2 = c.raXnZ;
const Vec4V normalVel2_tmp2 = V4Mul(raXnT0, angState0T0);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnT1, angState0T1, normalVel2_tmp2);
const Vec4V normalVel2 = V4MulAdd(raXnT2, angState0T2, normalVel2_tmp1);
const Vec4V biasedErr = V4MulAdd(targetVel, velMultiplier, V4Neg(scaledBias));
//Linear component - normal * invMass_dom
const Vec4V normalVel(V4Add(normalVel1, normalVel2));
const Vec4V _deltaF = V4NegMulSub(normalVel, velMultiplier, biasedErr);
const Vec4V nAppliedForce = V4Neg(appliedForce);
const Vec4V _deltaF2 = V4Max(_deltaF, nAppliedForce);
const Vec4V _newAppliedForce(V4Add(appliedForce, _deltaF2));
const Vec4V newAppliedForce = V4Min(_newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaAngF = V4Mul(deltaF, angD0);
normalVel1 = V4MulAdd(invMass0D0, deltaF, normalVel1);
accumDeltaF = V4Add(deltaF, accumDeltaF);
angState0T0 = V4MulAdd(raXnT0, deltaAngF, angState0T0);
angState0T1 = V4MulAdd(raXnT1, deltaAngF, angState0T1);
angState0T2 = V4MulAdd(raXnT2, deltaAngF, angState0T2);
c.appliedForce = newAppliedForce;
appliedForceBuffer[i] = newAppliedForce;
}
const Vec4V scaledAccumDeltaF = V4Mul(accumDeltaF, invMass0D0);
linVel0T0 = V4MulAdd(normalT0, scaledAccumDeltaF, linVel0T0);
linVel0T1 = V4MulAdd(normalT1, scaledAccumDeltaF, linVel0T1);
linVel0T2 = V4MulAdd(normalT2, scaledAccumDeltaF, linVel0T2);
}
PX_ASSERT(currPtr == last);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
}
static void solveFriction4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
while(currPtr < endPtr)
{
SolverFrictionHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverFrictionHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
Vec4V* appliedImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += hdr->numNormalConstr * sizeof(Vec4V);
PxPrefetchLine(currPtr, 128);
PxPrefetchLine(currPtr,256);
PxPrefetchLine(currPtr,384);
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverFriction4Dynamic* PX_RESTRICT frictions = reinterpret_cast<SolverFriction4Dynamic*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(frictions + hdr->numFrictionConstr);
const PxU32 maxFrictionConstr = numFrictionConstr;
const Vec4V staticFric = hdr->staticFriction;
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V invMass1D1 = hdr->invMassBDom;
const Vec4V angD0 = hdr->angD0;
const Vec4V angD1 = hdr->angD1;
for(PxU32 i=0;i<maxFrictionConstr;i++)
{
SolverFriction4Dynamic& f = frictions[i];
PxPrefetchLine((&f)+1);
PxPrefetchLine((&f)+1,128);
PxPrefetchLine((&f)+1,256);
PxPrefetchLine((&f)+1,384);
const Vec4V appliedImpulse = appliedImpulses[i>>hdr->frictionPerContact];
const Vec4V maxFriction = V4Mul(staticFric, appliedImpulse);
const Vec4V nMaxFriction = V4Neg(maxFriction);
const Vec4V normalX = f.normalX;
const Vec4V normalY = f.normalY;
const Vec4V normalZ = f.normalZ;
const Vec4V raXnX = f.raXnX;
const Vec4V raXnY = f.raXnY;
const Vec4V raXnZ = f.raXnZ;
const Vec4V rbXnX = f.rbXnX;
const Vec4V rbXnY = f.rbXnY;
const Vec4V rbXnZ = f.rbXnZ;
const Vec4V appliedForce(f.appliedForce);
const Vec4V velMultiplier(f.velMultiplier);
const Vec4V targetVel(f.targetVelocity);
//4 x 4 Dot3 products encoded as 8 M44 transposes, 4 MulV and 8 MulAdd ops
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalX);
const Vec4V normalVel2_tmp2 = V4Mul(raXnX, angState0T0);
const Vec4V normalVel3_tmp2 = V4Mul(linVel1T0, normalX);
const Vec4V normalVel4_tmp2 = V4Mul(rbXnX, angState1T0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalY, normalVel1_tmp2);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnY, angState0T1, normalVel2_tmp2);
const Vec4V normalVel3_tmp1 = V4MulAdd(linVel1T1, normalY, normalVel3_tmp2);
const Vec4V normalVel4_tmp1 = V4MulAdd(rbXnY, angState1T1, normalVel4_tmp2);
const Vec4V normalVel1 = V4MulAdd(linVel0T2, normalZ, normalVel1_tmp1);
const Vec4V normalVel2 = V4MulAdd(raXnZ, angState0T2, normalVel2_tmp1);
const Vec4V normalVel3 = V4MulAdd(linVel1T2, normalZ, normalVel3_tmp1);
const Vec4V normalVel4 = V4MulAdd(rbXnZ, angState1T2, normalVel4_tmp1);
const Vec4V normalVel_tmp2 = V4Add(normalVel1, normalVel2);
const Vec4V normalVel_tmp1 = V4Add(normalVel3, normalVel4);
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V tmp = V4NegMulSub(targetVel, velMultiplier, appliedForce);
Vec4V newAppliedForce = V4MulAdd(normalVel, velMultiplier, tmp);
newAppliedForce = V4Clamp(newAppliedForce,nMaxFriction, maxFriction);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaLinF0 = V4Mul(invMass0D0, deltaF);
const Vec4V deltaLinF1 = V4Mul(invMass1D1, deltaF);
const Vec4V deltaAngF0 = V4Mul(angD0, deltaF);
const Vec4V deltaAngF1 = V4Mul(angD1, deltaF);
linVel0T0 = V4MulAdd(normalX, deltaLinF0, linVel0T0);
linVel1T0 = V4NegMulSub(normalX, deltaLinF1, linVel1T0);
angState0T0 = V4MulAdd(raXnX, deltaAngF0, angState0T0);
angState1T0 = V4NegMulSub(rbXnX, deltaAngF1, angState1T0);
linVel0T1 = V4MulAdd(normalY, deltaLinF0, linVel0T1);
linVel1T1 = V4NegMulSub(normalY, deltaLinF1, linVel1T1);
angState0T1 = V4MulAdd(raXnY, deltaAngF0, angState0T1);
angState1T1 = V4NegMulSub(rbXnY, deltaAngF1, angState1T1);
linVel0T2 = V4MulAdd(normalZ, deltaLinF0, linVel0T2);
linVel1T2 = V4NegMulSub(normalZ, deltaLinF1, linVel1T2);
angState0T2 = V4MulAdd(raXnZ, deltaAngF0, angState0T2);
angState1T2 = V4NegMulSub(rbXnZ, deltaAngF1, angState1T2);
f.appliedForce = newAppliedForce;
}
}
PX_ASSERT(currPtr == endPtr);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void solveFriction4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxU8* PX_RESTRICT endPtr = desc[0].constraint + getConstraintLength(desc[0]);
while(currPtr < endPtr)
{
SolverFrictionHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverFrictionHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
Vec4V* appliedImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += hdr->numNormalConstr * sizeof(Vec4V);
PxPrefetchLine(currPtr, 128);
PxPrefetchLine(currPtr,256);
PxPrefetchLine(currPtr,384);
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
SolverFriction4Base* PX_RESTRICT frictions = reinterpret_cast<SolverFriction4Base*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(frictions + hdr->numFrictionConstr);
const PxU32 maxFrictionConstr = numFrictionConstr;
const Vec4V staticFric = hdr->staticFriction;
const Vec4V invMass0D0 = hdr->invMassADom;
const Vec4V angD0 = hdr->angD0;
for(PxU32 i=0;i<maxFrictionConstr;i++)
{
SolverFriction4Base& f = frictions[i];
PxPrefetchLine((&f)+1);
PxPrefetchLine((&f)+1,128);
PxPrefetchLine((&f)+1,256);
const Vec4V appliedImpulse = appliedImpulses[i>>hdr->frictionPerContact];
const Vec4V maxFriction = V4Mul(staticFric, appliedImpulse);
const Vec4V nMaxFriction = V4Neg(maxFriction);
const Vec4V normalX = f.normalX;
const Vec4V normalY = f.normalY;
const Vec4V normalZ = f.normalZ;
const Vec4V raXnX = f.raXnX;
const Vec4V raXnY = f.raXnY;
const Vec4V raXnZ = f.raXnZ;
const Vec4V appliedForce(f.appliedForce);
const Vec4V velMultiplier(f.velMultiplier);
const Vec4V targetVel(f.targetVelocity);
//4 x 4 Dot3 products encoded as 8 M44 transposes, 4 MulV and 8 MulAdd ops
const Vec4V normalVel1_tmp2 = V4Mul(linVel0T0, normalX);
const Vec4V normalVel2_tmp2 = V4Mul(raXnX, angState0T0);
const Vec4V normalVel1_tmp1 = V4MulAdd(linVel0T1, normalY, normalVel1_tmp2);
const Vec4V normalVel2_tmp1 = V4MulAdd(raXnY, angState0T1, normalVel2_tmp2);
const Vec4V normalVel1 = V4MulAdd(linVel0T2, normalZ, normalVel1_tmp1);
const Vec4V normalVel2 = V4MulAdd(raXnZ, angState0T2, normalVel2_tmp1);
const Vec4V delLinVel00 = V4Mul(normalX, invMass0D0);
const Vec4V delLinVel10 = V4Mul(normalY, invMass0D0);
const Vec4V normalVel = V4Add(normalVel1, normalVel2);
const Vec4V delLinVel20 = V4Mul(normalZ, invMass0D0);
const Vec4V tmp = V4NegMulSub(targetVel, velMultiplier, appliedForce);
Vec4V newAppliedForce = V4MulAdd(normalVel, velMultiplier, tmp);
newAppliedForce = V4Clamp(newAppliedForce,nMaxFriction, maxFriction);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaAngF0 = V4Mul(angD0, deltaF);
linVel0T0 = V4MulAdd(delLinVel00, deltaF, linVel0T0);
angState0T0 = V4MulAdd(raXnX, deltaAngF0, angState0T0);
linVel0T1 = V4MulAdd(delLinVel10, deltaF, linVel0T1);
angState0T1 = V4MulAdd(raXnY, deltaAngF0, angState0T1);
linVel0T2 = V4MulAdd(delLinVel20, deltaF, linVel0T2);
angState0T2 = V4MulAdd(raXnZ, deltaAngF0, angState0T2);
f.appliedForce = newAppliedForce;
}
}
PX_ASSERT(currPtr == endPtr);
//KS - we need to use PX_TRANSPOSE_44 here instead of the 34_43 variants because the W components are being used to
//store the bodies' progress counters.
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
// Write back
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
}
static void concludeContactCoulomb4(const PxSolverConstraintDesc* desc, SolverContext& /*cache*/)
{
PxU8* PX_RESTRICT cPtr = desc[0].constraint;
const Vec4V zero = V4Zero();
const SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
PxU32 pointStride = firstHeader->type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContact4Dynamic) : sizeof(SolverContact4Base);
while(cPtr < last)
{
const SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader4);
const PxU32 numNormalConstr = hdr->numNormalConstr;
//if(cPtr < last)
//PxPrefetchLine(cPtr, 512);
PxPrefetchLine(cPtr,128);
PxPrefetchLine(cPtr,256);
PxPrefetchLine(cPtr,384);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContact4Base *c = reinterpret_cast<SolverContact4Base*>(cPtr);
cPtr += pointStride;
c->scaledBias = V4Max(c->scaledBias, zero);
}
}
PX_ASSERT(cPtr == last);
}
static void writeBackContactCoulomb4(const PxSolverConstraintDesc* desc, SolverContext& cache,
const PxSolverBodyData** PX_RESTRICT bd0, const PxSolverBodyData** PX_RESTRICT bd1)
{
Vec4V normalForceV = V4Zero();
PxU8* PX_RESTRICT cPtr = desc[0].constraint;
PxReal* PX_RESTRICT vForceWriteback0 = reinterpret_cast<PxReal*>(desc[0].writeBack);
PxReal* PX_RESTRICT vForceWriteback1 = reinterpret_cast<PxReal*>(desc[1].writeBack);
PxReal* PX_RESTRICT vForceWriteback2 = reinterpret_cast<PxReal*>(desc[2].writeBack);
PxReal* PX_RESTRICT vForceWriteback3 = reinterpret_cast<PxReal*>(desc[3].writeBack);
const SolverContactCoulombHeader4* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
PxU8* PX_RESTRICT last = desc[0].constraint + firstHeader->frictionOffset;
const PxU32 pointStride = firstHeader->type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContact4Dynamic)
: sizeof(SolverContact4Base);
bool writeBackThresholds[4] = {false, false, false, false};
while(cPtr < last)
{
const SolverContactCoulombHeader4* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader4*>(cPtr);
cPtr += sizeof(SolverContactCoulombHeader4);
writeBackThresholds[0] = hdr->flags[0] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[1] = hdr->flags[1] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[2] = hdr->flags[2] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[3] = hdr->flags[3] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
const PxU32 numNormalConstr = hdr->numNormalConstr;
PxPrefetchLine(cPtr, 256);
PxPrefetchLine(cPtr, 384);
for(PxU32 i=0; i<numNormalConstr; i++)
{
SolverContact4Base* c = reinterpret_cast<SolverContact4Base*>(cPtr);
cPtr += pointStride;
const Vec4V appliedForce = c->appliedForce;
if(vForceWriteback0 && i < hdr->numNormalConstr0)
FStore(V4GetX(appliedForce), vForceWriteback0++);
if(vForceWriteback1 && i < hdr->numNormalConstr1)
FStore(V4GetY(appliedForce), vForceWriteback1++);
if(vForceWriteback2 && i < hdr->numNormalConstr2)
FStore(V4GetZ(appliedForce), vForceWriteback2++);
if(vForceWriteback3 && i < hdr->numNormalConstr3)
FStore(V4GetW(appliedForce), vForceWriteback3++);
normalForceV = V4Add(normalForceV, appliedForce);
}
}
PX_ASSERT(cPtr == last);
PX_ALIGN(16, PxReal nf[4]);
V4StoreA(normalForceV, nf);
//all constraint pointer in descs are the same constraint
Sc::ShapeInteraction** shapeInteractions = reinterpret_cast<SolverContactCoulombHeader4*>(desc[0].constraint)->shapeInteraction;
for(PxU32 a = 0; a < 4; ++a)
{
if(writeBackThresholds[a] && desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
nf[a] !=0.f && (bd0[a]->reportThreshold < PX_MAX_REAL || bd1[a]->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = nf[a];
elt.threshold = PxMin<float>(bd0[a]->reportThreshold, bd1[a]->reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0[a]->nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1[a]->nodeIndex);
elt.shapeInteraction = shapeInteractions[a];
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
}
void solveContactCoulombPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
}
void solveContactCoulombPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
}
void solveContactCoulombPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
concludeContactCoulomb4(desc, cache);
}
void solveContactCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
concludeContactCoulomb4(desc, cache);
}
void solveContactCoulombPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContactCoulomb4(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContactCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContactCoulomb4_StaticBlock(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContactCoulomb4(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveFrictionCoulombPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
void solveFrictionCoulombPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
void solveFrictionCoulombPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_Block(desc, cache);
}
void solveFrictionCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveFriction4_StaticBlock(desc, cache);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionCorrelation.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "PxvConfig.h"
#include "DyCorrelationBuffer.h"
#include "PxsMaterialManager.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxVecMath.h"
#include "GuBounds.h"
using namespace physx;
using namespace aos;
namespace physx
{
namespace Dy
{
static PX_FORCE_INLINE void initContactPatch(CorrelationBuffer::ContactPatchData& patch, PxU16 index, PxReal restitution, PxReal staticFriction, PxReal dynamicFriction,
PxU8 flags)
{
patch.start = index;
patch.count = 1;
patch.next = 0;
patch.flags = flags;
patch.restitution = restitution;
patch.staticFriction = staticFriction;
patch.dynamicFriction = dynamicFriction;
}
bool createContactPatches(CorrelationBuffer& fb, const PxContactPoint* cb, PxU32 contactCount, PxReal normalTolerance)
{
// PT: this rewritten version below doesn't have LHS
PxU32 contactPatchCount = fb.contactPatchCount;
if(contactPatchCount == PxContactBuffer::MAX_CONTACTS)
return false;
if(contactCount>0)
{
CorrelationBuffer::ContactPatchData* PX_RESTRICT currentPatchData = fb.contactPatches + contactPatchCount;
const PxContactPoint* PX_RESTRICT contacts = cb;
initContactPatch(fb.contactPatches[contactPatchCount++], PxTo16(0), contacts[0].restitution,
contacts[0].staticFriction, contacts[0].dynamicFriction, PxU8(contacts[0].materialFlags));
Vec4V minV = V4LoadA(&contacts[0].point.x);
Vec4V maxV = minV;
PxU32 patchIndex = 0;
PxU8 count = 1;
for (PxU32 i = 1; i<contactCount; i++)
{
const PxContactPoint& curContact = contacts[i];
const PxContactPoint& preContact = contacts[patchIndex];
if(curContact.staticFriction == preContact.staticFriction
&& curContact.dynamicFriction == preContact.dynamicFriction
&& curContact.restitution == preContact.restitution
&& curContact.normal.dot(preContact.normal)>=normalTolerance)
{
const Vec4V ptV = V4LoadA(&curContact.point.x);
minV = V4Min(minV, ptV);
maxV = V4Max(maxV, ptV);
count++;
}
else
{
if(contactPatchCount == PxContactBuffer::MAX_CONTACTS)
return false;
patchIndex = i;
currentPatchData->count = count;
count = 1;
StoreBounds(currentPatchData->patchBounds, minV, maxV);
currentPatchData = fb.contactPatches + contactPatchCount;
initContactPatch(fb.contactPatches[contactPatchCount++], PxTo16(i), curContact.restitution,
curContact.staticFriction, curContact.dynamicFriction, PxU8(curContact.materialFlags));
minV = V4LoadA(&curContact.point.x);
maxV = minV;
}
}
if(count!=1)
currentPatchData->count = count;
StoreBounds(currentPatchData->patchBounds, minV, maxV);
}
fb.contactPatchCount = contactPatchCount;
return true;
}
static PX_FORCE_INLINE void initFrictionPatch(FrictionPatch& p, const PxVec3& worldNormal, const PxTransform& body0Pose, const PxTransform& body1Pose,
PxReal restitution, PxReal staticFriction, PxReal dynamicFriction, PxU8 materialFlags)
{
p.body0Normal = body0Pose.rotateInv(worldNormal);
p.body1Normal = body1Pose.rotateInv(worldNormal);
p.relativeQuat = body0Pose.q.getConjugate() * body1Pose.q;
p.anchorCount = 0;
p.broken = 0;
p.staticFriction = staticFriction;
p.dynamicFriction = dynamicFriction;
p.restitution = restitution;
p.materialFlags = materialFlags;
}
bool correlatePatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxReal normalTolerance,
PxU32 startContactPatchIndex,
PxU32 startFrictionPatchIndex)
{
bool overflow = false;
PxU32 frictionPatchCount = fb.frictionPatchCount;
for(PxU32 i=startContactPatchIndex;i<fb.contactPatchCount;i++)
{
CorrelationBuffer::ContactPatchData &c = fb.contactPatches[i];
const PxVec3 patchNormal = cb[c.start].normal;
PxU32 j=startFrictionPatchIndex;
for(;j<frictionPatchCount && ((patchNormal.dot(fb.frictionPatchWorldNormal[j]) < normalTolerance)
|| fb.frictionPatches[j].restitution != c.restitution|| fb.frictionPatches[j].staticFriction != c.staticFriction ||
fb.frictionPatches[j].dynamicFriction != c.dynamicFriction);j++)
;
if(j==frictionPatchCount)
{
overflow |= j==CorrelationBuffer::MAX_FRICTION_PATCHES;
if(overflow)
continue;
initFrictionPatch(fb.frictionPatches[frictionPatchCount], patchNormal, bodyFrame0, bodyFrame1, c.restitution, c.staticFriction, c.dynamicFriction, c.flags);
fb.frictionPatchWorldNormal[j] = patchNormal;
fb.frictionPatchContactCounts[frictionPatchCount] = c.count;
fb.patchBounds[frictionPatchCount] = c.patchBounds;
fb.contactID[frictionPatchCount][0] = 0xffff;
fb.contactID[frictionPatchCount++][1] = 0xffff;
c.next = CorrelationBuffer::LIST_END;
}
else
{
fb.patchBounds[j].include(c.patchBounds);
fb.frictionPatchContactCounts[j] += c.count;
c.next = PxTo16(fb.correlationListHeads[j]);
}
fb.correlationListHeads[j] = i;
}
fb.frictionPatchCount = frictionPatchCount;
return overflow;
}
// run over the friction patches, trying to find two anchors per patch. If we already have
// anchors that are close, we keep them, which gives us persistent spring behavior
void growPatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU32 frictionPatchStartIndex,
PxReal frictionOffsetThreshold)
{
for(PxU32 i=frictionPatchStartIndex;i<fb.frictionPatchCount;i++)
{
FrictionPatch& fp = fb.frictionPatches[i];
if (fp.anchorCount == 2 || fb.correlationListHeads[i] == CorrelationBuffer::LIST_END)
{
const PxReal frictionPatchDiagonalSq = fb.patchBounds[i].getDimensions().magnitudeSquared();
const PxReal anchorSqDistance = (fp.body0Anchors[0] - fp.body0Anchors[1]).magnitudeSquared();
//If the squared distance between the anchors is more than a quarter of the patch diagonal, we can keep,
//otherwise the anchors are potentially clustered around a corner so force a rebuild of the patch
if (fb.frictionPatchContactCounts[i] == 0 || (anchorSqDistance * 4.f) >= frictionPatchDiagonalSq)
continue;
fp.anchorCount = 0;
}
PxVec3 worldAnchors[2];
PxU16 anchorCount = 0;
PxReal pointDistSq = 0.0f, dist0, dist1;
// if we have an anchor already, keep it
if(fp.anchorCount == 1)
{
worldAnchors[anchorCount++] = bodyFrame0.transform(fp.body0Anchors[0]);
}
const PxReal eps = 1e-8f;
for(PxU32 patch = fb.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = fb.contactPatches[patch].next)
{
CorrelationBuffer::ContactPatchData& cp = fb.contactPatches[patch];
for(PxU16 j=0;j<cp.count;j++)
{
const PxVec3& worldPoint = cb[cp.start+j].point;
if(cb[cp.start+j].separation < frictionOffsetThreshold)
{
switch(anchorCount)
{
case 0:
fb.contactID[i][0] = PxU16(cp.start+j);
worldAnchors[0] = worldPoint;
anchorCount++;
break;
case 1:
pointDistSq = (worldPoint-worldAnchors[0]).magnitudeSquared();
if (pointDistSq > eps)
{
fb.contactID[i][1] = PxU16(cp.start+j);
worldAnchors[1] = worldPoint;
anchorCount++;
}
break;
default: //case 2
dist0 = (worldPoint-worldAnchors[0]).magnitudeSquared();
dist1 = (worldPoint-worldAnchors[1]).magnitudeSquared();
if (dist0 > dist1)
{
if(dist0 > pointDistSq)
{
fb.contactID[i][1] = PxU16(cp.start+j);
worldAnchors[1] = worldPoint;
pointDistSq = dist0;
}
}
else if (dist1 > pointDistSq)
{
fb.contactID[i][0] = PxU16(cp.start+j);
worldAnchors[0] = worldPoint;
pointDistSq = dist1;
}
}
}
}
}
//PX_ASSERT(anchorCount > 0);
// add the new anchor(s) to the patch
for(PxU32 j = fp.anchorCount; j < anchorCount; j++)
{
fp.body0Anchors[j] = bodyFrame0.transformInv(worldAnchors[j]);
fp.body1Anchors[j] = bodyFrame1.transformInv(worldAnchors[j]);
}
// the block contact solver always reads at least one anchor per patch for performance reasons even if there are no valid patches,
// so we need to initialize this in the unexpected case that we have no anchors
if(anchorCount==0)
fp.body0Anchors[0] = fp.body1Anchors[0] = PxVec3(0);
fp.anchorCount = anchorCount;
}
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintSetupBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "DyConstraintPrep.h"
#include "PxsRigidBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraint1D4.h"
#include "foundation/PxSort.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
namespace physx
{
namespace Dy
{
namespace
{
void setConstants(PxReal& constant, PxReal& unbiasedConstant, PxReal& velMultiplier, PxReal& impulseMultiplier,
const Px1DConstraint& c, PxReal unitResponse, PxReal minRowResponse, PxReal erp, PxReal dt, PxReal recipdt,
const PxSolverBodyData& b0, const PxSolverBodyData& b1, const bool finished)
{
if(finished)
{
constant = 0.f;
unbiasedConstant = 0.f;
velMultiplier = 0.f;
impulseMultiplier = 0.f;
return;
}
PxReal nv = needsNormalVel(c) ? b0.projectVelocity(c.linear0, c.angular0) - b1.projectVelocity(c.linear1, c.angular1)
: 0;
setSolverConstants(constant, unbiasedConstant, velMultiplier, impulseMultiplier,
c, nv, unitResponse, minRowResponse, erp, dt, recipdt);
}
}
SolverConstraintPrepState::Enum setupSolverConstraint4
(PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows);
SolverConstraintPrepState::Enum setupSolverConstraint4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator)
{
//KS - we will never get here with constraints involving articulations so we don't need to stress about those in here
totalRows = 0;
Px1DConstraint allRows[MAX_CONSTRAINT_ROWS * 4];
Px1DConstraint* rows = allRows;
Px1DConstraint* rows2 = allRows;
PxU32 maxRows = 0;
PxU32 nbToPrep = MAX_CONSTRAINT_ROWS;
for (PxU32 a = 0; a < 4; ++a)
{
SolverConstraintShaderPrepDesc& shaderDesc = constraintShaderDescs[a];
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
if (!shaderDesc.solverPrep)
return SolverConstraintPrepState::eUNBATCHABLE;
PX_ASSERT(rows2 + nbToPrep <= allRows + MAX_CONSTRAINT_ROWS*4);
setupConstraintRows(rows2, nbToPrep);
rows2 += nbToPrep;
desc.invMassScales.linear0 = desc.invMassScales.linear1 = desc.invMassScales.angular0 = desc.invMassScales.angular1 = 1.0f;
desc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_ra, unused_rb;
//TAG:solverprepcall
const PxU32 constraintCount = desc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
desc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
desc.invMassScales,
shaderDesc.constantBlock,
desc.bodyFrame0, desc.bodyFrame1, desc.extendedLimits, unused_ra, unused_rb);
nbToPrep = constraintCount;
maxRows = PxMax(constraintCount, maxRows);
if (constraintCount == 0)
return SolverConstraintPrepState::eUNBATCHABLE;
desc.rows = rows;
desc.numRows = constraintCount;
rows += constraintCount;
}
return setupSolverConstraint4(constraintDescs, dt, recipdt, totalRows, allocator, maxRows);
}
SolverConstraintPrepState::Enum setupSolverConstraint4
(PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal recipdt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows)
{
const Vec4V zero = V4Zero();
Px1DConstraint* allSorted[MAX_CONSTRAINT_ROWS * 4];
PxU32 startIndex[4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS * 4];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS * 4];
PxU32 numRows = 0;
for (PxU32 a = 0; a < 4; ++a)
{
startIndex[a] = numRows;
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
Px1DConstraint** sorted = allSorted + numRows;
preprocessRows(sorted, desc.rows, angSqrtInvInertia0 + numRows, angSqrtInvInertia1 + numRows, desc.numRows,
desc.data0->sqrtInvInertia, desc.data1->sqrtInvInertia, desc.data0->invMass, desc.data1->invMass,
desc.invMassScales, desc.disablePreprocessing, desc.improvedSlerp);
numRows += desc.numRows;
}
const PxU32 stride = sizeof(SolverConstraint1DDynamic4);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeader4) + stride * maxRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if(NULL == ptr || (reinterpret_cast<PxU8*>(-1))==ptr)
{
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = NULL;
setConstraintLength(*desc.desc, 0);
desc.desc->writeBack = desc.writeback;
}
if(NULL==ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr=NULL;
return SolverConstraintPrepState::eOUT_OF_MEMORY;
}
}
//desc.constraint = ptr;
totalRows = numRows;
for(PxU32 a = 0; a < 4; ++a)
{
PxSolverConstraintPrepDesc& desc = constraintDescs[a];
desc.desc->constraint = ptr;
setConstraintLength(*desc.desc, constraintLength);
desc.desc->writeBack = desc.writeback;
}
const PxReal erp[4] = { 1.0f, 1.0f, 1.0f, 1.0f};
//OK, now we build all 4 constraints into a single set of rows
{
PxU8* currPtr = ptr;
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(currPtr);
currPtr += sizeof(SolverConstraint1DHeader4);
const PxSolverBodyData& bd00 = *constraintDescs[0].data0;
const PxSolverBodyData& bd01 = *constraintDescs[1].data0;
const PxSolverBodyData& bd02 = *constraintDescs[2].data0;
const PxSolverBodyData& bd03 = *constraintDescs[3].data0;
const PxSolverBodyData& bd10 = *constraintDescs[0].data1;
const PxSolverBodyData& bd11 = *constraintDescs[1].data1;
const PxSolverBodyData& bd12 = *constraintDescs[2].data1;
const PxSolverBodyData& bd13 = *constraintDescs[3].data1;
//Load up masses, invInertia, velocity etc.
const Vec4V invMassScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.linear0, constraintDescs[1].invMassScales.linear0,
constraintDescs[2].invMassScales.linear0, constraintDescs[3].invMassScales.linear0);
const Vec4V invMassScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.linear1, constraintDescs[1].invMassScales.linear1,
constraintDescs[2].invMassScales.linear1, constraintDescs[3].invMassScales.linear1);
const Vec4V iMass0 = V4LoadXYZW(bd00.invMass, bd01.invMass, bd02.invMass, bd03.invMass);
const Vec4V iMass1 = V4LoadXYZW(bd10.invMass, bd11.invMass, bd12.invMass, bd13.invMass);
const Vec4V invMass0 = V4Mul(iMass0, invMassScale0);
const Vec4V invMass1 = V4Mul(iMass1, invMassScale1);
const Vec4V invInertiaScale0 = V4LoadXYZW(constraintDescs[0].invMassScales.angular0, constraintDescs[1].invMassScales.angular0,
constraintDescs[2].invMassScales.angular0, constraintDescs[3].invMassScales.angular0);
const Vec4V invInertiaScale1 = V4LoadXYZW(constraintDescs[0].invMassScales.angular1, constraintDescs[1].invMassScales.angular1,
constraintDescs[2].invMassScales.angular1, constraintDescs[3].invMassScales.angular1);
//Velocities
Vec4V linVel00 = V4LoadA(&bd00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&bd10.linearVelocity.x);
Vec4V angVel00 = V4LoadA(&bd00.angularVelocity.x);
Vec4V angVel01 = V4LoadA(&bd10.angularVelocity.x);
Vec4V linVel10 = V4LoadA(&bd01.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&bd11.linearVelocity.x);
Vec4V angVel10 = V4LoadA(&bd01.angularVelocity.x);
Vec4V angVel11 = V4LoadA(&bd11.angularVelocity.x);
Vec4V linVel20 = V4LoadA(&bd02.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&bd12.linearVelocity.x);
Vec4V angVel20 = V4LoadA(&bd02.angularVelocity.x);
Vec4V angVel21 = V4LoadA(&bd12.angularVelocity.x);
Vec4V linVel30 = V4LoadA(&bd03.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&bd13.linearVelocity.x);
Vec4V angVel30 = V4LoadA(&bd03.angularVelocity.x);
Vec4V angVel31 = V4LoadA(&bd13.angularVelocity.x);
Vec4V linVel0T0, linVel0T1, linVel0T2;
Vec4V linVel1T0, linVel1T1, linVel1T2;
Vec4V angVel0T0, angVel0T1, angVel0T2;
Vec4V angVel1T0, angVel1T1, angVel1T2;
PX_TRANSPOSE_44_34(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2);
PX_TRANSPOSE_44_34(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2);
PX_TRANSPOSE_44_34(angVel00, angVel10, angVel20, angVel30, angVel0T0, angVel0T1, angVel0T2);
PX_TRANSPOSE_44_34(angVel01, angVel11, angVel21, angVel31, angVel1T0, angVel1T1, angVel1T2);
//body world offsets
Vec4V workOffset0 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[0].body0WorldOffset));
Vec4V workOffset1 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[1].body0WorldOffset));
Vec4V workOffset2 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[2].body0WorldOffset));
Vec4V workOffset3 = Vec4V_From_Vec3V(V3LoadU(constraintDescs[3].body0WorldOffset));
Vec4V workOffsetX, workOffsetY, workOffsetZ;
PX_TRANSPOSE_44_34(workOffset0, workOffset1, workOffset2, workOffset3, workOffsetX, workOffsetY, workOffsetZ);
const FloatV dtV = FLoad(dt);
const Vec4V linBreakForce = V4LoadXYZW(constraintDescs[0].linBreakForce, constraintDescs[1].linBreakForce,
constraintDescs[2].linBreakForce, constraintDescs[3].linBreakForce);
const Vec4V angBreakForce = V4LoadXYZW(constraintDescs[0].angBreakForce, constraintDescs[1].angBreakForce,
constraintDescs[2].angBreakForce, constraintDescs[3].angBreakForce);
header->break0 = PxU8((constraintDescs[0].linBreakForce != PX_MAX_F32) || (constraintDescs[0].angBreakForce != PX_MAX_F32));
header->break1 = PxU8((constraintDescs[1].linBreakForce != PX_MAX_F32) || (constraintDescs[1].angBreakForce != PX_MAX_F32));
header->break2 = PxU8((constraintDescs[2].linBreakForce != PX_MAX_F32) || (constraintDescs[2].angBreakForce != PX_MAX_F32));
header->break3 = PxU8((constraintDescs[3].linBreakForce != PX_MAX_F32) || (constraintDescs[3].angBreakForce != PX_MAX_F32));
//OK, I think that's everything loaded in
header->invMass0D0 = invMass0;
header->invMass1D1 = invMass1;
header->angD0 = invInertiaScale0;
header->angD1 = invInertiaScale1;
header->body0WorkOffsetX = workOffsetX;
header->body0WorkOffsetY = workOffsetY;
header->body0WorkOffsetZ = workOffsetZ;
header->count = maxRows;
header->type = DY_SC_TYPE_BLOCK_1D;
header->linBreakImpulse = V4Scale(linBreakForce, dtV);
header->angBreakImpulse = V4Scale(angBreakForce, dtV);
header->count0 = PxTo8(constraintDescs[0].numRows);
header->count1 = PxTo8(constraintDescs[1].numRows);
header->count2 = PxTo8(constraintDescs[2].numRows);
header->count3 = PxTo8(constraintDescs[3].numRows);
//Now we loop over the constraints and build the results...
PxU32 index0 = 0;
PxU32 endIndex0 = constraintDescs[0].numRows - 1;
PxU32 index1 = startIndex[1];
PxU32 endIndex1 = index1 + constraintDescs[1].numRows - 1;
PxU32 index2 = startIndex[2];
PxU32 endIndex2 = index2 + constraintDescs[2].numRows - 1;
PxU32 index3 = startIndex[3];
PxU32 endIndex3 = index3 + constraintDescs[3].numRows - 1;
const FloatV one = FOne();
for(PxU32 a = 0; a < maxRows; ++a)
{
SolverConstraint1DDynamic4* c = reinterpret_cast<SolverConstraint1DDynamic4*>(currPtr);
currPtr += stride;
Px1DConstraint* con0 = allSorted[index0];
Px1DConstraint* con1 = allSorted[index1];
Px1DConstraint* con2 = allSorted[index2];
Px1DConstraint* con3 = allSorted[index3];
Vec4V cangDelta00 = V4LoadA(&angSqrtInvInertia0[index0].x);
Vec4V cangDelta01 = V4LoadA(&angSqrtInvInertia0[index1].x);
Vec4V cangDelta02 = V4LoadA(&angSqrtInvInertia0[index2].x);
Vec4V cangDelta03 = V4LoadA(&angSqrtInvInertia0[index3].x);
Vec4V cangDelta10 = V4LoadA(&angSqrtInvInertia1[index0].x);
Vec4V cangDelta11 = V4LoadA(&angSqrtInvInertia1[index1].x);
Vec4V cangDelta12 = V4LoadA(&angSqrtInvInertia1[index2].x);
Vec4V cangDelta13 = V4LoadA(&angSqrtInvInertia1[index3].x);
index0 = index0 == endIndex0 ? index0 : index0 + 1;
index1 = index1 == endIndex1 ? index1 : index1 + 1;
index2 = index2 == endIndex2 ? index2 : index2 + 1;
index3 = index3 == endIndex3 ? index3 : index3 + 1;
Vec4V driveScale = V4Splat(one);
if (con0->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[0].driveLimitsAreForces)
driveScale = V4SetX(driveScale, FMin(one, dtV));
if (con1->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[1].driveLimitsAreForces)
driveScale = V4SetY(driveScale, FMin(one, dtV));
if (con2->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[2].driveLimitsAreForces)
driveScale = V4SetZ(driveScale, FMin(one, dtV));
if (con3->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[3].driveLimitsAreForces)
driveScale = V4SetW(driveScale, FMin(one, dtV));
Vec4V clin00 = V4LoadA(&con0->linear0.x);
Vec4V clin01 = V4LoadA(&con1->linear0.x);
Vec4V clin02 = V4LoadA(&con2->linear0.x);
Vec4V clin03 = V4LoadA(&con3->linear0.x);
Vec4V cang00 = V4LoadA(&con0->angular0.x);
Vec4V cang01 = V4LoadA(&con1->angular0.x);
Vec4V cang02 = V4LoadA(&con2->angular0.x);
Vec4V cang03 = V4LoadA(&con3->angular0.x);
Vec4V clin0X, clin0Y, clin0Z;
Vec4V cang0X, cang0Y, cang0Z;
PX_TRANSPOSE_44_34(clin00, clin01, clin02, clin03, clin0X, clin0Y, clin0Z);
PX_TRANSPOSE_44_34(cang00, cang01, cang02, cang03, cang0X, cang0Y, cang0Z);
const Vec4V maxImpulse = V4LoadXYZW(con0->maxImpulse, con1->maxImpulse, con2->maxImpulse, con3->maxImpulse);
const Vec4V minImpulse = V4LoadXYZW(con0->minImpulse, con1->minImpulse, con2->minImpulse, con3->minImpulse);
Vec4V angDelta0X, angDelta0Y, angDelta0Z;
PX_TRANSPOSE_44_34(cangDelta00, cangDelta01, cangDelta02, cangDelta03, angDelta0X, angDelta0Y, angDelta0Z);
c->flags[0] = 0;
c->flags[1] = 0;
c->flags[2] = 0;
c->flags[3] = 0;
c->lin0X = clin0X;
c->lin0Y = clin0Y;
c->lin0Z = clin0Z;
c->ang0X = angDelta0X;
c->ang0Y = angDelta0Y;
c->ang0Z = angDelta0Z;
c->ang0WritebackX = cang0X;
c->ang0WritebackY = cang0Y;
c->ang0WritebackZ = cang0Z;
c->minImpulse = V4Mul(minImpulse, driveScale);
c->maxImpulse = V4Mul(maxImpulse, driveScale);
c->appliedForce = zero;
const Vec4V lin0MagSq = V4MulAdd(clin0Z, clin0Z, V4MulAdd(clin0Y, clin0Y, V4Mul(clin0X, clin0X)));
const Vec4V cang0DotAngDelta = V4MulAdd(angDelta0Z, angDelta0Z, V4MulAdd(angDelta0Y, angDelta0Y, V4Mul(angDelta0X, angDelta0X)));
c->flags[0] = 0;
c->flags[1] = 0;
c->flags[2] = 0;
c->flags[3] = 0;
Vec4V unitResponse = V4MulAdd(lin0MagSq, invMass0, V4Mul(cang0DotAngDelta, invInertiaScale0));
Vec4V clin10 = V4LoadA(&con0->linear1.x);
Vec4V clin11 = V4LoadA(&con1->linear1.x);
Vec4V clin12 = V4LoadA(&con2->linear1.x);
Vec4V clin13 = V4LoadA(&con3->linear1.x);
Vec4V cang10 = V4LoadA(&con0->angular1.x);
Vec4V cang11 = V4LoadA(&con1->angular1.x);
Vec4V cang12 = V4LoadA(&con2->angular1.x);
Vec4V cang13 = V4LoadA(&con3->angular1.x);
Vec4V clin1X, clin1Y, clin1Z;
Vec4V cang1X, cang1Y, cang1Z;
PX_TRANSPOSE_44_34(clin10, clin11, clin12, clin13, clin1X, clin1Y, clin1Z);
PX_TRANSPOSE_44_34(cang10, cang11, cang12, cang13, cang1X, cang1Y, cang1Z);
Vec4V angDelta1X, angDelta1Y, angDelta1Z;
PX_TRANSPOSE_44_34(cangDelta10, cangDelta11, cangDelta12, cangDelta13, angDelta1X, angDelta1Y, angDelta1Z);
const Vec4V lin1MagSq = V4MulAdd(clin1Z, clin1Z, V4MulAdd(clin1Y, clin1Y, V4Mul(clin1X, clin1X)));
const Vec4V cang1DotAngDelta = V4MulAdd(angDelta1Z, angDelta1Z, V4MulAdd(angDelta1Y, angDelta1Y, V4Mul(angDelta1X, angDelta1X)));
c->lin1X = clin1X;
c->lin1Y = clin1Y;
c->lin1Z = clin1Z;
c->ang1X = angDelta1X;
c->ang1Y = angDelta1Y;
c->ang1Z = angDelta1Z;
unitResponse = V4Add(unitResponse, V4MulAdd(lin1MagSq, invMass1, V4Mul(cang1DotAngDelta, invInertiaScale1)));
Vec4V linProj0(V4Mul(clin0X, linVel0T0));
Vec4V linProj1(V4Mul(clin1X, linVel1T0));
Vec4V angProj0(V4Mul(cang0X, angVel0T0));
Vec4V angProj1(V4Mul(cang1X, angVel1T0));
linProj0 = V4MulAdd(clin0Y, linVel0T1, linProj0);
linProj1 = V4MulAdd(clin1Y, linVel1T1, linProj1);
angProj0 = V4MulAdd(cang0Y, angVel0T1, angProj0);
angProj1 = V4MulAdd(cang1Y, angVel1T1, angProj1);
linProj0 = V4MulAdd(clin0Z, linVel0T2, linProj0);
linProj1 = V4MulAdd(clin1Z, linVel1T2, linProj1);
angProj0 = V4MulAdd(cang0Z, angVel0T2, angProj0);
angProj1 = V4MulAdd(cang1Z, angVel1T2, angProj1);
const Vec4V projectVel0 = V4Add(linProj0, angProj0);
const Vec4V projectVel1 = V4Add(linProj1, angProj1);
const Vec4V normalVel = V4Sub(projectVel0, projectVel1);
{
const PxVec4& ur = reinterpret_cast<const PxVec4&>(unitResponse);
PxVec4& cConstant = reinterpret_cast<PxVec4&>(c->constant);
PxVec4& cUnbiasedConstant = reinterpret_cast<PxVec4&>(c->unbiasedConstant);
PxVec4& cVelMultiplier = reinterpret_cast<PxVec4&>(c->velMultiplier);
PxVec4& cImpulseMultiplier = reinterpret_cast<PxVec4&>(c->impulseMultiplier);
setConstants(cConstant.x, cUnbiasedConstant.x, cVelMultiplier.x, cImpulseMultiplier.x,
*con0, ur.x, constraintDescs[0].minResponseThreshold, erp[0], dt, recipdt,
*constraintDescs[0].data0, *constraintDescs[0].data1, a >= constraintDescs[0].numRows);
setConstants(cConstant.y, cUnbiasedConstant.y, cVelMultiplier.y, cImpulseMultiplier.y,
*con1, ur.y, constraintDescs[1].minResponseThreshold, erp[1], dt, recipdt,
*constraintDescs[1].data0, *constraintDescs[1].data1, a >= constraintDescs[1].numRows);
setConstants(cConstant.z, cUnbiasedConstant.z, cVelMultiplier.z, cImpulseMultiplier.z,
*con2, ur.z, constraintDescs[2].minResponseThreshold, erp[2], dt, recipdt,
*constraintDescs[2].data0, *constraintDescs[2].data1, a >= constraintDescs[2].numRows);
setConstants(cConstant.w, cUnbiasedConstant.w, cVelMultiplier.w, cImpulseMultiplier.w,
*con3, ur.w, constraintDescs[3].minResponseThreshold, erp[3], dt, recipdt,
*constraintDescs[3].data0, *constraintDescs[3].data1, a >= constraintDescs[3].numRows);
}
const Vec4V velBias = V4Mul(c->velMultiplier, normalVel);
c->constant = V4Add(c->constant, velBias);
c->unbiasedConstant = V4Add(c->unbiasedConstant, velBias);
if(con0->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[0] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con1->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[1] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con2->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[2] |= DY_SC_FLAG_OUTPUT_FORCE;
if(con3->flags & Px1DConstraintFlag::eOUTPUT_FORCE)
c->flags[3] |= DY_SC_FLAG_OUTPUT_FORCE;
}
*(reinterpret_cast<PxU32*>(currPtr)) = 0;
*(reinterpret_cast<PxU32*>(currPtr + 4)) = 0;
}
//OK, we're ready to allocate and solve prep these constraints now :-)
return SolverConstraintPrepState::eSUCCESS;
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrep.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 DY_ARTICULATION_CONTACT_PREP_H
#define DY_ARTICULATION_CONTACT_PREP_H
#include "DySolverExt.h"
#include "foundation/PxVecMath.h"
namespace physx
{
struct PxcNpWorkUnit;
class PxContactBuffer;
struct PxContactPoint;
namespace Dy
{
struct CorrelationBuffer;
PxReal getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxReal dom0, PxReal angDom0,
const SolverExtBody& b1, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal dom1, PxReal angDom1,
Cm::SpatialVectorF* Z, bool allowSelfCollision = false);
aos::FloatV getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const aos::FloatV& dom0, const aos::FloatV& angDom0,
const SolverExtBody& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const aos::FloatV& dom1, const aos::FloatV& angDom1,
Cm::SpatialVectorV* Z, bool allowSelfCollision = false);
Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBody& body);
Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBody& body);
void setupFinalizeExtSolverContacts(
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const SolverExtBody& b0,
const SolverExtBody& b1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDistance, PxU8* frictionDataPtr,
PxReal ccdMaxContactDist,
Cm::SpatialVectorF* Z,
const PxReal offsetSlop);
bool setupFinalizeExtSolverContactsCoulomb(
const PxContactBuffer& buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
PxReal invDt,
PxReal dtF32,
PxReal bounceThreshold,
const SolverExtBody& b0,
const SolverExtBody& b1,
PxU32 frictionCountPerPoint,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
PxReal restDist,
PxReal ccdMaxContactDist,
Cm::SpatialVectorF* Z,
const PxReal solverOffsetSlop);
} //namespace Dy
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationUtils.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 DY_ARTICULATION_UTILS_H
#define DY_ARTICULATION_UTILS_H
#include "foundation/PxBitUtils.h"
#include "foundation/PxVecMath.h"
#include "CmSpatialVector.h"
#include "DyVArticulation.h"
namespace physx
{
namespace Dy
{
struct ArticulationCore;
struct ArticulationLink;
#define DY_ARTICULATION_DEBUG_VERIFY 0
PX_FORCE_INLINE PxU32 ArticulationLowestSetBit(ArticulationBitField val)
{
PxU32 low = PxU32(val&0xffffffff), high = PxU32(val>>32);
PxU32 mask = PxU32((!low)-1);
PxU32 result = (mask&PxLowestSetBitUnsafe(low)) | ((~mask)&(PxLowestSetBitUnsafe(high)+32));
PX_ASSERT(val & (PxU64(1)<<result));
PX_ASSERT(!(val & ((PxU64(1)<<result)-1)));
return result;
}
PX_FORCE_INLINE PxU32 ArticulationHighestSetBit(ArticulationBitField val)
{
PxU32 low = PxU32(val & 0xffffffff), high = PxU32(val >> 32);
PxU32 mask = PxU32((!high) - 1);
PxU32 result = ((~mask)&PxHighestSetBitUnsafe(low)) | ((mask)&(PxHighestSetBitUnsafe(high) + 32));
PX_ASSERT(val & (PxU64(1) << result));
return result;
}
using namespace aos;
PX_FORCE_INLINE Cm::SpatialVector& unsimdRef(Cm::SpatialVectorV& v) { return reinterpret_cast<Cm::SpatialVector&>(v); }
PX_FORCE_INLINE const Cm::SpatialVector& unsimdRef(const Cm::SpatialVectorV& v) { return reinterpret_cast<const Cm::SpatialVector&>(v); }
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSDynamics.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 DY_TGS_DYNAMICS_H
#define DY_TGS_DYNAMICS_H
#include "PxvConfig.h"
#include "CmSpatialVector.h"
#include "CmTask.h"
#include "CmPool.h"
#include "PxcThreadCoherentCache.h"
#include "DyThreadContext.h"
#include "PxcConstraintBlockStream.h"
#include "DySolverBody.h"
#include "DyContext.h"
#include "PxsIslandManagerTypes.h"
#include "PxvNphaseImplementationContext.h"
#include "solver/PxSolverDefs.h"
#include "PxsIslandSim.h"
namespace physx
{
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
}
class PxsRigidBody;
struct PxsBodyCore;
class PxsIslandIndices;
struct PxsIndexedInteraction;
struct PxsIndexedContactManager;
namespace Dy
{
struct SolverContext;
struct SolverIslandObjectsStep
{
PxsRigidBody** bodies;
FeatherstoneArticulation** articulations;
FeatherstoneArticulation** articulationOwners;
PxsIndexedContactManager* contactManagers;
const IG::IslandId* islandIds;
PxU32 numIslands;
PxU32* bodyRemapTable;
PxU32* nodeIndexArray;
PxSolverConstraintDesc* constraintDescs;
PxSolverConstraintDesc* orderedConstraintDescs;
PxSolverConstraintDesc* tempConstraintDescs;
PxConstraintBatchHeader* constraintBatchHeaders;
Cm::SpatialVector* motionVelocities;
PxsBodyCore** bodyCoreArray;
PxU32 solverBodyOffset;
SolverIslandObjectsStep() : bodies(NULL), articulations(NULL), articulationOwners(NULL),
contactManagers(NULL), islandIds(NULL), numIslands(0), nodeIndexArray(NULL), constraintDescs(NULL), motionVelocities(NULL), bodyCoreArray(NULL),
solverBodyOffset(0)
{
}
};
struct IslandContextStep
{
//The thread context for this island (set in in the island start task, released in the island end task)
ThreadContext* mThreadContext;
PxsIslandIndices mCounts;
SolverIslandObjectsStep mObjects;
PxU32 mPosIters;
PxU32 mVelIters;
PxU32 mArticulationOffset;
PxReal mStepDt;
PxReal mInvStepDt;
PxReal mBiasCoefficient;
PxI32 mSharedSolverIndex;
PxI32 mSolvedCount;
PxI32 mSharedRigidBodyIndex;
PxI32 mRigidBodyIntegratedCount;
PxI32 mSharedArticulationIndex;
PxI32 mArticulationIntegratedCount;
};
struct SolverIslandObjectsStep;
class SolverBodyVelDataPool : public PxArray<PxTGSSolverBodyVel, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyVel> > >
{
PX_NOCOPY(SolverBodyVelDataPool)
public:
SolverBodyVelDataPool() {}
};
class SolverBodyTxInertiaPool : public PxArray<PxTGSSolverBodyTxInertia, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyTxInertia> > >
{
PX_NOCOPY(SolverBodyTxInertiaPool)
public:
SolverBodyTxInertiaPool() {}
};
class SolverBodyDataStepPool : public PxArray<PxTGSSolverBodyData, PxAlignedAllocator<128, PxReflectionAllocator<PxTGSSolverBodyData> > >
{
PX_NOCOPY(SolverBodyDataStepPool)
public:
SolverBodyDataStepPool() {}
};
class SolverStepConstraintDescPool : public PxArray<PxSolverConstraintDesc, PxAlignedAllocator<128, PxReflectionAllocator<PxSolverConstraintDesc> > >
{
PX_NOCOPY(SolverStepConstraintDescPool)
public:
SolverStepConstraintDescPool() { }
};
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class DynamicsTGSContext : public Context
{
PX_NOCOPY(DynamicsTGSContext)
public:
DynamicsTGSContext(PxcNpMemBlockPool* memBlockPool,
PxcScratchAllocator& scratchAllocator,
Cm::FlushPool& taskPool,
PxvSimStats& simStats,
PxTaskManager* taskManager,
PxVirtualAllocatorCallback* allocator,
PxsMaterialManager* materialManager,
IG::SimpleIslandManager* islandManager,
PxU64 contextID,
bool enableStabilization,
bool useEnhancedDeterminism,
PxReal lengthScale
);
virtual ~DynamicsTGSContext();
// Context
virtual void destroy() PX_OVERRIDE;
virtual void update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask,
PxvNphaseImplementationContext* nphase, PxU32 maxPatchesPerCM, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& changedHandleMap) PX_OVERRIDE;
virtual void mergeResults() PX_OVERRIDE;
virtual void setSimulationController(PxsSimulationController* simulationController) PX_OVERRIDE { mSimulationController = simulationController; }
virtual PxSolverType::Enum getSolverType() const PX_OVERRIDE { return PxSolverType::eTGS; }
//~Context
/**
\brief Allocates and returns a thread context object.
\return A thread context.
*/
PX_FORCE_INLINE ThreadContext* getThreadContext() { return mThreadContextPool.get(); }
/**
\brief Returns a thread context to the thread context pool.
\param[in] context The thread context to return to the thread context pool.
*/
void putThreadContext(ThreadContext* context) { mThreadContextPool.put(context); }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() { return mTaskPool; }
PX_FORCE_INLINE ThresholdStream& getThresholdStream() { return *mThresholdStream; }
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE PxU32 getKinematicCount() const { return mKinematicCount; }
void updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks);
protected:
// PT: TODO: the thread stats are missing for TGS
/*#if PX_ENABLE_SIM_STATS
void addThreadStats(const ThreadContext::ThreadSimStats& stats);
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif*/
// Solver helper-methods
/**
\brief Computes the unconstrained velocity for a given PxsRigidBody
\param[in] atom The PxsRigidBody
*/
void computeUnconstrainedVelocity(PxsRigidBody* atom) const;
/**
\brief fills in a PxSolverConstraintDesc from an indexed interaction
\param[in,out] desc The PxSolverConstraintDesc
\param[in] constraint The PxsIndexedInteraction
*/
void setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim,
const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies);
void setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex,
const IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies);
void solveIsland(const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts,
PxU32 solverBodyOffset,
IG::SimpleIslandManager& islandManager,
PxU32* bodyRemapTable, PxsMaterialManager* materialManager,
PxsContactManagerOutputIterator& iterator,
PxBaseTask* continuation);
void prepareBodiesAndConstraints(const SolverIslandObjectsStep& objects,
IG::SimpleIslandManager& islandManager,
IslandContextStep& islandContext);
void setupDescs(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, PxU32* mBodyRemapTable, PxU32 mSolverBodyOffset,
PxsContactManagerOutputIterator& outputs);
void preIntegrateBodies(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray,
PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2,
PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxU32 iteration);
void setupArticulations(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxBaseTask* continuation);
PxU32 setupArticulationInternalConstraints(IslandContextStep& islandContext, PxReal dt, PxReal invStepDt);
void createSolverConstraints(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders,
PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& islandThreadContext, Dy::ThreadContext& threadContext, PxReal stepDt, PxReal totalDt,
PxReal invStepDt, PxReal biasCoefficient, PxI32 velIters);
void solveConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxReal invStepDt,
const PxTGSSolverBodyTxInertia* const solverTxInertia, PxReal elapsedTime, PxReal minPenetration, SolverContext& cache);
template <bool TSync>
void solveConcludeConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders,
PxTGSSolverBodyTxInertia* solverTxInertia, PxReal elapsedTime, SolverContext& cache, PxU32 iterCount);
template <bool Sync>
void parallelSolveConstraints(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxTGSSolverBodyTxInertia* solverTxInertia,
PxReal elapsedTime, PxReal minPenetration, SolverContext& cache, PxU32 iterCount);
void writebackConstraintsIteration(const PxConstraintBatchHeader* const hdrs, const PxSolverConstraintDesc* const contactDescPtr, PxU32 nbHeaders);
void parallelWritebackConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders);
void integrateBodies(const SolverIslandObjectsStep& objects,
PxU32 count, PxTGSSolverBodyVel* vels,
PxTGSSolverBodyTxInertia* txInertias, const PxTGSSolverBodyData*const bodyDatas, PxReal dt, PxReal invTotalDt, bool averageBodies,
PxReal ratio);
void parallelIntegrateBodies(PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
const PxTGSSolverBodyData* const bodyDatas, PxU32 count, PxReal dt, PxU32 iteration, PxReal invTotalDt, bool average,
PxReal ratio);
void copyBackBodies(const SolverIslandObjectsStep& objects,
PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias,
PxTGSSolverBodyData* solverBodyData, PxReal invDt, IG::IslandSim& islandSim,
PxU32 startIdx, PxU32 endIdx);
void updateArticulations(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt);
void stepArticulations(Dy::ThreadContext& threadContext, const PxsIslandIndices& counts, PxReal dt, PxReal stepInvDt);
void iterativeSolveIsland(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxReal invStepDt, PxU32 posIters, PxU32 velIters, SolverContext& cache, PxReal ratio,
PxReal biasCoefficient);
void iterativeSolveIslandParallel(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext,
PxReal stepDt, PxU32 posIters, PxU32 velIters, PxI32* solverCounts, PxI32* integrationCounts, PxI32* articulationIntegrationCounts,
PxI32* solverProgressCount, PxI32* integrationProgressCount, PxI32* articulationProgressCount, PxU32 solverUnrollSize, PxU32 integrationUnrollSize,
PxReal ratio, PxReal biasCoefficient);
void endIsland(ThreadContext& mThreadContext);
void finishSolveIsland(ThreadContext& mThreadContext, const SolverIslandObjectsStep& objects,
const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, PxBaseTask* continuation);
/**
\brief Resets the thread contexts
*/
void resetThreadContexts();
/**
\brief Returns the scratch memory allocator.
\return The scratch memory allocator.
*/
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
//Data
PxTGSSolverBodyVel mWorldSolverBodyVel;
PxTGSSolverBodyTxInertia mWorldSolverBodyTxInertia;
PxTGSSolverBodyData mWorldSolverBodyData2;
/**
\brief A thread context pool
*/
PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool> mThreadContextPool;
/**
\brief Solver constraint desc array
*/
SolverStepConstraintDescPool mSolverConstraintDescPool;
SolverStepConstraintDescPool mOrderedSolverConstraintDescPool;
SolverStepConstraintDescPool mTempSolverConstraintDescPool;
PxArray<PxConstraintBatchHeader> mContactConstraintBatchHeaders;
/**
\brief Array of motion velocities for all bodies in the scene.
*/
PxArray<Cm::SpatialVector> mMotionVelocityArray;
/**
\brief Array of body core pointers for all bodies in the scene.
*/
PxArray<PxsBodyCore*> mBodyCoreArray;
/**
\brief Array of rigid body pointers for all bodies in the scene.
*/
PxArray<PxsRigidBody*> mRigidBodyArray;
/**
\brief Array of articulationpointers for all articulations in the scene.
*/
PxArray<FeatherstoneArticulation*> mArticulationArray;
SolverBodyVelDataPool mSolverBodyVelPool;
SolverBodyTxInertiaPool mSolverBodyTxInertiaPool;
SolverBodyDataStepPool mSolverBodyDataPool2;
ThresholdStream* mExceededForceThresholdStream[2]; //this store previous and current exceeded force thresholdStream
PxArray<PxU32> mExceededForceThresholdStreamMask;
PxArray<PxU32> mSolverBodyRemapTable; //Remaps from the "active island" index to the index within a solver island
PxArray<PxU32> mNodeIndexArray; //island node index
PxArray<PxsIndexedContactManager> mContactList;
/**
\brief The total number of kinematic bodies in the scene
*/
PxU32 mKinematicCount;
/**
\brief Atomic counter for the number of threshold stream elements.
*/
PxI32 mThresholdStreamOut;
PxsMaterialManager* mMaterialManager;
PxsContactManagerOutputIterator mOutputIterator;
private:
//private:
PxcScratchAllocator& mScratchAllocator;
Cm::FlushPool& mTaskPool;
PxTaskManager* mTaskManager;
PxU32 mCurrentIndex; // this is the index point to the current exceeded force threshold stream
friend class SetupDescsTask;
friend class PreIntegrateTask;
friend class SetupArticulationTask;
friend class SetupArticulationInternalConstraintsTask;
friend class SetupSolverConstraintsTask;
friend class SolveIslandTask;
friend class EndIslandTask;
friend class SetupSolverConstraintsSubTask;
friend class ParallelSolveTask;
friend class PreIntegrateParallelTask;
friend class CopyBackTask;
friend class UpdateArticTask;
friend class FinishSolveIslandTask;
};
#if PX_VC
#pragma warning(pop)
#endif
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "PxcNpWorkUnit.h"
#include "DyThreadContext.h"
#include "PxcNpContactPrepShared.h"
#include "DyConstraintPrep.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "DyContactPrepShared.h"
using namespace aos;
namespace physx
{
namespace Dy
{
PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3] =
{
createFinalizeSolverContacts,
createFinalizeSolverContactsCoulomb1D,
createFinalizeSolverContactsCoulomb2D
};
static void setupFinalizeSolverConstraints(Sc::ShapeInteraction* shapeInteraction,
const PxContactPoint* buffer,
const CorrelationBuffer& c,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU8* workspace,
const PxSolverBodyData& data0,
const PxSolverBodyData& data1,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal invMassScale0, PxReal invInertiaScale0,
PxReal invMassScale1, PxReal invInertiaScale1,
bool hasForceThreshold, bool staticOrKinematicBody,
const PxReal restDist, PxU8* frictionDataPtr,
const PxReal maxCCDSeparation,
const PxReal solverOffsetSlopF32)
{
// NOTE II: the friction patches are sparse (some of them have no contact patches, and
// therefore did not get written back to the cache) but the patch addresses are dense,
// corresponding to valid patches
const Vec3V solverOffsetSlop = V3Load(solverOffsetSlopF32);
const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation);
PxU8 flags = PxU8(hasForceThreshold ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0);
PxU8* PX_RESTRICT ptr = workspace;
PxU8 type = PxTo8(staticOrKinematicBody ? DY_SC_TYPE_STATIC_CONTACT
: DY_SC_TYPE_RB_CONTACT);
const FloatV zero=FZero();
const Vec3V v3Zero = V3Zero();
const FloatV d0 = FLoad(invMassScale0);
const FloatV d1 = FLoad(invMassScale1);
const FloatV angD0 = FLoad(invInertiaScale0);
const FloatV angD1 = FLoad(invInertiaScale1);
const FloatV nDom1fV = FNeg(d1);
const FloatV invMass0 = FLoad(data0.invMass);
const FloatV invMass1 = FLoad(data1.invMass);
const FloatV invMass0_dom0fV = FMul(d0, invMass0);
const FloatV invMass1_dom1fV = FMul(nDom1fV, invMass1);
Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero();
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass0_dom0fV);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, invMass1_dom1fV);
const FloatV restDistance = FLoad(restDist);
const FloatV maxPenBias = FMax(FLoad(data0.penBiasClamp), FLoad(data1.penBiasClamp));
const QuatV bodyFrame0q = QuatVLoadU(&bodyFrame0.q.x);
const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p);
const QuatV bodyFrame1q = QuatVLoadU(&bodyFrame1.q.x);
const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p);
PxU32 frictionPatchWritebackAddrIndex = 0;
PxPrefetchLine(c.contactID);
PxPrefetchLine(c.contactID, 128);
const Vec3V linVel0 = V3LoadU_SafeReadW(data0.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V linVel1 = V3LoadU_SafeReadW(data1.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData
const Vec3V angVel0 = V3LoadU_SafeReadW(data0.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
const Vec3V angVel1 = V3LoadU_SafeReadW(data1.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData
PX_ALIGN(16, const Mat33V invSqrtInertia0)
(
V3LoadU_SafeReadW(data0.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(data0.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(data0.sqrtInvInertia.column2)
);
PX_ALIGN(16, const Mat33V invSqrtInertia1)
(
V3LoadU_SafeReadW(data1.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33
V3LoadU_SafeReadW(data1.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33
V3LoadU(data1.sqrtInvInertia.column2)
);
const FloatV invDt = FLoad(invDtF32);
const FloatV p8 = FLoad(0.8f);
const FloatV bounceThreshold = FLoad(bounceThresholdF32);
const FloatV invDtp8 = FMul(invDt, p8);
const FloatV dt = FLoad(dtF32);
for(PxU32 i=0;i<c.frictionPatchCount;i++)
{
PxU32 contactCount = c.frictionPatchContactCounts[i];
if(contactCount == 0)
continue;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
PX_ASSERT(frictionPatch.anchorCount <= 2);
PxU32 firstPatch = c.correlationListHeads[i];
const PxContactPoint* contactBase0 = buffer + c.contactPatches[firstPatch].start;
SolverContactHeader* PX_RESTRICT header = reinterpret_cast<SolverContactHeader*>(ptr);
ptr += sizeof(SolverContactHeader);
PxPrefetchLine(ptr, 128);
PxPrefetchLine(ptr, 256);
header->shapeInteraction = shapeInteraction;
header->flags = flags;
FStore(invMass0_dom0fV, &header->invMass0);
FStore(FNeg(invMass1_dom1fV), &header->invMass1);
const FloatV restitution = FLoad(contactBase0->restitution);
const FloatV damping = FLoad(contactBase0->damping);
PxU32 pointStride = sizeof(SolverContactPoint);
PxU32 frictionStride = sizeof(SolverContactFriction);
const Vec3V normal = V3LoadA(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV normalLenSq = V3LengthSq(normal);
const VecCrossV norCross = V3PrepareCross(normal);
const FloatV norVel = V3SumElems(V3NegMulSub(normal, linVel1, V3Mul(normal, linVel0)));
const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq);
const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq);
header->normal_minAppliedImpulseForFrictionW = Vec4V_From_Vec3V(normal);
for(PxU32 patch=c.correlationListHeads[i];
patch!=CorrelationBuffer::LIST_END;
patch = c.contactPatches[patch].next)
{
const PxU32 count = c.contactPatches[patch].count;
const PxContactPoint* contactBase = buffer + c.contactPatches[patch].start;
PxU8* p = ptr;
for(PxU32 j=0;j<count;j++)
{
PxPrefetchLine(p, 256);
const PxContactPoint& contact = contactBase[j];
SolverContactPoint* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPoint*>(p);
p += pointStride;
constructContactConstraint(invSqrtInertia0, invSqrtInertia1, invMassNorLenSq0,
invMassNorLenSq1, angD0, angD1, bodyFrame0p, bodyFrame1p,
normal, norVel, norCross, angVel0, angVel1,
invDt, invDtp8, dt, restDistance, maxPenBias, restitution,
bounceThreshold, contact, *solverContact,
ccdMaxSeparation, solverOffsetSlop, damping);
}
ptr = p;
}
PxF32* forceBuffers = reinterpret_cast<PxF32*>(ptr);
PxMemZero(forceBuffers, sizeof(PxF32) * contactCount);
ptr += ((contactCount + 3) & (~3)) * sizeof(PxF32); // jump to next 16-byte boundary
const PxReal frictionCoefficient = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f;
const PxReal staticFriction = contactBase0->staticFriction * frictionCoefficient;
const PxReal dynamicFriction = contactBase0->dynamicFriction* frictionCoefficient;
const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION);
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(staticFriction));
staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(dynamicFriction));
const bool haveFriction = (disableStrongFriction == 0 && frictionPatch.anchorCount != 0);//PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;
header->numNormalConstr = PxTo8(contactCount);
header->numFrictionConstr = PxTo8(haveFriction ? frictionPatch.anchorCount*2 : 0);
header->type = type;
header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W;
FStore(angD0, &header->angDom0);
FStore(angD1, &header->angDom1);
header->broken = 0;
if(haveFriction)
{
const Vec3V linVrel = V3Sub(linVel0, linVel1);
//const Vec3V normal = Vec3V_From_PxVec3_Aligned(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal);
const FloatV orthoThreshold = FLoad(0.70710678f);
const FloatV p1 = FLoad(0.0001f);
// fallback: normal.cross((1,0,0)) or normal.cross((0,0,1))
const FloatV normalX = V3GetX(normal);
const FloatV normalY = V3GetY(normal);
const FloatV normalZ = V3GetZ(normal);
Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY);
Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero);
Vec3V t0Fallback = V3Sel(FIsGrtr(orthoThreshold, FAbs(normalX)), t0Fallback1, t0Fallback2);
Vec3V t0 = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel)));
t0 = V3Sel(FIsGrtr(V3LengthSq(t0), p1), t0, t0Fallback);
t0 = V3Normalize(t0);
const VecCrossV t0Cross = V3PrepareCross(t0);
const Vec3V t1 = V3Cross(norCross, t0Cross);
const VecCrossV t1Cross = V3PrepareCross(t1);
// since we don't even have the body velocities we can't compute the tangent dirs, so
// the only thing we can do right now is to write the geometric information (which is the
// same for both axis constraints of an anchor) We put ra in the raXn field, rb in the rbXn
// field, and the error in the normal field. See corresponding comments in
// completeContactFriction()
//We want to set the writeBack ptr to point to the broken flag of the friction patch.
//On spu we have a slight problem here because the friction patch array is
//in local store rather than in main memory. The good news is that the address of the friction
//patch array in main memory is stored in the work unit. These two addresses will be equal
//except on spu where one is local store memory and the other is the effective address in main memory.
//Using the value stored in the work unit guarantees that the main memory address is used on all platforms.
PxU8* PX_RESTRICT writeback = frictionDataPtr + frictionPatchWritebackAddrIndex*sizeof(FrictionPatch);
header->frictionBrokenWritebackByte = writeback;
for(PxU32 j = 0; j < frictionPatch.anchorCount; j++)
{
PxPrefetchLine(ptr, 256);
PxPrefetchLine(ptr, 384);
SolverContactFriction* PX_RESTRICT f0 = reinterpret_cast<SolverContactFriction*>(ptr);
ptr += frictionStride;
SolverContactFriction* PX_RESTRICT f1 = reinterpret_cast<SolverContactFriction*>(ptr);
ptr += frictionStride;
Vec3V body0Anchor = V3LoadU(frictionPatch.body0Anchors[j]);
Vec3V body1Anchor = V3LoadU(frictionPatch.body1Anchors[j]);
const Vec3V ra = QuatRotate(bodyFrame0q, body0Anchor);
const Vec3V rb = QuatRotate(bodyFrame1q, body1Anchor);
/*ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), v3Zero, ra);
rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), v3Zero, rb);*/
PxU32 index = c.contactID[i][j];
Vec3V error = V3Sub(V3Add(ra, bodyFrame0p), V3Add(rb, bodyFrame1p));
error = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(error)), v3Zero, error);
index = index == 0xFFFF ? c.contactPatches[c.correlationListHeads[i]].start : index;
const Vec3V tvel = V3LoadA(buffer[index].targetVel);
{
Vec3V raXn = V3Cross(ra, t0Cross);
Vec3V rbXn = V3Cross(rb, t0Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn);
const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(raXnSqrtInertia, raXnSqrtInertia)));
const FloatV resp1 = FSub(FMul(angD1, V3Dot(rbXnSqrtInertia, rbXnSqrtInertia)), invMass1_dom1fV);
const FloatV resp = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(resp, zero), FDiv(p8, resp), zero);
FloatV targetVel = V3Dot(tvel, t0);
const FloatV vrel1 = FAdd(V3Dot(t0, linVel0), V3Dot(raXn, angVel0));
const FloatV vrel2 = FAdd(V3Dot(t0, linVel1), V3Dot(rbXn, angVel1));
const FloatV vrel = FSub(vrel1, vrel2);
targetVel = FSub(targetVel, vrel);
f0->normalXYZ_appliedForceW = V4SetW(t0, zero);
f0->raXnXYZ_velMultiplierW = V4SetW(raXnSqrtInertia, velMultiplier);
f0->rbXnXYZ_biasW = V4SetW(rbXnSqrtInertia, FMul(V3Dot(t0, error), invDt));
FStore(targetVel, &f0->targetVel);
}
{
Vec3V raXn = V3Cross(ra, t1Cross);
Vec3V rbXn = V3Cross(rb, t1Cross);
raXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rbXn)), V3Zero(), rbXn);
const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn);
const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn);
const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(raXnSqrtInertia, raXnSqrtInertia)));
const FloatV resp1 = FSub(FMul(angD1, V3Dot(rbXnSqrtInertia, rbXnSqrtInertia)), invMass1_dom1fV);
const FloatV resp = FAdd(resp0, resp1);
const FloatV velMultiplier = FSel(FIsGrtr(resp, zero), FDiv(p8, resp), zero);
FloatV targetVel = V3Dot(tvel, t1);
const FloatV vrel1 = FAdd(V3Dot(t1, linVel0), V3Dot(raXn, angVel0));
const FloatV vrel2 = FAdd(V3Dot(t1, linVel1), V3Dot(rbXn, angVel1));
const FloatV vrel = FSub(vrel1, vrel2);
targetVel = FSub(targetVel, vrel);
f1->normalXYZ_appliedForceW = V4SetW(t1, zero);
f1->raXnXYZ_velMultiplierW = V4SetW(raXnSqrtInertia, velMultiplier);
f1->rbXnXYZ_biasW = V4SetW(rbXnSqrtInertia, FMul(V3Dot(t1, error), invDt));
FStore(targetVel, &f1->targetVel);
}
}
}
frictionPatchWritebackAddrIndex++;
}
}
PX_FORCE_INLINE void computeBlockStreamByteSizes(const bool useExtContacts, const CorrelationBuffer& c,
PxU32& _solverConstraintByteSize, PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches,
PxU32& _axisConstraintCount)
{
PX_ASSERT(0 == _solverConstraintByteSize);
PX_ASSERT(0 == _frictionPatchByteSize);
PX_ASSERT(0 == _numFrictionPatches);
PX_ASSERT(0 == _axisConstraintCount);
// PT: use local vars to remove LHS
PxU32 solverConstraintByteSize = 0;
PxU32 numFrictionPatches = 0;
PxU32 axisConstraintCount = 0;
for(PxU32 i = 0; i < c.frictionPatchCount; i++)
{
//Friction patches.
if(c.correlationListHeads[i] != CorrelationBuffer::LIST_END)
numFrictionPatches++;
const FrictionPatch& frictionPatch = c.frictionPatches[i];
const bool haveFriction = (frictionPatch.materialFlags & PxMaterialFlag::eDISABLE_FRICTION) == 0;
//Solver constraint data.
if(c.frictionPatchContactCounts[i]!=0)
{
solverConstraintByteSize += sizeof(SolverContactHeader);
solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointExt)
: c.frictionPatchContactCounts[i] * sizeof(SolverContactPoint);
solverConstraintByteSize += sizeof(PxF32) * ((c.frictionPatchContactCounts[i] + 3)&(~3)); //Add on space for applied impulses
axisConstraintCount += c.frictionPatchContactCounts[i];
if(haveFriction)
{
solverConstraintByteSize += useExtContacts ? c.frictionPatches[i].anchorCount * 2 * sizeof(SolverContactFrictionExt)
: c.frictionPatches[i].anchorCount * 2 * sizeof(SolverContactFriction);
axisConstraintCount += c.frictionPatches[i].anchorCount * 2;
}
}
}
PxU32 frictionPatchByteSize = numFrictionPatches*sizeof(FrictionPatch);
_numFrictionPatches = numFrictionPatches;
_axisConstraintCount = axisConstraintCount;
//16-byte alignment.
_frictionPatchByteSize = ((frictionPatchByteSize + 0x0f) & ~0x0f);
_solverConstraintByteSize = ((solverConstraintByteSize + 0x0f) & ~0x0f);
PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f));
PX_ASSERT(0 == (_frictionPatchByteSize & 0x0f));
}
static bool reserveBlockStreams(const bool useExtContacts, Dy::CorrelationBuffer& cBuffer,
PxU8*& solverConstraint,
FrictionPatch*& _frictionPatches,
PxU32& numFrictionPatches, PxU32& solverConstraintByteSize,
PxU32& axisConstraintCount, PxConstraintAllocator& constraintAllocator)
{
PX_ASSERT(NULL == solverConstraint);
PX_ASSERT(NULL == _frictionPatches);
PX_ASSERT(0 == numFrictionPatches);
PX_ASSERT(0 == solverConstraintByteSize);
PX_ASSERT(0 == axisConstraintCount);
//From frictionPatchStream we just need to reserve a single buffer.
PxU32 frictionPatchByteSize = 0;
//Compute the sizes of all the buffers.
computeBlockStreamByteSizes(
useExtContacts, cBuffer,
solverConstraintByteSize, frictionPatchByteSize, numFrictionPatches,
axisConstraintCount);
//Reserve the buffers.
//First reserve the accumulated buffer size for the constraint block.
PxU8* constraintBlock = NULL;
const PxU32 constraintBlockByteSize = solverConstraintByteSize;
if(constraintBlockByteSize > 0)
{
constraintBlock = constraintAllocator.reserveConstraintData(constraintBlockByteSize + 16u);
if(0==constraintBlock || (reinterpret_cast<PxU8*>(-1))==constraintBlock)
{
if(0==constraintBlock)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
constraintBlock=NULL;
}
}
PX_ASSERT((size_t(constraintBlock) & 0xF) == 0);
}
FrictionPatch* frictionPatches = NULL;
//If the constraint block reservation didn't fail then reserve the friction buffer too.
if(frictionPatchByteSize >0 && (0==constraintBlockByteSize || constraintBlock))
{
frictionPatches = reinterpret_cast<FrictionPatch*>(constraintAllocator.reserveFrictionData(frictionPatchByteSize));
if(0==frictionPatches || (reinterpret_cast<FrictionPatch*>(-1))==frictionPatches)
{
if(0==frictionPatches)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of friction data for a single contact pair in constraint prep. "
"Either accept dropped contacts or simplify collision geometry.");
frictionPatches=NULL;
}
}
}
_frictionPatches = frictionPatches;
//Patch up the individual ptrs to the buffer returned by the constraint block reservation (assuming the reservation didn't fail).
if(0==constraintBlockByteSize || constraintBlock)
{
if(solverConstraintByteSize)
{
solverConstraint = constraintBlock;
PX_ASSERT(0==(uintptr_t(solverConstraint) & 0x0f));
}
}
//Return true if neither of the two block reservations failed.
return ((0==constraintBlockByteSize || constraintBlock) && (0==frictionPatchByteSize || frictionPatches));
}
bool createFinalizeSolverContacts(
PxSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
PxPrefetchLine(contactDesc.body0);
PxPrefetchLine(contactDesc.body1);
PxPrefetchLine(contactDesc.data0);
PxPrefetchLine(contactDesc.data1);
c.frictionPatchCount = 0;
c.contactPatchCount = 0;
const bool hasForceThreshold = contactDesc.hasForceThresholds;
const bool staticOrKinematicBody = contactDesc.bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY || contactDesc.bodyState1 == PxSolverContactDesc::eSTATIC_BODY;
const bool disableStrongFriction = contactDesc.disableStrongFriction;
PxSolverConstraintDesc& desc = *contactDesc.desc;
const bool useExtContacts = (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY || desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY);
desc.constraintLengthOver16 = 0;
if (contactDesc.numContacts == 0)
{
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
return true;
}
if (!disableStrongFriction)
{
getFrictionPatches(c, contactDesc.frictionPtr, contactDesc.frictionCount, contactDesc.bodyFrame0, contactDesc.bodyFrame1, correlationDistance);
}
bool overflow = !createContactPatches(c, contactDesc.contacts, contactDesc.numContacts, PXC_SAME_NORMAL);
overflow = correlatePatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, PXC_SAME_NORMAL, 0, 0) || overflow;
PX_UNUSED(overflow);
#if PX_CHECKED
if (overflow)
PxGetFoundation().error(physx::PxErrorCode::eDEBUG_WARNING, PX_FL, "Dropping contacts in solver because we exceeded limit of 32 friction patches.");
#endif
growPatches(c, contactDesc.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, 0, frictionOffsetThreshold + contactDesc.restDistance);
//PX_ASSERT(patchCount == c.frictionPatchCount);
FrictionPatch* frictionPatches = NULL;
PxU8* solverConstraint = NULL;
PxU32 numFrictionPatches = 0;
PxU32 solverConstraintByteSize = 0;
PxU32 axisConstraintCount = 0;
const bool successfulReserve = reserveBlockStreams(
useExtContacts, c,
solverConstraint, frictionPatches,
numFrictionPatches,
solverConstraintByteSize,
axisConstraintCount,
constraintAllocator);
// initialise the work unit's ptrs to the various buffers.
contactDesc.frictionPtr = NULL;
contactDesc.frictionCount = 0;
desc.constraint = NULL;
desc.constraintLengthOver16 = 0;
// patch up the work unit with the reserved buffers and set the reserved buffer data as appropriate.
if (successfulReserve)
{
PxU8* frictionDataPtr = reinterpret_cast<PxU8*>(frictionPatches);
contactDesc.frictionPtr = frictionDataPtr;
desc.constraint = solverConstraint;
//output.nbContacts = PxTo8(numContacts);
contactDesc.frictionCount = PxTo8(numFrictionPatches);
desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize / 16);
desc.writeBack = contactDesc.contactForces;
//Initialise friction buffer.
if (frictionPatches)
{
// PT: TODO: revisit this... not very satisfying
//const PxU32 maxSize = numFrictionPatches*sizeof(FrictionPatch);
PxPrefetchLine(frictionPatches);
PxPrefetchLine(frictionPatches, 128);
PxPrefetchLine(frictionPatches, 256);
for (PxU32 i = 0; i<c.frictionPatchCount; i++)
{
//if(c.correlationListHeads[i]!=CorrelationBuffer::LIST_END)
if (c.frictionPatchContactCounts[i])
{
*frictionPatches++ = c.frictionPatches[i];
PxPrefetchLine(frictionPatches, 256);
}
}
}
//Initialise solverConstraint buffer.
if (solverConstraint)
{
const PxSolverBodyData& data0 = *contactDesc.data0;
const PxSolverBodyData& data1 = *contactDesc.data1;
if (useExtContacts)
{
const SolverExtBody b0(reinterpret_cast<const void*>(contactDesc.body0), reinterpret_cast<const void*>(&data0), desc.linkIndexA);
const SolverExtBody b1(reinterpret_cast<const void*>(contactDesc.body1), reinterpret_cast<const void*>(&data1), desc.linkIndexB);
setupFinalizeExtSolverContacts(contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
b0, b1, invDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, Z, contactDesc.offsetSlop);
}
else
{
setupFinalizeSolverConstraints(getInteraction(contactDesc), contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint,
data0, data1, invDtF32, dtF32, bounceThresholdF32,
contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1,
hasForceThreshold, staticOrKinematicBody, contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, contactDesc.offsetSlop);
}
//KS - set to 0 so we have a counter for the number of times we solved the constraint
//only going to be used on SPU but might as well set on all platforms because this code is shared
*(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0;
}
}
return successfulReserve;
}
FloatV setupExtSolverContact(const SolverExtBody& b0, const SolverExtBody& b1,
const FloatV& d0, const FloatV& d1, const FloatV& angD0, const FloatV& angD1, const Vec3V& bodyFrame0p, const Vec3V& bodyFrame1p,
const Vec3VArg normal, const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg dt, const FloatVArg restDistance,
const FloatVArg maxPenBias, const FloatVArg restitution,const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointExt& solverContact, const FloatVArg ccdMaxSeparation, Cm::SpatialVectorF* zVector,
const Cm::SpatialVectorV& v0, const Cm::SpatialVectorV& v1, const FloatV& cfm, const Vec3VArg solverOffsetSlop,
const FloatVArg norVel0, const FloatVArg norVel1, const FloatVArg damping )
{
const FloatV zero = FZero();
const FloatV separation = FLoad(contact.separation);
const FloatV penetration = FSub(separation, restDistance);
const Vec3V point = V3LoadA(contact.point);
const Vec3V ra = V3Sub(point, bodyFrame0p);
const Vec3V rb = V3Sub(point, bodyFrame1p);
Vec3V raXn = V3Cross(ra, normal);
Vec3V rbXn = V3Cross(rb, normal);
FloatV aVel0 = V3Dot(v0.angular, raXn);
FloatV aVel1 = V3Dot(v1.angular, raXn);
FloatV relLinVel = FSub(norVel0, norVel1);
FloatV relAngVel = FSub(aVel0, aVel1);
const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(relLinVel, zero), FMax(), FDiv(relAngVel, relLinVel)), FOne()));
raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn);
rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn);
aVel0 = V3Dot(raXn, v0.angular);
aVel1 = V3Dot(rbXn, v1.angular);
relAngVel = FSub(aVel0, aVel1);
Cm::SpatialVectorV deltaV0, deltaV1;
const Cm::SpatialVectorV resp0 = createImpulseResponseVector(normal, raXn, b0);
const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(normal), V3Neg(rbXn), b1);
const FloatV unitResponse = getImpulseResponse(b0, resp0, deltaV0, d0, angD0,
b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(zVector));
const FloatV vrel = FAdd(relLinVel, relAngVel);
const FloatV penetrationInvDt = FMul(penetration, invDt);
const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt));
FloatV velMultiplier, impulseMultiplier;
FloatV biasedErr, unbiasedErr;
const FloatV tVel = FSel(isGreater2, FMul(FNeg(vrel), restitution), zero);
FloatV targetVelocity = tVel;
//Get the rigid body's current velocity and embed into the constraint target velocities
if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVelocity = FSub(targetVelocity, FAdd(norVel0, aVel0));
else if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
targetVelocity = FAdd(targetVelocity, FAdd(norVel1, aVel1));
targetVelocity = FAdd(targetVelocity, V3Dot(V3LoadA(contact.targetVel), normal));
if (FAllGrtr(zero, restitution)) // negative restitution -> interpret as spring stiffness for compliant contact
{
const FloatV nrdt = FMul(dt, restitution);
const FloatV a = FMul(dt, FSub(damping, nrdt));
const FloatV b = FMul(dt, FNeg(FMul(restitution, penetration)));
const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne()));
velMultiplier = FMul(x, a);
//FloatV scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier));
const FloatV scaledBias = FMul(x, b);
impulseMultiplier = FSub(FOne(), x);
unbiasedErr = biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
}
else
{
const BoolV ccdSeparationCondition = FIsGrtrOrEq(ccdMaxSeparation, penetration);
velMultiplier = FSel(FIsGrtr(unitResponse, FZero()), FRecip(FAdd(unitResponse, cfm)), zero);
FloatV scaledBias = FMul(velMultiplier, FMax(maxPenBias, FMul(penetration, invDtp8)));
scaledBias = FSel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias);
biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias));
unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FSel(isGreater2, zero, FNeg(FMax(scaledBias, zero))));
impulseMultiplier = FOne();
}
const FloatV deltaF = FMax(FMul(FSub(tVel, FAdd(vrel, FMax(penetrationInvDt, zero))), velMultiplier), zero);
FStore(biasedErr, &solverContact.biasedErr);
FStore(unbiasedErr, &solverContact.unbiasedErr);
solverContact.raXn_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier);
solverContact.rbXn_maxImpulseW = V4SetW(Vec4V_From_Vec3V(V3Neg(resp1.angular)), FLoad(contact.maxImpulse));;
solverContact.linDeltaVA = deltaV0.linear;
solverContact.angDeltaVA = deltaV0.angular;
solverContact.linDeltaVB = deltaV1.linear;
solverContact.angDeltaVB = deltaV1.angular;
FStore(impulseMultiplier, &solverContact.impulseMultiplier);
return deltaF;
}
bool createFinalizeSolverContacts(PxSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal dtF32,
PxReal bounceThresholdF32,
PxReal frictionOffsetThreshold,
PxReal correlationDistance,
PxConstraintAllocator& constraintAllocator,
Cm::SpatialVectorF* Z)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
buffer.count = 0;
// We pull the friction patches out of the cache to remove the dependency on how
// the cache is organized. Remember original addrs so we can write them back
// efficiently.
PxU32 numContacts = 0;
{
PxReal invMassScale0 = 1.f;
PxReal invMassScale1 = 1.f;
PxReal invInertiaScale0 = 1.f;
PxReal invInertiaScale1 = 1.f;
bool hasMaxImpulse = false, hasTargetVelocity = false;
numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1,
invInertiaScale0, invInertiaScale1, PxMin(contactDesc.data0->maxContactImpulse, contactDesc.data1->maxContactImpulse));
contactDesc.contacts = buffer.contacts;
contactDesc.numContacts = numContacts;
contactDesc.disableStrongFriction = contactDesc.disableStrongFriction || hasTargetVelocity;
contactDesc.hasMaxImpulse = hasMaxImpulse;
contactDesc.invMassScales.linear0 *= invMassScale0;
contactDesc.invMassScales.linear1 *= invMassScale1;
contactDesc.invMassScales.angular0 *= invInertiaScale0;
contactDesc.invMassScales.angular1 *= invInertiaScale1;
}
CorrelationBuffer& c = threadContext.mCorrelationBuffer;
return createFinalizeSolverContacts(contactDesc, c, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold,
correlationDistance, constraintAllocator, Z);
}
PxU32 getContactManagerConstraintDesc(const PxsContactManagerOutput& cmOutput, const PxsContactManager& /*cm*/, PxSolverConstraintDesc& desc)
{
desc.writeBack = cmOutput.contactForces;
return cmOutput.nbContacts;// cm.getWorkUnit().axisConstraintCount;
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyBodyCoreIntegrator.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 DY_BODYCORE_INTEGRATOR_H
#define DY_BODYCORE_INTEGRATOR_H
#include "PxvDynamics.h"
#include "DySolverBody.h"
namespace physx
{
namespace Dy
{
PX_FORCE_INLINE void bodyCoreComputeUnconstrainedVelocity
(const PxVec3& gravity, PxReal dt, PxReal linearDamping, PxReal angularDamping, PxReal accelScale,
PxReal maxLinearVelocitySq, PxReal maxAngularVelocitySq, PxVec3& inOutLinearVelocity, PxVec3& inOutAngularVelocity,
bool disableGravity)
{
//Multiply everything that needs multiplied by dt to improve code generation.
PxVec3 linearVelocity = inOutLinearVelocity;
PxVec3 angularVelocity = inOutAngularVelocity;
const PxReal linearDampingTimesDT=linearDamping*dt;
const PxReal angularDampingTimesDT=angularDamping*dt;
const PxReal oneMinusLinearDampingTimesDT=1.0f-linearDampingTimesDT;
const PxReal oneMinusAngularDampingTimesDT=1.0f-angularDampingTimesDT;
//TODO context-global gravity
if(!disableGravity)
{
const PxVec3 linearAccelTimesDT = gravity*dt *accelScale;
linearVelocity += linearAccelTimesDT;
}
//Apply damping.
const PxReal linVelMultiplier = physx::intrinsics::fsel(oneMinusLinearDampingTimesDT, oneMinusLinearDampingTimesDT, 0.0f);
const PxReal angVelMultiplier = physx::intrinsics::fsel(oneMinusAngularDampingTimesDT, oneMinusAngularDampingTimesDT, 0.0f);
linearVelocity*=linVelMultiplier;
angularVelocity*=angVelMultiplier;
// Clamp velocity
const PxReal linVelSq = linearVelocity.magnitudeSquared();
if(linVelSq > maxLinearVelocitySq)
{
linearVelocity *= PxSqrt(maxLinearVelocitySq / linVelSq);
}
const PxReal angVelSq = angularVelocity.magnitudeSquared();
if(angVelSq > maxAngularVelocitySq)
{
angularVelocity *= PxSqrt(maxAngularVelocitySq / angVelSq);
}
inOutLinearVelocity = linearVelocity;
inOutAngularVelocity = angularVelocity;
}
PX_FORCE_INLINE void integrateCore(PxVec3& motionLinearVelocity, PxVec3& motionAngularVelocity,
PxSolverBody& solverBody, PxSolverBodyData& solverBodyData, PxF32 dt, PxU32 lockFlags)
{
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
{
motionLinearVelocity.x = 0.f;
solverBody.linearVelocity.x = 0.f;
solverBodyData.linearVelocity.x = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
{
motionLinearVelocity.y = 0.f;
solverBody.linearVelocity.y = 0.f;
solverBodyData.linearVelocity.y = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
{
motionLinearVelocity.z = 0.f;
solverBody.linearVelocity.z = 0.f;
solverBodyData.linearVelocity.z = 0.f;
}
//The angular velocity should be 0 because it is now impossible to make it rotate around that axis!
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
{
motionAngularVelocity.x = 0.f;
solverBody.angularState.x = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
{
motionAngularVelocity.y = 0.f;
solverBody.angularState.y = 0.f;
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
{
motionAngularVelocity.z = 0.f;
solverBody.angularState.z = 0.f;
}
}
// Integrate linear part
const PxVec3 linearMotionVel = solverBodyData.linearVelocity + motionLinearVelocity;
const PxVec3 delta = linearMotionVel * dt;
PxVec3 angularMotionVel = solverBodyData.angularVelocity + solverBodyData.sqrtInvInertia * motionAngularVelocity;
PxReal w = angularMotionVel.magnitudeSquared();
solverBodyData.body2World.p += delta;
PX_ASSERT(solverBodyData.body2World.p.isFinite());
//Store back the linear and angular velocities
//core.linearVelocity += solverBody.linearVelocity * solverBodyData.sqrtInvMass;
solverBodyData.linearVelocity += solverBody.linearVelocity;
solverBodyData.angularVelocity += solverBodyData.sqrtInvInertia * solverBody.angularState;
// Integrate the rotation using closed form quaternion integrator
if (w != 0.0f)
{
w = PxSqrt(w);
// Perform a post-solver clamping
// TODO(dsequeira): ignore this for the moment
//just clamp motionVel to half float-range
const PxReal maxW = 1e+7f; //Should be about sqrt(PX_MAX_REAL/2) or smaller
if (w > maxW)
{
angularMotionVel = angularMotionVel.getNormalized() * maxW;
w = maxW;
}
const PxReal v = dt * w * 0.5f;
PxReal s, q;
PxSinCos(v, s, q);
s /= w;
const PxVec3 pqr = angularMotionVel * s;
const PxQuat quatVel(pqr.x, pqr.y, pqr.z, 0);
PxQuat result = quatVel * solverBodyData.body2World.q;
result += solverBodyData.body2World.q * q;
solverBodyData.body2World.q = result.getNormalized();
PX_ASSERT(solverBodyData.body2World.q.isSane());
PX_ASSERT(solverBodyData.body2World.q.isFinite());
}
motionLinearVelocity = linearMotionVel;
motionAngularVelocity = angularMotionVel;
}
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyCorrelationBuffer.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 DY_CORRELATION_BUFFER_H
#define DY_CORRELATION_BUFFER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBounds3.h"
#include "geomutils/PxContactBuffer.h"
#include "PxvConfig.h"
#include "DyFrictionPatch.h"
namespace physx
{
namespace Dy
{
struct CorrelationBuffer
{
static const PxU32 MAX_FRICTION_PATCHES = 32;
static const PxU16 LIST_END = 0xffff;
struct ContactPatchData
{
PxBounds3 patchBounds;
PxU32 boundsPadding;
PxReal staticFriction;
PxReal dynamicFriction;
PxReal restitution;
PxU16 start;
PxU16 next;
PxU8 flags;
PxU8 count;
};
// we can have as many contact patches as contacts, unfortunately
ContactPatchData PX_ALIGN(16, contactPatches[PxContactBuffer::MAX_CONTACTS]);
FrictionPatch PX_ALIGN(16, frictionPatches[MAX_FRICTION_PATCHES]);
PxVec3 PX_ALIGN(16, frictionPatchWorldNormal[MAX_FRICTION_PATCHES]);
PxBounds3 patchBounds[MAX_FRICTION_PATCHES];
PxU32 frictionPatchContactCounts[MAX_FRICTION_PATCHES];
PxU32 correlationListHeads[MAX_FRICTION_PATCHES+1];
// contact IDs are only used to identify auxiliary contact data when velocity
// targets have been set.
PxU16 contactID[MAX_FRICTION_PATCHES][2];
PxU32 contactPatchCount, frictionPatchCount;
};
bool createContactPatches(CorrelationBuffer& fb, const PxContactPoint* cb, PxU32 contactCount, PxReal normalTolerance);
bool correlatePatches(CorrelationBuffer& fb,
const PxContactPoint* cb,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxReal normalTolerance,
PxU32 startContactPatchIndex,
PxU32 startFrictionPatchIndex);
void growPatches(CorrelationBuffer& fb,
const PxContactPoint* buffer,
const PxTransform& bodyFrame0,
const PxTransform& bodyFrame1,
PxU32 frictionPatchStartIndex,
PxReal frictionOffsetThreshold);
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControlPF.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 DY_SOLVER_CONTROLPF_H
#define DY_SOLVER_CONTROLPF_H
#include "DySolverCore.h"
#include "DySolverConstraintDesc.h"
namespace physx
{
namespace Dy
{
// PT: TODO: these "solver core" classes are mostly stateless, at this point they could just be function pointers like the solve methods.
class SolverCoreGeneralPF : public SolverCore
{
public:
SolverCoreGeneralPF(){}
// SolverCore
virtual void solveVParallelAndWriteBack
(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const PX_OVERRIDE PX_FINAL;
virtual void solveV_Blocks
(SolverIslandParams& params) const PX_OVERRIDE PX_FINAL;
//~SolverCore
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintDesc.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 DY_SOLVER_CONSTRAINT_DESC_H
#define DY_SOLVER_CONSTRAINT_DESC_H
#include "PxvConfig.h"
#include "DySolverConstraintTypes.h"
#include "foundation/PxUtilities.h"
#include "PxConstraintDesc.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
struct PxcNpWorkUnit;
struct PxsContactManagerOutput;
namespace Dy
{
class FeatherstoneArticulation;
// dsequeira: moved this articulation stuff here to sever a build dep on Articulation.h through DyThreadContext.h and onward
struct SelfConstraintBlock
{
PxU32 startId;
PxU32 numSelfConstraints;
PxU16 fsDataLength;
PxU16 requiredSolverProgress;
uintptr_t eaFsData;
};
//This class rolls together multiple contact managers into a single contact manager.
struct CompoundContactManager
{
PxU32 mStartIndex;
PxU16 mStride;
PxU16 mReducedContactCount;
PxU16 originalContactCount;
PxU8 originalPatchCount;
PxU8 originalStatusFlags;
PxcNpWorkUnit* unit; //This is a work unit but the contact buffer has been adjusted to contain all the contacts for all the subsequent pairs
PxsContactManagerOutput* cmOutput;
PxU8* originalContactPatches; //This is the original contact buffer that we replaced with a combined buffer
PxU8* originalContactPoints;
PxReal* originalForceBuffer; //This is the original force buffer that we replaced with a combined force buffer
PxU16* forceBufferList; //This is a list of indices from the reduced force buffer to the original force buffers - we need this to fix up the write-backs from the solver
};
struct SolverConstraintPrepState
{
enum Enum
{
eOUT_OF_MEMORY,
eUNBATCHABLE,
eSUCCESS
};
};
PX_FORCE_INLINE bool isArticulationConstraint(const PxSolverConstraintDesc& desc)
{
return desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY
|| desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY;
}
PX_FORCE_INLINE void setConstraintLength(PxSolverConstraintDesc& desc, const PxU32 constraintLength)
{
PX_ASSERT(0==(constraintLength & 0x0f));
PX_ASSERT(constraintLength <= PX_MAX_U16 * 16);
desc.constraintLengthOver16 = PxTo16(constraintLength >> 4);
}
PX_FORCE_INLINE PxU32 getConstraintLength(const PxSolverConstraintDesc& desc)
{
return PxU32(desc.constraintLengthOver16 << 4);
}
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getArticulationA(const PxSolverConstraintDesc& desc)
{
return reinterpret_cast<Dy::FeatherstoneArticulation*>(desc.articulationA);
}
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getArticulationB(const PxSolverConstraintDesc& desc)
{
return reinterpret_cast<Dy::FeatherstoneArticulation*>(desc.articulationB);
}
PX_COMPILE_TIME_ASSERT(0 == (0x0f & sizeof(PxSolverConstraintDesc)));
#define MAX_PERMITTED_SOLVER_PROGRESS 0xFFFF
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintsBlock.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxFPU.h"
#include "DySolverBody.h"
#include "DySolverContact.h"
#include "DySolverConstraint1D.h"
#include "DySolverConstraintDesc.h"
#include "DyThresholdTable.h"
#include "DySolverContext.h"
#include "foundation/PxUtilities.h"
#include "DyConstraint.h"
#include "foundation/PxAtomic.h"
#include "DySolverContact4.h"
#include "DySolverConstraint1D4.h"
#include "DyPGS.h"
namespace physx
{
namespace Dy
{
static void solveContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
Vec4V vMax = V4Splat(FMax());
const PxU8* PX_RESTRICT prefetchAddress = currPtr + sizeof(SolverContactHeader4) + sizeof(SolverContactBatchPointDynamic4);
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
const Vec4V invMassA = hdr->invMass0D0;
const Vec4V invMassB = hdr->invMass1D1;
const Vec4V sumInvMass = V4Add(invMassA, invMassB);
while(currPtr < last)
{
hdr = reinterpret_cast<const SolverContactHeader4*>(currPtr);
PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_RB_CONTACT);
currPtr = reinterpret_cast<PxU8*>(const_cast<SolverContactHeader4*>(hdr) + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointDynamic4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointDynamic4*>(currPtr);
Vec4V* maxImpulses;
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
PxU32 maxImpulseMask = 0;
if(hasMaxImpulse)
{
maxImpulseMask = 0xFFFFFFFF;
maxImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V) * numNormalConstr;
}
else
{
maxImpulses = &vMax;
}
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
Vec4V* frictionAppliedForce = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numFrictionConstr;
const SolverContactFrictionDynamic4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionDynamic4*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionDynamic4);
Vec4V accumulatedNormalImpulse = vZero;
const Vec4V angD0 = hdr->angDom0;
const Vec4V angD1 = hdr->angDom1;
const Vec4V _normalT0 = hdr->normalX;
const Vec4V _normalT1 = hdr->normalY;
const Vec4V _normalT2 = hdr->normalZ;
Vec4V contactNormalVel1 = V4Mul(linVel0T0, _normalT0);
Vec4V contactNormalVel3 = V4Mul(linVel1T0, _normalT0);
contactNormalVel1 = V4MulAdd(linVel0T1, _normalT1, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T1, _normalT1, contactNormalVel3);
contactNormalVel1 = V4MulAdd(linVel0T2, _normalT2, contactNormalVel1);
contactNormalVel3 = V4MulAdd(linVel1T2, _normalT2, contactNormalVel3);
Vec4V relVel1 = V4Sub(contactNormalVel1, contactNormalVel3);
Vec4V accumDeltaF = vZero;
for(PxU32 i=0;i<numNormalConstr;i++)
{
const SolverContactBatchPointDynamic4& c = contacts[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = appliedForces[i];
const Vec4V maxImpulse = maxImpulses[i & maxImpulseMask];
Vec4V contactNormalVel2 = V4Mul(c.raXnX, angState0T0);
Vec4V contactNormalVel4 = V4Mul(c.rbXnX, angState1T0);
contactNormalVel2 = V4MulAdd(c.raXnY, angState0T1, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnY, angState1T1, contactNormalVel4);
contactNormalVel2 = V4MulAdd(c.raXnZ, angState0T2, contactNormalVel2);
contactNormalVel4 = V4MulAdd(c.rbXnZ, angState1T2, contactNormalVel4);
const Vec4V normalVel = V4Add(relVel1, V4Sub(contactNormalVel2, contactNormalVel4));
Vec4V deltaF = V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr);
deltaF = V4Max(deltaF, V4Neg(appliedForce));
const Vec4V newAppliedForce = V4Min(V4MulAdd(c.impulseMultiplier, appliedForce, deltaF), maxImpulse);
deltaF = V4Sub(newAppliedForce, appliedForce);
accumDeltaF = V4Add(accumDeltaF, deltaF);
const Vec4V angDetaF0 = V4Mul(deltaF, angD0);
const Vec4V angDetaF1 = V4Mul(deltaF, angD1);
relVel1 = V4MulAdd(sumInvMass, deltaF, relVel1);
angState0T0 = V4MulAdd(c.raXnX, angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(c.rbXnX, angDetaF1, angState1T0);
angState0T1 = V4MulAdd(c.raXnY, angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(c.rbXnY, angDetaF1, angState1T1);
angState0T2 = V4MulAdd(c.raXnZ, angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(c.rbXnZ, angDetaF1, angState1T2);
appliedForces[i] = newAppliedForce;
accumulatedNormalImpulse = V4Add(accumulatedNormalImpulse, newAppliedForce);
}
const Vec4V accumDeltaF_IM0 = V4Mul(accumDeltaF, invMassA);
const Vec4V accumDeltaF_IM1 = V4Mul(accumDeltaF, invMassB);
linVel0T0 = V4MulAdd(_normalT0, accumDeltaF_IM0, linVel0T0);
linVel1T0 = V4NegMulSub(_normalT0, accumDeltaF_IM1, linVel1T0);
linVel0T1 = V4MulAdd(_normalT1, accumDeltaF_IM0, linVel0T1);
linVel1T1 = V4NegMulSub(_normalT1, accumDeltaF_IM1, linVel1T1);
linVel0T2 = V4MulAdd(_normalT2, accumDeltaF_IM0, linVel0T2);
linVel1T2 = V4NegMulSub(_normalT2, accumDeltaF_IM1, linVel1T2);
if(cache.doFriction && numFrictionConstr)
{
const Vec4V staticFric = hdr->staticFriction;
const Vec4V dynamicFric = hdr->dynamicFriction;
const Vec4V maxFrictionImpulse = V4Mul(staticFric, accumulatedNormalImpulse);
const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse);
const Vec4V negMaxDynFrictionImpulse = V4Neg(maxDynFrictionImpulse);
//const Vec4V negMaxFrictionImpulse = V4Neg(maxFrictionImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
{
PxPrefetchLine(fd->frictionBrokenWritebackByte[0]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[1]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[2]);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
const SolverContactFrictionDynamic4& f = frictions[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = frictionAppliedForce[i];
const Vec4V normalT0 = fd->normalX[i&1];
const Vec4V normalT1 = fd->normalY[i&1];
const Vec4V normalT2 = fd->normalZ[i&1];
Vec4V normalVel1 = V4Mul(linVel0T0, normalT0);
Vec4V normalVel2 = V4Mul(f.raXnX, angState0T0);
Vec4V normalVel3 = V4Mul(linVel1T0, normalT0);
Vec4V normalVel4 = V4Mul(f.rbXnX, angState1T0);
normalVel1 = V4MulAdd(linVel0T1, normalT1, normalVel1);
normalVel2 = V4MulAdd(f.raXnY, angState0T1, normalVel2);
normalVel3 = V4MulAdd(linVel1T1, normalT1, normalVel3);
normalVel4 = V4MulAdd(f.rbXnY, angState1T1, normalVel4);
normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1);
normalVel2 = V4MulAdd(f.raXnZ, angState0T2, normalVel2);
normalVel3 = V4MulAdd(linVel1T2, normalT2, normalVel3);
normalVel4 = V4MulAdd(f.rbXnZ, angState1T2, normalVel4);
const Vec4V normalVel_tmp2 = V4Add(normalVel1, normalVel2);
const Vec4V normalVel_tmp1 = V4Add(normalVel3, normalVel4);
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const Vec4V normalVel = V4Sub(normalVel_tmp2, normalVel_tmp1 );
const Vec4V tmp1 = V4Sub(appliedForce, f.scaledBias);
const Vec4V totalImpulse = V4NegMulSub(normalVel, f.velMultiplier, tmp1);
broken = BOr(broken, V4IsGrtr(V4Abs(totalImpulse), maxFrictionImpulse));
const Vec4V newAppliedForce = V4Sel(broken, V4Min(maxDynFrictionImpulse, V4Max(negMaxDynFrictionImpulse, totalImpulse)), totalImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
frictionAppliedForce[i] = newAppliedForce;
const Vec4V deltaFIM0 = V4Mul(deltaF, invMassA);
const Vec4V deltaFIM1 = V4Mul(deltaF, invMassB);
const Vec4V angDetaF0 = V4Mul(deltaF, angD0);
const Vec4V angDetaF1 = V4Mul(deltaF, angD1);
linVel0T0 = V4MulAdd(normalT0, deltaFIM0, linVel0T0);
linVel1T0 = V4NegMulSub(normalT0, deltaFIM1, linVel1T0);
angState0T0 = V4MulAdd(f.raXnX, angDetaF0, angState0T0);
angState1T0 = V4NegMulSub(f.rbXnX, angDetaF1, angState1T0);
linVel0T1 = V4MulAdd(normalT1, deltaFIM0, linVel0T1);
linVel1T1 = V4NegMulSub(normalT1, deltaFIM1, linVel1T1);
angState0T1 = V4MulAdd(f.raXnY, angDetaF0, angState0T1);
angState1T1 = V4NegMulSub(f.rbXnY, angDetaF1, angState1T1);
linVel0T2 = V4MulAdd(normalT2, deltaFIM0, linVel0T2);
linVel1T2 = V4NegMulSub(normalT2, deltaFIM1, linVel1T2);
angState0T2 = V4MulAdd(f.raXnZ, angDetaF0, angState0T2);
angState1T2 = V4NegMulSub(f.rbXnZ, angDetaF1, angState1T2);
}
fd->broken = broken;
}
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularState.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularState.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularState.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularState.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState30, &b30.angularState.x);
if(desc[0].bodyBDataIndex != 0)
{
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(angState01, &b01.angularState.x);
}
if(desc[1].bodyBDataIndex != 0)
{
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(angState11, &b11.angularState.x);
}
if(desc[2].bodyBDataIndex != 0)
{
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(angState21, &b21.angularState.x);
}
if(desc[3].bodyBDataIndex != 0)
{
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState31, &b31.angularState.x);
}
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
PX_ASSERT(b01.linearVelocity.isFinite());
PX_ASSERT(b01.angularState.isFinite());
PX_ASSERT(b11.linearVelocity.isFinite());
PX_ASSERT(b11.angularState.isFinite());
PX_ASSERT(b21.linearVelocity.isFinite());
PX_ASSERT(b21.angularState.isFinite());
PX_ASSERT(b31.linearVelocity.isFinite());
PX_ASSERT(b31.angularState.isFinite());
}
static void solveContact4_StaticBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b30 = *desc[3].bodyA;
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
//We'll need this.
const Vec4V vZero = V4Zero();
Vec4V vMax = V4Splat(FMax());
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
const PxU8* PX_RESTRICT prefetchAddress = currPtr + sizeof(SolverContactHeader4) + sizeof(SolverContactBatchPointBase4);
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
const Vec4V invMass0 = hdr->invMass0D0;
while((currPtr < last))
{
hdr = reinterpret_cast<const SolverContactHeader4*>(currPtr);
PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT);
currPtr = const_cast<PxU8*>(reinterpret_cast<const PxU8*>(hdr + 1));
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointBase4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointBase4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(contacts + numNormalConstr);
Vec4V* maxImpulses;
PxU32 maxImpulseMask;
if(hasMaxImpulse)
{
maxImpulseMask = 0xFFFFFFFF;
maxImpulses = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V) * numNormalConstr;
}
else
{
maxImpulseMask = 0;
maxImpulses = &vMax;
}
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
Vec4V* frictionAppliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numFrictionConstr;
const SolverContactFrictionBase4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionBase4*>(currPtr);
currPtr += numFrictionConstr * sizeof(SolverContactFrictionBase4);
Vec4V accumulatedNormalImpulse = vZero;
const Vec4V angD0 = hdr->angDom0;
const Vec4V _normalT0 = hdr->normalX;
const Vec4V _normalT1 = hdr->normalY;
const Vec4V _normalT2 = hdr->normalZ;
Vec4V contactNormalVel1 = V4Mul(linVel0T0, _normalT0);
contactNormalVel1 = V4MulAdd(linVel0T1, _normalT1, contactNormalVel1);
contactNormalVel1 = V4MulAdd(linVel0T2, _normalT2, contactNormalVel1);
Vec4V accumDeltaF = vZero;
// numNormalConstr is the maxium number of normal constraints any of these 4 contacts have.
// Contacts with fewer normal constraints than that maximum apply zero force because their
// c.velMultiplier and c.biasedErr were set to zero in contact prepping (see the bFinished variables there)
for(PxU32 i=0;i<numNormalConstr;i++)
{
const SolverContactBatchPointBase4& c = contacts[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = appliedForces[i];
const Vec4V maxImpulse = maxImpulses[i&maxImpulseMask];
Vec4V contactNormalVel2 = V4MulAdd(c.raXnX, angState0T0, contactNormalVel1);
contactNormalVel2 = V4MulAdd(c.raXnY, angState0T1, contactNormalVel2);
const Vec4V normalVel = V4MulAdd(c.raXnZ, angState0T2, contactNormalVel2);
const Vec4V _deltaF = V4Max(V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr), V4Neg(appliedForce));
Vec4V newAppliedForce(V4MulAdd(c.impulseMultiplier, appliedForce, _deltaF));
newAppliedForce = V4Min(newAppliedForce, maxImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V angDeltaF = V4Mul(angD0, deltaF);
accumDeltaF = V4Add(accumDeltaF, deltaF);
contactNormalVel1 = V4MulAdd(invMass0, deltaF, contactNormalVel1);
angState0T0 = V4MulAdd(c.raXnX, angDeltaF, angState0T0);
angState0T1 = V4MulAdd(c.raXnY, angDeltaF, angState0T1);
angState0T2 = V4MulAdd(c.raXnZ, angDeltaF, angState0T2);
#if 1
appliedForces[i] = newAppliedForce;
#endif
accumulatedNormalImpulse = V4Add(accumulatedNormalImpulse, newAppliedForce);
}
const Vec4V deltaFInvMass0 = V4Mul(accumDeltaF, invMass0);
linVel0T0 = V4MulAdd(_normalT0, deltaFInvMass0, linVel0T0);
linVel0T1 = V4MulAdd(_normalT1, deltaFInvMass0, linVel0T1);
linVel0T2 = V4MulAdd(_normalT2, deltaFInvMass0, linVel0T2);
if(cache.doFriction && numFrictionConstr)
{
const Vec4V staticFric = hdr->staticFriction;
const Vec4V dynamicFric = hdr->dynamicFriction;
const Vec4V maxFrictionImpulse = V4Mul(staticFric, accumulatedNormalImpulse);
const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse);
const Vec4V negMaxDynFrictionImpulse = V4Neg(maxDynFrictionImpulse);
BoolV broken = BFFFF();
if(cache.writeBackIteration)
{
PxPrefetchLine(fd->frictionBrokenWritebackByte[0]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[1]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[2]);
PxPrefetchLine(fd->frictionBrokenWritebackByte[3]);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
const SolverContactFrictionBase4& f = frictions[i];
PxU32 offset = 0;
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
PxPrefetchLine(prefetchAddress, offset += 64);
prefetchAddress += offset;
const Vec4V appliedForce = frictionAppliedForces[i];
const Vec4V normalT0 = fd->normalX[i&1];
const Vec4V normalT1 = fd->normalY[i&1];
const Vec4V normalT2 = fd->normalZ[i&1];
Vec4V normalVel1 = V4Mul(linVel0T0, normalT0);
Vec4V normalVel2 = V4Mul(f.raXnX, angState0T0);
normalVel1 = V4MulAdd(linVel0T1, normalT1, normalVel1);
normalVel2 = V4MulAdd(f.raXnY, angState0T1, normalVel2);
normalVel1 = V4MulAdd(linVel0T2, normalT2, normalVel1);
normalVel2 = V4MulAdd(f.raXnZ, angState0T2, normalVel2);
//relative normal velocity for all 4 constraints
const Vec4V normalVel = V4Add(normalVel1, normalVel2);
// appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation
const Vec4V tmp1 = V4Sub(appliedForce, f.scaledBias);
const Vec4V totalImpulse = V4NegMulSub(normalVel, f.velMultiplier, tmp1);
broken = BOr(broken, V4IsGrtr(V4Abs(totalImpulse), maxFrictionImpulse));
const Vec4V newAppliedForce = V4Sel(broken, V4Min(maxDynFrictionImpulse, V4Max(negMaxDynFrictionImpulse, totalImpulse)), totalImpulse);
const Vec4V deltaF = V4Sub(newAppliedForce, appliedForce);
const Vec4V deltaFInvMass = V4Mul(invMass0, deltaF);
const Vec4V angDeltaF = V4Mul(angD0, deltaF);
linVel0T0 = V4MulAdd(normalT0, deltaFInvMass, linVel0T0);
angState0T0 = V4MulAdd(f.raXnX, angDeltaF, angState0T0);
linVel0T1 = V4MulAdd(normalT1, deltaFInvMass, linVel0T1);
angState0T1 = V4MulAdd(f.raXnY, angDeltaF, angState0T1);
linVel0T2 = V4MulAdd(normalT2, deltaFInvMass, linVel0T2);
angState0T2 = V4MulAdd(f.raXnZ, angDeltaF, angState0T2);
#if 1
frictionAppliedForces[i] = newAppliedForce;
#endif
}
fd->broken = broken;
}
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
PX_ASSERT(b00.linearVelocity.isFinite());
PX_ASSERT(b00.angularState.isFinite());
PX_ASSERT(b10.linearVelocity.isFinite());
PX_ASSERT(b10.angularState.isFinite());
PX_ASSERT(b20.linearVelocity.isFinite());
PX_ASSERT(b20.angularState.isFinite());
PX_ASSERT(b30.linearVelocity.isFinite());
PX_ASSERT(b30.angularState.isFinite());
}
static void concludeContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/, PxU32 contactSize, PxU32 frictionSize)
{
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
while((currPtr < last))
{
const SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
currPtr = const_cast<PxU8*>(reinterpret_cast<const PxU8*>(hdr + 1));
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
currPtr += sizeof(Vec4V)*numNormalConstr;
SolverContactBatchPointBase4* PX_RESTRICT contacts = reinterpret_cast<SolverContactBatchPointBase4*>(currPtr);
currPtr += (numNormalConstr * contactSize);
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
if(hasMaxImpulse)
currPtr += sizeof(Vec4V) * numNormalConstr;
currPtr += sizeof(Vec4V)*numFrictionConstr;
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
PX_UNUSED(fd);
SolverContactFrictionBase4* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionBase4*>(currPtr);
currPtr += (numFrictionConstr * frictionSize);
for(PxU32 i=0;i<numNormalConstr;i++)
{
SolverContactBatchPointBase4& c = *contacts;
contacts = reinterpret_cast<SolverContactBatchPointBase4*>((reinterpret_cast<PxU8*>(contacts)) + contactSize);
c.biasedErr = V4Sub(c.biasedErr, c.scaledBias);
}
for(PxU32 i=0;i<numFrictionConstr;i++)
{
SolverContactFrictionBase4& f = *frictions;
frictions = reinterpret_cast<SolverContactFrictionBase4*>((reinterpret_cast<PxU8*>(frictions)) + frictionSize);
f.scaledBias = f.targetVelocity;
}
}
}
static void writeBackContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& cache,
const PxSolverBodyData** PX_RESTRICT bd0, const PxSolverBodyData** PX_RESTRICT bd1)
{
const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]);
//hopefully pointer aliasing doesn't bite.
PxU8* PX_RESTRICT currPtr = desc[0].constraint;
PxReal* PX_RESTRICT vForceWriteback0 = reinterpret_cast<PxReal*>(desc[0].writeBack);
PxReal* PX_RESTRICT vForceWriteback1 = reinterpret_cast<PxReal*>(desc[1].writeBack);
PxReal* PX_RESTRICT vForceWriteback2 = reinterpret_cast<PxReal*>(desc[2].writeBack);
PxReal* PX_RESTRICT vForceWriteback3 = reinterpret_cast<PxReal*>(desc[3].writeBack);
const PxU8 type = *desc[0].constraint;
const PxU32 contactSize = type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContactBatchPointDynamic4) : sizeof(SolverContactBatchPointBase4);
const PxU32 frictionSize = type == DY_SC_TYPE_BLOCK_RB_CONTACT ? sizeof(SolverContactFrictionDynamic4) : sizeof(SolverContactFrictionBase4);
Vec4V normalForce = V4Zero();
//We'll need this.
//const Vec4V vZero = V4Zero();
bool writeBackThresholds[4] = {false, false, false, false};
while((currPtr < last))
{
SolverContactHeader4* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader4*>(currPtr);
currPtr = reinterpret_cast<PxU8*>(hdr + 1);
const PxU32 numNormalConstr = hdr->numNormalConstr;
const PxU32 numFrictionConstr = hdr->numFrictionConstr;
Vec4V* PX_RESTRICT appliedForces = reinterpret_cast<Vec4V*>(currPtr);
currPtr += sizeof(Vec4V)*numNormalConstr;
//SolverContactBatchPointBase4* PX_RESTRICT contacts = (SolverContactBatchPointBase4*)currPtr;
currPtr += (numNormalConstr * contactSize);
bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0;
if(hasMaxImpulse)
currPtr += sizeof(Vec4V) * numNormalConstr;
SolverFrictionSharedData4* PX_RESTRICT fd = reinterpret_cast<SolverFrictionSharedData4*>(currPtr);
if(numFrictionConstr)
currPtr += sizeof(SolverFrictionSharedData4);
currPtr += sizeof(Vec4V)*numFrictionConstr;
//SolverContactFrictionBase4* PX_RESTRICT frictions = (SolverContactFrictionBase4*)currPtr;
currPtr += (numFrictionConstr * frictionSize);
writeBackThresholds[0] = hdr->flags[0] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[1] = hdr->flags[1] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[2] = hdr->flags[2] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
writeBackThresholds[3] = hdr->flags[3] & SolverContactHeader::eHAS_FORCE_THRESHOLDS;
for(PxU32 i=0;i<numNormalConstr;i++)
{
//contacts = (SolverContactBatchPointBase4*)(((PxU8*)contacts) + contactSize);
const FloatV appliedForce0 = V4GetX(appliedForces[i]);
const FloatV appliedForce1 = V4GetY(appliedForces[i]);
const FloatV appliedForce2 = V4GetZ(appliedForces[i]);
const FloatV appliedForce3 = V4GetW(appliedForces[i]);
normalForce = V4Add(normalForce, appliedForces[i]);
if(vForceWriteback0 && i < hdr->numNormalConstr0)
FStore(appliedForce0, vForceWriteback0++);
if(vForceWriteback1 && i < hdr->numNormalConstr1)
FStore(appliedForce1, vForceWriteback1++);
if(vForceWriteback2 && i < hdr->numNormalConstr2)
FStore(appliedForce2, vForceWriteback2++);
if(vForceWriteback3 && i < hdr->numNormalConstr3)
FStore(appliedForce3, vForceWriteback3++);
}
if(numFrictionConstr)
{
PX_ALIGN(16, PxU32 broken[4]);
BStoreA(fd->broken, broken);
PxU8* frictionCounts = &hdr->numFrictionConstr0;
for(PxU32 a = 0; a < 4; ++a)
{
if(frictionCounts[a] && broken[a])
*fd->frictionBrokenWritebackByte[a] = 1; // PT: bad L2 miss here
}
}
}
PX_ALIGN(16, PxReal nf[4]);
V4StoreA(normalForce, nf);
Sc::ShapeInteraction** shapeInteractions = reinterpret_cast<SolverContactHeader4*>(desc[0].constraint)->shapeInteraction;
for(PxU32 a = 0; a < 4; ++a)
{
if(writeBackThresholds[a] && desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY &&
nf[a] !=0.f && (bd0[a]->reportThreshold < PX_MAX_REAL || bd1[a]->reportThreshold < PX_MAX_REAL))
{
ThresholdStreamElement elt;
elt.normalForce = nf[a];
elt.threshold = PxMin<float>(bd0[a]->reportThreshold, bd1[a]->reportThreshold);
elt.nodeIndexA = PxNodeIndex(bd0[a]->nodeIndex);
elt.nodeIndexB = PxNodeIndex(bd1[a]->nodeIndex);
elt.shapeInteraction = shapeInteractions[a];
PxOrder(elt.nodeIndexA, elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB);
PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength);
cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt;
}
}
}
static void solve1D4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
PxSolverBody& b00 = *desc[0].bodyA;
PxSolverBody& b01 = *desc[0].bodyB;
PxSolverBody& b10 = *desc[1].bodyA;
PxSolverBody& b11 = *desc[1].bodyB;
PxSolverBody& b20 = *desc[2].bodyA;
PxSolverBody& b21 = *desc[2].bodyB;
PxSolverBody& b30 = *desc[3].bodyA;
PxSolverBody& b31 = *desc[3].bodyB;
PxU8* PX_RESTRICT bPtr = desc[0].constraint;
//PxU32 length = desc.constraintLength;
SolverConstraint1DHeader4* PX_RESTRICT header = reinterpret_cast<SolverConstraint1DHeader4*>(bPtr);
SolverConstraint1DDynamic4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DDynamic4*>(header+1);
//const FloatV fZero = FZero();
Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x);
Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x);
Vec4V angState00 = V4LoadA(&b00.angularState.x);
Vec4V angState01 = V4LoadA(&b01.angularState.x);
Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x);
Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x);
Vec4V angState10 = V4LoadA(&b10.angularState.x);
Vec4V angState11 = V4LoadA(&b11.angularState.x);
Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x);
Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x);
Vec4V angState20 = V4LoadA(&b20.angularState.x);
Vec4V angState21 = V4LoadA(&b21.angularState.x);
Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x);
Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x);
Vec4V angState30 = V4LoadA(&b30.angularState.x);
Vec4V angState31 = V4LoadA(&b31.angularState.x);
Vec4V linVel0T0, linVel0T1, linVel0T2, linVel0T3;
Vec4V linVel1T0, linVel1T1, linVel1T2, linVel1T3;
Vec4V angState0T0, angState0T1, angState0T2, angState0T3;
Vec4V angState1T0, angState1T1, angState1T2, angState1T3;
PX_TRANSPOSE_44(linVel00, linVel10, linVel20, linVel30, linVel0T0, linVel0T1, linVel0T2, linVel0T3);
PX_TRANSPOSE_44(linVel01, linVel11, linVel21, linVel31, linVel1T0, linVel1T1, linVel1T2, linVel1T3);
PX_TRANSPOSE_44(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2, angState0T3);
PX_TRANSPOSE_44(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2, angState1T3);
const Vec4V invMass0D0 = header->invMass0D0;
const Vec4V invMass1D1 = header->invMass1D1;
const Vec4V angD0 = header->angD0;
const Vec4V angD1 = header->angD1;
const PxU32 maxConstraints = header->count;
for(PxU32 a = 0; a < maxConstraints; ++a)
{
SolverConstraint1DDynamic4& c = *base;
base++;
PxPrefetchLine(base);
PxPrefetchLine(base, 64);
PxPrefetchLine(base, 128);
PxPrefetchLine(base, 192);
PxPrefetchLine(base, 256);
const Vec4V appliedForce = c.appliedForce;
Vec4V linProj0(V4Mul(c.lin0X, linVel0T0));
Vec4V linProj1(V4Mul(c.lin1X, linVel1T0));
Vec4V angProj0(V4Mul(c.ang0X, angState0T0));
Vec4V angProj1(V4Mul(c.ang1X, angState1T0));
linProj0 = V4MulAdd(c.lin0Y, linVel0T1, linProj0);
linProj1 = V4MulAdd(c.lin1Y, linVel1T1, linProj1);
angProj0 = V4MulAdd(c.ang0Y, angState0T1, angProj0);
angProj1 = V4MulAdd(c.ang1Y, angState1T1, angProj1);
linProj0 = V4MulAdd(c.lin0Z, linVel0T2, linProj0);
linProj1 = V4MulAdd(c.lin1Z, linVel1T2, linProj1);
angProj0 = V4MulAdd(c.ang0Z, angState0T2, angProj0);
angProj1 = V4MulAdd(c.ang1Z, angState1T2, angProj1);
const Vec4V projectVel0 = V4Add(linProj0, angProj0);
const Vec4V projectVel1 = V4Add(linProj1, angProj1);
const Vec4V normalVel = V4Sub(projectVel0, projectVel1);
const Vec4V unclampedForce = V4MulAdd(appliedForce, c.impulseMultiplier, V4MulAdd(normalVel, c.velMultiplier, c.constant));
const Vec4V clampedForce = V4Max(c.minImpulse, V4Min(c.maxImpulse, unclampedForce));
const Vec4V deltaF = V4Sub(clampedForce, appliedForce);
c.appliedForce = clampedForce;
const Vec4V deltaFInvMass0 = V4Mul(deltaF, invMass0D0);
const Vec4V deltaFInvMass1 = V4Mul(deltaF, invMass1D1);
const Vec4V angDeltaFInvMass0 = V4Mul(deltaF, angD0);
const Vec4V angDeltaFInvMass1 = V4Mul(deltaF, angD1);
linVel0T0 = V4MulAdd(c.lin0X, deltaFInvMass0, linVel0T0);
linVel1T0 = V4NegMulSub(c.lin1X, deltaFInvMass1, linVel1T0);
angState0T0 = V4MulAdd(c.ang0X, angDeltaFInvMass0, angState0T0);
angState1T0 = V4NegMulSub(c.ang1X, angDeltaFInvMass1, angState1T0);
linVel0T1 = V4MulAdd(c.lin0Y, deltaFInvMass0, linVel0T1);
linVel1T1 = V4NegMulSub(c.lin1Y, deltaFInvMass1, linVel1T1);
angState0T1 = V4MulAdd(c.ang0Y, angDeltaFInvMass0, angState0T1);
angState1T1 = V4NegMulSub(c.ang1Y, angDeltaFInvMass1, angState1T1);
linVel0T2 = V4MulAdd(c.lin0Z, deltaFInvMass0, linVel0T2);
linVel1T2 = V4NegMulSub(c.lin1Z, deltaFInvMass1, linVel1T2);
angState0T2 = V4MulAdd(c.ang0Z, angDeltaFInvMass0, angState0T2);
angState1T2 = V4NegMulSub(c.ang1Z, angDeltaFInvMass1, angState1T2);
}
PX_TRANSPOSE_44(linVel0T0, linVel0T1, linVel0T2, linVel0T3, linVel00, linVel10, linVel20, linVel30);
PX_TRANSPOSE_44(linVel1T0, linVel1T1, linVel1T2, linVel1T3, linVel01, linVel11, linVel21, linVel31);
PX_TRANSPOSE_44(angState0T0, angState0T1, angState0T2, angState0T3, angState00, angState10, angState20, angState30);
PX_TRANSPOSE_44(angState1T0, angState1T1, angState1T2, angState1T3, angState01, angState11, angState21, angState31);
// Write back
V4StoreA(linVel00, &b00.linearVelocity.x);
V4StoreA(linVel10, &b10.linearVelocity.x);
V4StoreA(linVel20, &b20.linearVelocity.x);
V4StoreA(linVel30, &b30.linearVelocity.x);
V4StoreA(linVel01, &b01.linearVelocity.x);
V4StoreA(linVel11, &b11.linearVelocity.x);
V4StoreA(linVel21, &b21.linearVelocity.x);
V4StoreA(linVel31, &b31.linearVelocity.x);
V4StoreA(angState00, &b00.angularState.x);
V4StoreA(angState10, &b10.angularState.x);
V4StoreA(angState20, &b20.angularState.x);
V4StoreA(angState30, &b30.angularState.x);
V4StoreA(angState01, &b01.angularState.x);
V4StoreA(angState11, &b11.angularState.x);
V4StoreA(angState21, &b21.angularState.x);
V4StoreA(angState31, &b31.angularState.x);
}
static void conclude1D4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/)
{
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(desc[0].constraint);
PxU8* base = desc[0].constraint + sizeof(SolverConstraint1DHeader4);
const PxU32 stride = header->type == DY_SC_TYPE_BLOCK_1D ? sizeof(SolverConstraint1DDynamic4) : sizeof(SolverConstraint1DBase4);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
SolverConstraint1DBase4& c = *reinterpret_cast<SolverConstraint1DBase4*>(base);
c.constant = c.unbiasedConstant;
base += stride;
}
PX_ASSERT(desc[0].constraint + getConstraintLength(desc[0]) == base);
}
static void writeBack1D4(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext& /*cache*/,
const PxSolverBodyData** PX_RESTRICT /*bd0*/, const PxSolverBodyData** PX_RESTRICT /*bd1*/)
{
ConstraintWriteback* writeback0 = reinterpret_cast<ConstraintWriteback*>(desc[0].writeBack);
ConstraintWriteback* writeback1 = reinterpret_cast<ConstraintWriteback*>(desc[1].writeBack);
ConstraintWriteback* writeback2 = reinterpret_cast<ConstraintWriteback*>(desc[2].writeBack);
ConstraintWriteback* writeback3 = reinterpret_cast<ConstraintWriteback*>(desc[3].writeBack);
if(writeback0 || writeback1 || writeback2 || writeback3)
{
SolverConstraint1DHeader4* header = reinterpret_cast<SolverConstraint1DHeader4*>(desc[0].constraint);
PxU8* base = desc[0].constraint + sizeof(SolverConstraint1DHeader4);
PxU32 stride = header->type == DY_SC_TYPE_BLOCK_1D ? sizeof(SolverConstraint1DDynamic4) : sizeof(SolverConstraint1DBase4);
const Vec4V zero = V4Zero();
Vec4V linX(zero), linY(zero), linZ(zero);
Vec4V angX(zero), angY(zero), angZ(zero);
const PxU32 count = header->count;
for(PxU32 i=0; i<count; i++)
{
const SolverConstraint1DBase4* c = reinterpret_cast<SolverConstraint1DBase4*>(base);
//Load in flags
const VecI32V flags = I4LoadU(reinterpret_cast<const PxI32*>(&c->flags[0]));
//Work out masks
const VecI32V mask = I4Load(DY_SC_FLAG_OUTPUT_FORCE);
const VecI32V masked = VecI32V_And(flags, mask);
const BoolV isEq = VecI32V_IsEq(masked, mask);
const Vec4V appliedForce = V4Sel(isEq, c->appliedForce, zero);
linX = V4MulAdd(c->lin0X, appliedForce, linX);
linY = V4MulAdd(c->lin0Y, appliedForce, linY);
linZ = V4MulAdd(c->lin0Z, appliedForce, linZ);
angX = V4MulAdd(c->ang0WritebackX, appliedForce, angX);
angY = V4MulAdd(c->ang0WritebackY, appliedForce, angY);
angZ = V4MulAdd(c->ang0WritebackZ, appliedForce, angZ);
base += stride;
}
//We need to do the cross product now
angX = V4Sub(angX, V4NegMulSub(header->body0WorkOffsetZ, linY, V4Mul(header->body0WorkOffsetY, linZ)));
angY = V4Sub(angY, V4NegMulSub(header->body0WorkOffsetX, linZ, V4Mul(header->body0WorkOffsetZ, linX)));
angZ = V4Sub(angZ, V4NegMulSub(header->body0WorkOffsetY, linX, V4Mul(header->body0WorkOffsetX, linY)));
const Vec4V linLenSq = V4MulAdd(linZ, linZ, V4MulAdd(linY, linY, V4Mul(linX, linX)));
const Vec4V angLenSq = V4MulAdd(angZ, angZ, V4MulAdd(angY, angY, V4Mul(angX, angX)));
const Vec4V linLen = V4Sqrt(linLenSq);
const Vec4V angLen = V4Sqrt(angLenSq);
const BoolV broken = BOr(V4IsGrtr(linLen, header->linBreakImpulse), V4IsGrtr(angLen, header->angBreakImpulse));
PX_ALIGN(16, PxU32 iBroken[4]);
BStoreA(broken, iBroken);
Vec4V lin0, lin1, lin2, lin3;
Vec4V ang0, ang1, ang2, ang3;
PX_TRANSPOSE_34_44(linX, linY, linZ, lin0, lin1, lin2, lin3);
PX_TRANSPOSE_34_44(angX, angY, angZ, ang0, ang1, ang2, ang3);
if(writeback0)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin0), writeback0->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang0), writeback0->angularImpulse);
writeback0->broken = header->break0 ? PxU32(iBroken[0] != 0) : 0;
}
if(writeback1)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin1), writeback1->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang1), writeback1->angularImpulse);
writeback1->broken = header->break1 ? PxU32(iBroken[1] != 0) : 0;
}
if(writeback2)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin2), writeback2->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang2), writeback2->angularImpulse);
writeback2->broken = header->break2 ? PxU32(iBroken[2] != 0) : 0;
}
if(writeback3)
{
V3StoreU(Vec3V_From_Vec4V_WUndefined(lin3), writeback3->linearImpulse);
V3StoreU(Vec3V_From_Vec4V_WUndefined(ang3), writeback3->angularImpulse);
writeback3->broken = header->break3 ? PxU32(iBroken[3] != 0) : 0;
}
PX_ASSERT(desc[0].constraint + getConstraintLength(desc[0]) == base);
}
}
void solveContactPreBlock(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
}
void solveContactPreBlock_Static(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
}
void solveContactPreBlock_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
concludeContact4_Block(desc, cache, sizeof(SolverContactBatchPointDynamic4), sizeof(SolverContactFrictionDynamic4));
}
void solveContactPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
concludeContact4_Block(desc, cache, sizeof(SolverContactBatchPointBase4), sizeof(SolverContactFrictionBase4));
}
void solveContactPreBlock_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContact4_Block(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solveContactPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solveContact4_StaticBlock(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBackContact4_Block(desc, cache, bd0, bd1);
if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4))
{
//Write back to global buffer
PxI32 threshIndex = physx::PxAtomicAdd(cache.mSharedOutThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 a = 0; a < cache.mThresholdStreamIndex; ++a)
{
cache.mSharedThresholdStream[a + threshIndex] = cache.mThresholdStream[a];
}
cache.mThresholdStreamIndex = 0;
}
}
void solve1D4_Block(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
}
void solve1D4Block_Conclude(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
conclude1D4_Block(desc, cache);
}
void solve1D4Block_WriteBack(DY_PGS_SOLVE_METHOD_PARAMS)
{
PX_UNUSED(constraintCount);
solve1D4_Block(desc, cache);
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBack1D4(desc, cache, bd0, bd1);
}
void writeBack1D4Block(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 /*constraintCount*/, SolverContext& cache)
{
const PxSolverBodyData* bd0[4] = { &cache.solverBodyArray[desc[0].bodyADataIndex],
&cache.solverBodyArray[desc[1].bodyADataIndex],
&cache.solverBodyArray[desc[2].bodyADataIndex],
&cache.solverBodyArray[desc[3].bodyADataIndex]};
const PxSolverBodyData* bd1[4] = { &cache.solverBodyArray[desc[0].bodyBDataIndex],
&cache.solverBodyArray[desc[1].bodyBDataIndex],
&cache.solverBodyArray[desc[2].bodyBDataIndex],
&cache.solverBodyArray[desc[3].bodyBDataIndex]};
writeBack1D4(desc, cache, bd0, bd1);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContext.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 DY_SOLVER_CONTEXT_H
#define DY_SOLVER_CONTEXT_H
namespace physx
{
struct PxSolverBodyData;
namespace Dy
{
struct ThresholdStreamElement;
struct SolverContext
{
bool doFriction;
bool writeBackIteration;
// for threshold stream output
ThresholdStreamElement* mThresholdStream;
PxU32 mThresholdStreamIndex;
PxU32 mThresholdStreamLength;
PxSolverBodyData* solverBodyArray;
ThresholdStreamElement* PX_RESTRICT mSharedThresholdStream;
PxU32 mSharedThresholdStreamLength;
PxI32* mSharedOutThresholdPairs;
Cm::SpatialVectorF* Z;
Cm::SpatialVectorF* deltaV;
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverCore.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 DY_SOLVER_CORE_H
#define DY_SOLVER_CORE_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxThread.h"
#include "foundation/PxUserAllocated.h"
// PT: it is not wrong to include DyPGS.h here because the SolverCore class is actually only used by PGS.
// (for patch / point friction). TGS doesn't use the same architecture / class hierarchy.
#include "DyPGS.h"
namespace physx
{
struct PxSolverBody;
struct PxSolverBodyData;
struct PxSolverConstraintDesc;
struct PxConstraintBatchHeader;
namespace Dy
{
struct ThresholdStreamElement;
struct ArticulationSolverDesc;
#define PX_PROFILE_SOLVE_STALLS 0
#if PX_PROFILE_SOLVE_STALLS
#if PX_WINDOWS
#include "foundation/windows/PxWindowsInclude.h"
PX_FORCE_INLINE PxU64 readTimer()
{
//return __rdtsc();
LARGE_INTEGER i;
QueryPerformanceCounter(&i);
return i.QuadPart;
}
#endif
#endif
#define YIELD_THREADS 1
#if YIELD_THREADS
#define ATTEMPTS_BEFORE_BACKOFF 30000
#define ATTEMPTS_BEFORE_RETEST 10000
#endif
PX_INLINE void WaitForProgressCount(volatile PxI32* pGlobalIndex, const PxI32 targetIndex)
{
#if YIELD_THREADS
if(*pGlobalIndex < targetIndex)
{
bool satisfied = false;
PxU32 count = ATTEMPTS_BEFORE_BACKOFF;
do
{
satisfied = true;
while(*pGlobalIndex < targetIndex)
{
if(--count == 0)
{
satisfied = false;
break;
}
}
if(!satisfied)
PxThread::yield();
count = ATTEMPTS_BEFORE_RETEST;
}
while(!satisfied);
}
#else
while(*pGlobalIndex < targetIndex);
#endif
}
#if PX_PROFILE_SOLVE_STALLS
PX_INLINE void WaitForProgressCount(volatile PxI32* pGlobalIndex, const PxI32 targetIndex, PxU64& stallTime)
{
if(*pGlobalIndex < targetIndex)
{
bool satisfied = false;
PxU32 count = ATTEMPTS_BEFORE_BACKOFF;
do
{
satisfied = true;
PxU64 startTime = readTimer();
while(*pGlobalIndex < targetIndex)
{
if(--count == 0)
{
satisfied = false;
break;
}
}
PxU64 endTime = readTimer();
stallTime += (endTime - startTime);
if(!satisfied)
PxThread::yield();
count = ATTEMPTS_BEFORE_BACKOFF;
}
while(!satisfied);
}
}
#define WAIT_FOR_PROGRESS(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex, stallCount)
#else
#define WAIT_FOR_PROGRESS(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex)
#endif
#define WAIT_FOR_PROGRESS_NO_TIMER(pGlobalIndex, targetIndex) if(*pGlobalIndex < targetIndex) WaitForProgressCount(pGlobalIndex, targetIndex)
struct SolverIslandParams
{
//Default friction model params
PxU32 positionIterations;
PxU32 velocityIterations;
PxSolverBody* PX_RESTRICT bodyListStart;
PxSolverBodyData* PX_RESTRICT bodyDataList;
PxU32 bodyListSize;
PxU32 solverBodyOffset;
ArticulationSolverDesc* PX_RESTRICT articulationListStart;
PxU32 articulationListSize;
PxSolverConstraintDesc* PX_RESTRICT constraintList;
PxConstraintBatchHeader* constraintBatchHeaders;
PxU32 numConstraintHeaders;
PxU32* headersPerPartition;
PxU32 nbPartitions;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray;
PxU32 batchSize;
PxsBodyCore*const* bodyArray;
PxsRigidBody** PX_RESTRICT rigidBodies;
//Shared state progress counters
PxI32 constraintIndex;
PxI32 constraintIndexCompleted;
PxI32 bodyListIndex;
PxI32 bodyListIndexCompleted;
PxI32 articSolveIndex;
PxI32 articSolveIndexCompleted;
PxI32 bodyIntegrationListIndex;
PxI32 numObjectsIntegrated;
PxReal dt;
PxReal invDt;
//Additional 1d/2d friction model params
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList;
PxConstraintBatchHeader* frictionConstraintBatches;
PxU32 numFrictionConstraintHeaders;
PxU32* frictionHeadersPerPartition;
PxU32 nbFrictionPartitions;
//Additional Shared state progress counters
PxI32 frictionConstraintIndex;
//Write-back threshold information
ThresholdStreamElement* PX_RESTRICT thresholdStream;
PxU32 thresholdStreamLength;
PxI32* outThresholdPairs;
PxU32 mMaxArticulationLinks;
Cm::SpatialVectorF* Z;
Cm::SpatialVectorF* deltaV;
};
/*!
Interface to constraint solver cores
*/
class SolverCore : public PxUserAllocated
{
public:
virtual ~SolverCore() {}
/*
solves dual problem exactly by GS-iterating until convergence stops
only uses regular velocity vector for storing results, and backs up initial state, which is restored.
the solution forces are saved in a vector.
state should not be stored, this function is safe to call from multiple threads.
*/
virtual void solveVParallelAndWriteBack
(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const = 0;
virtual void solveV_Blocks
(SolverIslandParams& params) const = 0;
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrep.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 DY_TGS_CONTACT_PREP_H
#define DY_TGS_CONTACT_PREP_H
#include "foundation/PxPreprocessor.h"
#include "DySolverConstraintDesc.h"
#include "PxSceneDesc.h"
#include "DySolverContact4.h"
namespace physx
{
struct PxsContactManagerOutput;
struct PxSolverConstraintDesc;
namespace Dy
{
class ThreadContext;
struct CorrelationBuffer;
bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc,
PxsContactManagerOutput& output,
ThreadContext& threadContext,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal stepDt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
bool createFinalizeSolverContactsStep(
PxTGSSolverContactDesc& contactDesc,
CorrelationBuffer& c,
const PxReal invDtF32,
const PxReal invTotalDtF32,
const PxReal totalDtF32,
const PxReal dtF32,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, PxU32 maxRows,
const PxReal lengthScale, const PxReal biasCoefficient);
PxU32 SetupSolverConstraintStep(SolverConstraintShaderPrepDesc& shaderDesc,
PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient);
PxU32 setupSolverConstraintStep(
const PxTGSSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
const PxReal dt, const PxReal totalDt, const PxReal invdt, const PxReal invTotalDt,
const PxReal lengthScale, const PxReal biasCoefficient);
SolverConstraintPrepState::Enum setupSolverConstraintStep4
(SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs,
PxTGSSolverConstraintPrepDesc* PX_RESTRICT constraintDescs,
const PxReal dt, const PxReal totalDt, const PxReal recipdt, const PxReal recipTotalDt, PxU32& totalRows,
PxConstraintAllocator& allocator, const PxReal lengthScale, const PxReal biasCoefficient);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
PxsContactManagerOutput** cmOutputs,
ThreadContext& threadContext,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDtF32,
const PxReal invTotalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step(
Dy::CorrelationBuffer& c,
PxTGSSolverContactDesc* blockDescs,
const PxReal invDtF32,
const PxReal totalDt,
const PxReal invTotalDtF32,
const PxReal dt,
const PxReal bounceThresholdF32,
const PxReal frictionOffsetThreshold,
const PxReal correlationDistance,
const PxReal biasCoefficient,
PxConstraintAllocator& constraintAllocator);
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyRigidBodyToSolverBody.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 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 "CmUtils.h"
#include "DySolverBody.h"
#include "PxsRigidBody.h"
#include "PxvDynamics.h"
#include "foundation/PxSIMDHelpers.h"
using namespace physx;
// PT: TODO: SIMDify all this...
void Dy::copyToSolverBodyData(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose,
PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxSolverBodyData& data, PxU32 lockFlags,
PxReal dt, bool gyroscopicForces)
{
data.nodeIndex = nodeIndex;
const PxVec3 safeSqrtInvInertia = computeSafeSqrtInertia(invInertia);
const PxMat33Padded rotation(globalPose.q);
Cm::transformInertiaTensor(safeSqrtInvInertia, rotation, data.sqrtInvInertia);
PxVec3 ang = angularVelocity;
PxVec3 lin = linearVelocity;
if (gyroscopicForces)
{
const PxVec3 localInertia(
invInertia.x == 0.f ? 0.f : 1.f / invInertia.x,
invInertia.y == 0.f ? 0.f : 1.f / invInertia.y,
invInertia.z == 0.f ? 0.f : 1.f / invInertia.z);
const PxVec3 localAngVel = globalPose.q.rotateInv(ang);
const PxVec3 origMom = localInertia.multiply(localAngVel);
const PxVec3 torque = -localAngVel.cross(origMom);
PxVec3 newMom = origMom + torque * dt;
const PxReal denom = newMom.magnitude();
const PxReal ratio = denom > 0.f ? origMom.magnitude() / denom : 0.f;
newMom *= ratio;
const PxVec3 newDeltaAngVel = globalPose.q.rotate(invInertia.multiply(newMom) - localAngVel);
ang += newDeltaAngVel;
}
if (lockFlags)
{
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
data.linearVelocity.x = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
data.linearVelocity.y = 0.f;
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
data.linearVelocity.z = 0.f;
//KS - technically, we can zero the inertia columns and produce stiffer constraints. However, this can cause numerical issues with the
//joint solver, which is fixed by disabling joint preprocessing and setting minResponseThreshold to some reasonable value > 0. However, until
//this is handled automatically, it's probably better not to zero these inertia rows
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
{
ang.x = 0.f;
//data.sqrtInvInertia.column0 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
{
ang.y = 0.f;
//data.sqrtInvInertia.column1 = PxVec3(0.f);
}
if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
{
ang.z = 0.f;
//data.sqrtInvInertia.column2 = PxVec3(0.f);
}
}
PX_ASSERT(lin.isFinite());
PX_ASSERT(ang.isFinite());
data.angularVelocity = ang;
data.linearVelocity = lin;
data.invMass = invMass;
data.penBiasClamp = maxDepenetrationVelocity;
data.maxContactImpulse = maxContactImpulse;
data.body2World = globalPose;
data.reportThreshold = reportThreshold;
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintExtShared.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 DY_SOLVER_CONSTRAINT_EXT_SHARED_H
#define DY_SOLVER_CONSTRAINT_EXT_SHARED_H
#include "foundation/PxPreprocessor.h"
#include "foundation/PxVecMath.h"
#include "DyArticulationContactPrep.h"
#include "DySolverConstraintDesc.h"
#include "DySolverConstraint1D.h"
#include "DySolverContact.h"
#include "DySolverContactPF.h"
#include "PxcNpWorkUnit.h"
#include "PxsMaterialManager.h"
namespace physx
{
namespace Dy
{
FloatV setupExtSolverContact(const SolverExtBody& b0, const SolverExtBody& b1,
const FloatV& d0, const FloatV& d1, const FloatV& angD0, const FloatV& angD1, const Vec3V& bodyFrame0p, const Vec3V& bodyFrame1p,
const Vec3VArg normal, const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg dt, const FloatVArg restDistance, const FloatVArg maxPenBias, const FloatVArg restitution,
const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointExt& solverContact, const FloatVArg ccdMaxSeparation,
Cm::SpatialVectorF* Z, const Cm::SpatialVectorV& v0, const Cm::SpatialVectorV& v1, const FloatV& cfm, const Vec3VArg solverOffsetSlop,
const FloatVArg norVel0, const FloatVArg norVel1, const FloatVArg damping);
} //namespace Dy
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintSetup.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxMemory.h"
#include "foundation/PxMathUtils.h"
#include "DyConstraintPrep.h"
#include "DyArticulationCpuGpu.h"
#include "PxsRigidBody.h"
#include "DySolverConstraint1D.h"
#include "foundation/PxSort.h"
#include "DySolverConstraintDesc.h"
#include "PxcConstraintBlockStream.h"
#include "DyArticulationContactPrep.h"
#include "foundation/PxSIMDHelpers.h"
namespace physx
{
namespace Dy
{
// dsequeira:
//
// we can choose any linear combination of equality constraints and get the same solution
// Hence we can orthogonalize the constraints using the inner product given by the
// inverse mass matrix, so that when we use PGS, solving a constraint row for a joint
// don't disturb the solution of prior rows.
//
// We also eliminate the equality constraints from the hard inequality constraints -
// (essentially projecting the direction corresponding to the lagrange multiplier
// onto the equality constraint subspace) but 'til I've verified this generates
// exactly the same KKT/complementarity conditions, status is 'experimental'.
//
// since for equality constraints the resulting rows have the property that applying
// an impulse along one row doesn't alter the projected velocity along another row,
// all equality constraints (plus one inequality constraint) can be processed in parallel
// using SIMD
//
// Eliminating the inequality constraints from each other would require a solver change
// and not give us any more parallelism, although we might get better convergence.
namespace
{
PX_FORCE_INLINE Vec3V V3FromV4(Vec4V x) { return Vec3V_From_Vec4V(x); }
PX_FORCE_INLINE Vec3V V3FromV4Unsafe(Vec4V x) { return Vec3V_From_Vec4V_WUndefined(x); }
PX_FORCE_INLINE Vec4V V4FromV3(Vec3V x) { return Vec4V_From_Vec3V(x); }
//PX_FORCE_INLINE Vec4V V4ClearW(Vec4V x) { return V4SetW(x, FZero()); }
struct MassProps
{
FloatV invMass0;
FloatV invMass1;
FloatV invInertiaScale0;
FloatV invInertiaScale1;
PX_FORCE_INLINE MassProps(const PxReal imass0, const PxReal imass1, const PxConstraintInvMassScale& ims) :
invMass0(FLoad(imass0 * ims.linear0)),
invMass1(FLoad(imass1 * ims.linear1)),
invInertiaScale0(FLoad(ims.angular0)),
invInertiaScale1(FLoad(ims.angular1))
{}
};
PX_FORCE_INLINE PxReal innerProduct(const Px1DConstraint& row0, Px1DConstraint& row1,
PxVec4& row0AngSqrtInvInertia0, PxVec4& row0AngSqrtInvInertia1,
PxVec4& row1AngSqrtInvInertia0, PxVec4& row1AngSqrtInvInertia1, const MassProps& m)
{
const Vec3V l0 = V3Mul(V3Scale(V3LoadA(row0.linear0), m.invMass0), V3LoadA(row1.linear0));
const Vec3V l1 = V3Mul(V3Scale(V3LoadA(row0.linear1), m.invMass1), V3LoadA(row1.linear1));
const Vec4V r0ang0 = V4LoadA(&row0AngSqrtInvInertia0.x);
const Vec4V r1ang0 = V4LoadA(&row1AngSqrtInvInertia0.x);
const Vec4V r0ang1 = V4LoadA(&row0AngSqrtInvInertia1.x);
const Vec4V r1ang1 = V4LoadA(&row1AngSqrtInvInertia1.x);
const Vec3V i0 = V3ScaleAdd(V3Mul(Vec3V_From_Vec4V(r0ang0), Vec3V_From_Vec4V(r1ang0)), m.invInertiaScale0, l0);
const Vec3V i1 = V3ScaleAdd(V3MulAdd(Vec3V_From_Vec4V(r0ang1), Vec3V_From_Vec4V(r1ang1), i0), m.invInertiaScale1, l1);
PxF32 f;
FStore(V3SumElems(i1), &f);
return f;
}
// indexed rotation around axis, with sine and cosine of half-angle
PX_FORCE_INLINE PxQuat indexedRotation(PxU32 axis, PxReal s, PxReal c)
{
PxQuat q(0,0,0,c);
reinterpret_cast<PxReal*>(&q)[axis] = s;
return q;
}
PxQuat diagonalize(const PxMat33& m) // jacobi rotation using quaternions
{
const PxU32 MAX_ITERS = 5;
PxQuat q(PxIdentity);
PxMat33 d;
for(PxU32 i=0; i < MAX_ITERS;i++)
{
const PxMat33Padded axes(q);
d = axes.getTranspose() * m * axes;
const PxReal d0 = PxAbs(d[1][2]), d1 = PxAbs(d[0][2]), d2 = PxAbs(d[0][1]);
const PxU32 a = PxU32(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2); // rotation axis index, from largest off-diagonal element
const PxU32 a1 = PxGetNextIndex3(a), a2 = PxGetNextIndex3(a1);
if(d[a1][a2] == 0.0f || PxAbs(d[a1][a1]-d[a2][a2]) > 2e6f*PxAbs(2.0f*d[a1][a2]))
break;
const PxReal w = (d[a1][a1]-d[a2][a2]) / (2.0f*d[a1][a2]); // cot(2 * phi), where phi is the rotation angle
const PxReal absw = PxAbs(w);
PxQuat r;
if(absw>1000)
r = indexedRotation(a, 1.0f/(4.0f*w), 1.f); // h will be very close to 1, so use small angle approx instead
else
{
const PxReal t = 1 / (absw + PxSqrt(w*w+1)); // absolute value of tan phi
const PxReal h = 1 / PxSqrt(t*t+1); // absolute value of cos phi
PX_ASSERT(h!=1); // |w|<1000 guarantees this with typical IEEE754 machine eps (approx 6e-8)
r = indexedRotation(a, PxSqrt((1-h)/2) * PxSign(w), PxSqrt((1+h)/2));
}
q = (q*r).getNormalized();
}
return q;
}
PX_FORCE_INLINE void rescale(const Mat33V& m, PxVec3& a0, PxVec3& a1, PxVec3& a2)
{
const Vec3V va0 = V3LoadU(a0);
const Vec3V va1 = V3LoadU(a1);
const Vec3V va2 = V3LoadU(a2);
const Vec3V b0 = V3ScaleAdd(va0, V3GetX(m.col0), V3ScaleAdd(va1, V3GetY(m.col0), V3Scale(va2, V3GetZ(m.col0))));
const Vec3V b1 = V3ScaleAdd(va0, V3GetX(m.col1), V3ScaleAdd(va1, V3GetY(m.col1), V3Scale(va2, V3GetZ(m.col1))));
const Vec3V b2 = V3ScaleAdd(va0, V3GetX(m.col2), V3ScaleAdd(va1, V3GetY(m.col2), V3Scale(va2, V3GetZ(m.col2))));
V3StoreU(b0, a0);
V3StoreU(b1, a1);
V3StoreU(b2, a2);
}
PX_FORCE_INLINE void rescale4(const Mat33V& m, PxReal* a0, PxReal* a1, PxReal* a2)
{
const Vec4V va0 = V4LoadA(a0);
const Vec4V va1 = V4LoadA(a1);
const Vec4V va2 = V4LoadA(a2);
const Vec4V b0 = V4ScaleAdd(va0, V3GetX(m.col0), V4ScaleAdd(va1, V3GetY(m.col0), V4Scale(va2, V3GetZ(m.col0))));
const Vec4V b1 = V4ScaleAdd(va0, V3GetX(m.col1), V4ScaleAdd(va1, V3GetY(m.col1), V4Scale(va2, V3GetZ(m.col1))));
const Vec4V b2 = V4ScaleAdd(va0, V3GetX(m.col2), V4ScaleAdd(va1, V3GetY(m.col2), V4Scale(va2, V3GetZ(m.col2))));
V4StoreA(b0, a0);
V4StoreA(b1, a1);
V4StoreA(b2, a2);
}
void diagonalize(Px1DConstraint** row,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
const MassProps &m)
{
const PxReal a00 = innerProduct(*row[0], *row[0], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[0], angSqrtInvInertia1[0], m);
const PxReal a01 = innerProduct(*row[0], *row[1], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[1], angSqrtInvInertia1[1], m);
const PxReal a02 = innerProduct(*row[0], *row[2], angSqrtInvInertia0[0], angSqrtInvInertia1[0], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxReal a11 = innerProduct(*row[1], *row[1], angSqrtInvInertia0[1], angSqrtInvInertia1[1], angSqrtInvInertia0[1], angSqrtInvInertia1[1], m);
const PxReal a12 = innerProduct(*row[1], *row[2], angSqrtInvInertia0[1], angSqrtInvInertia1[1], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxReal a22 = innerProduct(*row[2], *row[2], angSqrtInvInertia0[2], angSqrtInvInertia1[2], angSqrtInvInertia0[2], angSqrtInvInertia1[2], m);
const PxMat33 a(PxVec3(a00, a01, a02),
PxVec3(a01, a11, a12),
PxVec3(a02, a12, a22));
const PxQuat q = diagonalize(a);
const PxMat33 n(-q);
const Mat33V mn(V3LoadU(n.column0), V3LoadU(n.column1), V3LoadU(n.column2));
//KS - We treat as a Vec4V so that we get geometricError rescaled for free along with linear0
rescale4(mn, &row[0]->linear0.x, &row[1]->linear0.x, &row[2]->linear0.x);
rescale(mn, row[0]->linear1, row[1]->linear1, row[2]->linear1);
//KS - We treat as a PxVec4 so that we get velocityTarget rescaled for free
rescale4(mn, &row[0]->angular0.x, &row[1]->angular0.x, &row[2]->angular0.x);
rescale(mn, row[0]->angular1, row[1]->angular1, row[2]->angular1);
rescale4(mn, &angSqrtInvInertia0[0].x, &angSqrtInvInertia0[1].x, &angSqrtInvInertia0[2].x);
rescale4(mn, &angSqrtInvInertia1[0].x, &angSqrtInvInertia1[1].x, &angSqrtInvInertia1[2].x);
}
void orthogonalize(Px1DConstraint** row,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
PxU32 rowCount,
PxU32 eqRowCount,
const MassProps &m)
{
PX_ASSERT(eqRowCount<=6);
const FloatV zero = FZero();
Vec3V lin1m[6], ang1m[6], lin1[6], ang1[6];
Vec4V lin0m[6], ang0m[6]; // must have 0 in the W-field
Vec4V lin0AndG[6], ang0AndT[6];
for(PxU32 i=0;i<rowCount;i++)
{
Vec4V l0AndG = V4LoadA(&row[i]->linear0.x); // linear0 and geometric error
Vec4V a0AndT = V4LoadA(&row[i]->angular0.x); // angular0 and velocity target
Vec3V l1 = V3FromV4(V4LoadA(&row[i]->linear1.x));
Vec3V a1 = V3FromV4(V4LoadA(&row[i]->angular1.x));
Vec4V angSqrtL0 = V4LoadA(&angSqrtInvInertia0[i].x);
Vec4V angSqrtL1 = V4LoadA(&angSqrtInvInertia1[i].x);
const PxU32 eliminationRows = PxMin<PxU32>(i, eqRowCount);
for(PxU32 j=0;j<eliminationRows;j++)
{
const Vec3V s0 = V3MulAdd(l1, lin1m[j], V3FromV4Unsafe(V4Mul(l0AndG, lin0m[j])));
const Vec3V s1 = V3MulAdd(V3FromV4Unsafe(angSqrtL1), ang1m[j], V3FromV4Unsafe(V4Mul(angSqrtL0, ang0m[j])));
const FloatV t = V3SumElems(V3Add(s0, s1));
l0AndG = V4NegScaleSub(lin0AndG[j], t, l0AndG);
a0AndT = V4NegScaleSub(ang0AndT[j], t, a0AndT);
l1 = V3NegScaleSub(lin1[j], t, l1);
a1 = V3NegScaleSub(ang1[j], t, a1);
angSqrtL0 = V4NegScaleSub(V4LoadA(&angSqrtInvInertia0[j].x), t, angSqrtL0);
angSqrtL1 = V4NegScaleSub(V4LoadA(&angSqrtInvInertia1[j].x), t, angSqrtL1);
}
V4StoreA(l0AndG, &row[i]->linear0.x);
V4StoreA(a0AndT, &row[i]->angular0.x);
V3StoreA(l1, row[i]->linear1);
V3StoreA(a1, row[i]->angular1);
V4StoreA(angSqrtL0, &angSqrtInvInertia0[i].x);
V4StoreA(angSqrtL1, &angSqrtInvInertia1[i].x);
if(i<eqRowCount)
{
lin0AndG[i] = l0AndG;
ang0AndT[i] = a0AndT;
lin1[i] = l1;
ang1[i] = a1;
const Vec3V l0 = V3FromV4(l0AndG);
const Vec3V l0m = V3Scale(l0, m.invMass0);
const Vec3V l1m = V3Scale(l1, m.invMass1);
const Vec4V a0m = V4Scale(angSqrtL0, m.invInertiaScale0);
const Vec4V a1m = V4Scale(angSqrtL1, m.invInertiaScale1);
const Vec3V s0 = V3MulAdd(l0, l0m, V3Mul(l1, l1m));
const Vec4V s1 = V4MulAdd(a0m, angSqrtL0, V4Mul(a1m, angSqrtL1));
const FloatV s = V3SumElems(V3Add(s0, V3FromV4Unsafe(s1)));
const FloatV a = FSel(FIsGrtr(s, zero), FRecip(s), zero); // with mass scaling, it's possible for the inner product of a row to be zero
lin0m[i] = V4Scale(V4ClearW(V4FromV3(l0m)), a);
ang0m[i] = V4Scale(V4ClearW(a0m), a);
lin1m[i] = V3Scale(l1m, a);
ang1m[i] = V3Scale(V3FromV4Unsafe(a1m), a);
}
}
}
}
// PT: make sure that there's at least a PxU32 after sqrtInvInertia in the PxSolverBodyData structure (for safe SIMD reads)
//PX_COMPILE_TIME_ASSERT((sizeof(PxSolverBodyData) - PX_OFFSET_OF_RT(PxSolverBodyData, sqrtInvInertia)) >= (sizeof(PxMat33) + sizeof(PxU32)));
// PT: make sure that there's at least a PxU32 after angular0/angular1 in the Px1DConstraint structure (for safe SIMD reads)
// Note that the code was V4LoadAding these before anyway so it must be safe already.
// PT: removed for now because some compilers didn't like it
//PX_COMPILE_TIME_ASSERT((sizeof(Px1DConstraint) - PX_OFFSET_OF_RT(Px1DConstraint, angular0)) >= (sizeof(PxVec3) + sizeof(PxU32)));
//PX_COMPILE_TIME_ASSERT((sizeof(Px1DConstraint) - PX_OFFSET_OF_RT(Px1DConstraint, angular1)) >= (sizeof(PxVec3) + sizeof(PxU32)));
// PT: TODO: move somewhere else
PX_FORCE_INLINE Vec3V M33MulV4(const Mat33V& a, const Vec4V b)
{
const FloatV x = V4GetX(b);
const FloatV y = V4GetY(b);
const FloatV z = V4GetZ(b);
const Vec3V v0 = V3Scale(a.col0, x);
const Vec3V v1 = V3Scale(a.col1, y);
const Vec3V v2 = V3Scale(a.col2, z);
const Vec3V v0PlusV1 = V3Add(v0, v1);
return V3Add(v0PlusV1, v2);
}
void preprocessRows(Px1DConstraint** sorted,
Px1DConstraint* rows,
PxVec4* angSqrtInvInertia0,
PxVec4* angSqrtInvInertia1,
PxU32 rowCount,
const PxMat33& sqrtInvInertia0F32,
const PxMat33& sqrtInvInertia1F32,
const PxReal invMass0,
const PxReal invMass1,
const PxConstraintInvMassScale& ims,
bool disablePreprocessing,
bool diagonalizeDrive)
{
// j is maxed at 12, typically around 7, so insertion sort is fine
for(PxU32 i=0; i<rowCount; i++)
{
Px1DConstraint* r = rows+i;
PxU32 j = i;
for(;j>0 && r->solveHint < sorted[j-1]->solveHint; j--)
sorted[j] = sorted[j-1];
sorted[j] = r;
}
for(PxU32 i=0;i<rowCount-1;i++)
PX_ASSERT(sorted[i]->solveHint <= sorted[i+1]->solveHint);
for (PxU32 i = 0; i<rowCount; i++)
rows[i].forInternalUse = rows[i].flags & Px1DConstraintFlag::eKEEPBIAS ? rows[i].geometricError : 0;
const Mat33V sqrtInvInertia0 = Mat33V(V3LoadU(sqrtInvInertia0F32.column0), V3LoadU(sqrtInvInertia0F32.column1),
V3LoadU(sqrtInvInertia0F32.column2));
const Mat33V sqrtInvInertia1 = Mat33V(V3LoadU(sqrtInvInertia1F32.column0), V3LoadU(sqrtInvInertia1F32.column1),
V3LoadU(sqrtInvInertia1F32.column2));
PX_ASSERT(((uintptr_t(angSqrtInvInertia0)) & 0xF) == 0);
PX_ASSERT(((uintptr_t(angSqrtInvInertia1)) & 0xF) == 0);
for(PxU32 i=0; i<rowCount; ++i)
{
// PT: new version is 10 instructions smaller
//const Vec3V angDelta0_ = M33MulV3(sqrtInvInertia0, V3LoadU(sorted[i]->angular0));
//const Vec3V angDelta1_ = M33MulV3(sqrtInvInertia1, V3LoadU(sorted[i]->angular1));
const Vec3V angDelta0 = M33MulV4(sqrtInvInertia0, V4LoadA(&sorted[i]->angular0.x));
const Vec3V angDelta1 = M33MulV4(sqrtInvInertia1, V4LoadA(&sorted[i]->angular1.x));
V4StoreA(Vec4V_From_Vec3V(angDelta0), &angSqrtInvInertia0[i].x);
V4StoreA(Vec4V_From_Vec3V(angDelta1), &angSqrtInvInertia1[i].x);
}
if(disablePreprocessing)
return;
MassProps m(invMass0, invMass1, ims);
for(PxU32 i=0;i<rowCount;)
{
const PxU32 groupMajorId = PxU32(sorted[i]->solveHint>>8), start = i++;
while(i<rowCount && PxU32(sorted[i]->solveHint>>8) == groupMajorId)
i++;
if(groupMajorId == 4 || (groupMajorId == 8))
{
PxU32 bCount = start; // count of bilateral constraints
for(; bCount<i && (sorted[bCount]->solveHint&255)==0; bCount++)
;
orthogonalize(sorted+start, angSqrtInvInertia0+start, angSqrtInvInertia1+start, i-start, bCount-start, m);
}
if(groupMajorId == 1 && diagonalizeDrive)
{
PxU32 slerp = start; // count of bilateral constraints
for(; slerp<i && (sorted[slerp]->solveHint&255)!=2; slerp++)
;
if(slerp+3 == i)
diagonalize(sorted+slerp, angSqrtInvInertia0+slerp, angSqrtInvInertia1+slerp, m);
PX_ASSERT(i-start==3);
diagonalize(sorted+start, angSqrtInvInertia0+start, angSqrtInvInertia1+start, m);
}
}
}
PxU32 ConstraintHelper::setupSolverConstraint(
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt,
Cm::SpatialVectorF* Z)
{
if (prepDesc.numRows == 0)
{
prepDesc.desc->constraint = NULL;
prepDesc.desc->writeBack = NULL;
prepDesc.desc->constraintLengthOver16 = 0;
return 0;
}
PxSolverConstraintDesc& desc = *prepDesc.desc;
const bool isExtended = (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY)
|| (desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY);
const PxU32 stride = isExtended ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D);
const PxU32 constraintLength = sizeof(SolverConstraint1DHeader) + stride * prepDesc.numRows;
//KS - +16 is for the constraint progress counter, which needs to be the last element in the constraint (so that we
//know SPU DMAs have completed)
PxU8* ptr = allocator.reserveConstraintData(constraintLength + 16u);
if(NULL == ptr || (reinterpret_cast<PxU8*>(-1))==ptr)
{
if(NULL==ptr)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for constraint prep. "
"Either accept joints detaching/exploding or increase buffer size allocated for constraint prep by increasing PxSceneDesc::maxNbContactDataBlocks.");
return 0;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of constraint data. "
"Either accept joints detaching/exploding or simplify constraints.");
ptr=NULL;
return 0;
}
}
desc.constraint = ptr;
setConstraintLength(desc,constraintLength);
desc.writeBack = prepDesc.writeback;
PxMemSet(desc.constraint, 0, constraintLength);
SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint);
PxU8* constraints = desc.constraint + sizeof(SolverConstraint1DHeader);
init(*header, PxTo8(prepDesc.numRows), isExtended, prepDesc.invMassScales);
header->body0WorldOffset = prepDesc.body0WorldOffset;
header->linBreakImpulse = prepDesc.linBreakForce * dt;
header->angBreakImpulse = prepDesc.angBreakForce * dt;
header->breakable = PxU8((prepDesc.linBreakForce != PX_MAX_F32) || (prepDesc.angBreakForce != PX_MAX_F32));
header->invMass0D0 = prepDesc.data0->invMass * prepDesc.invMassScales.linear0;
header->invMass1D1 = prepDesc.data1->invMass * prepDesc.invMassScales.linear1;
PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS];
PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS];
Px1DConstraint* sorted[MAX_CONSTRAINT_ROWS];
preprocessRows(sorted, prepDesc.rows, angSqrtInvInertia0, angSqrtInvInertia1, prepDesc.numRows,
prepDesc.data0->sqrtInvInertia, prepDesc.data1->sqrtInvInertia, prepDesc.data0->invMass, prepDesc.data1->invMass,
prepDesc.invMassScales, isExtended || prepDesc.disablePreprocessing, prepDesc.improvedSlerp);
PxReal erp = 1.0f;
PxU32 outCount = 0;
const SolverExtBody eb0(reinterpret_cast<const void*>(prepDesc.body0), prepDesc.data0, desc.linkIndexA);
const SolverExtBody eb1(reinterpret_cast<const void*>(prepDesc.body1), prepDesc.data1, desc.linkIndexB);
PxReal cfm = 0.f;
if (isExtended)
{
cfm = PxMax(eb0.getCFM(), eb1.getCFM());
erp = 0.8f;
}
for (PxU32 i = 0; i<prepDesc.numRows; i++)
{
PxPrefetchLine(constraints, 128);
SolverConstraint1D& s = *reinterpret_cast<SolverConstraint1D *>(constraints);
Px1DConstraint& c = *sorted[i];
const PxReal driveScale = c.flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && prepDesc.driveLimitsAreForces ? PxMin(dt, 1.0f) : 1.0f;
PxReal unitResponse;
PxReal normalVel = 0.0f;
PxReal initVel = 0.f;
PxReal minResponseThreshold = prepDesc.minResponseThreshold;
if(!isExtended)
{
init(s, c.linear0, c.linear1, PxVec3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z),
PxVec3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z), c.minImpulse * driveScale, c.maxImpulse * driveScale);
s.ang0Writeback = c.angular0;
const PxReal resp0 = s.lin0.magnitudeSquared() * prepDesc.data0->invMass * prepDesc.invMassScales.linear0 + s.ang0.magnitudeSquared() * prepDesc.invMassScales.angular0;
const PxReal resp1 = s.lin1.magnitudeSquared() * prepDesc.data1->invMass * prepDesc.invMassScales.linear1 + s.ang1.magnitudeSquared() * prepDesc.invMassScales.angular1;
unitResponse = resp0 + resp1;
initVel = normalVel = prepDesc.data0->projectVelocity(c.linear0, c.angular0) - prepDesc.data1->projectVelocity(c.linear1, c.angular1);
}
else
{
//this is articulation/soft body
init(s, c.linear0, c.linear1, c.angular0, c.angular1, c.minImpulse * driveScale, c.maxImpulse * driveScale);
SolverConstraint1DExt& e = static_cast<SolverConstraint1DExt&>(s);
const Cm::SpatialVector resp0 = createImpulseResponseVector(e.lin0, e.ang0, eb0);
const Cm::SpatialVector resp1 = createImpulseResponseVector(-e.lin1, -e.ang1, eb1);
unitResponse = getImpulseResponse(eb0, resp0, unsimdRef(e.deltaVA), prepDesc.invMassScales.linear0, prepDesc.invMassScales.angular0,
eb1, resp1, unsimdRef(e.deltaVB), prepDesc.invMassScales.linear1, prepDesc.invMassScales.angular1, Z, false);
//Add CFM term!
if(unitResponse <= DY_ARTICULATION_MIN_RESPONSE)
continue;
unitResponse += cfm;
s.ang0Writeback = c.angular0;
s.lin0 = resp0.linear;
s.ang0 = resp0.angular;
s.lin1 = -resp1.linear;
s.ang1 = -resp1.angular;
PxReal vel0, vel1;
if(needsNormalVel(c) || eb0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY || eb1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
{
vel0 = eb0.projectVelocity(c.linear0, c.angular0);
vel1 = eb1.projectVelocity(c.linear1, c.angular1);
normalVel = vel0 - vel1;
//normalVel = eb0.projectVelocity(s.lin0, s.ang0) - eb1.projectVelocity(s.lin1, s.ang1);
if(eb0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
initVel = vel0;
else if(eb1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY)
initVel = -vel1;
}
//minResponseThreshold = PxMax(minResponseThreshold, DY_ARTICULATION_MIN_RESPONSE);
}
setSolverConstants(s.constant, s.unbiasedConstant, s.velMultiplier, s.impulseMultiplier,
c, normalVel, unitResponse, minResponseThreshold, erp, dt, invdt);
//If we have a spring then we will do the following:
//s.constant = -dt*kd*(vTar - v0)/denom - dt*ks*(xTar - x0)/denom
//s.unbiasedConstant = -dt*kd*(vTar - v0)/denom - dt*ks*(xTar - x0)/denom
const PxReal velBias = initVel * s.velMultiplier;
s.constant += velBias;
s.unbiasedConstant += velBias;
if(c.flags & Px1DConstraintFlag::eOUTPUT_FORCE)
s.flags |= DY_SC_FLAG_OUTPUT_FORCE;
outCount++;
constraints += stride;
}
//Reassign count to the header because we may have skipped some rows if they were degenerate
header->count = PxU8(outCount);
return prepDesc.numRows;
}
PxU32 SetupSolverConstraint(SolverConstraintShaderPrepDesc& shaderDesc,
PxSolverConstraintPrepDesc& prepDesc,
PxConstraintAllocator& allocator,
PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z)
{
// LL shouldn't see broken constraints
PX_ASSERT(!(reinterpret_cast<ConstraintWriteback*>(prepDesc.writeback)->broken));
setConstraintLength(*prepDesc.desc, 0);
if (!shaderDesc.solverPrep)
return 0;
//PxU32 numAxisConstraints = 0;
Px1DConstraint rows[MAX_CONSTRAINT_ROWS];
setupConstraintRows(rows, MAX_CONSTRAINT_ROWS);
prepDesc.invMassScales.linear0 = prepDesc.invMassScales.linear1 = prepDesc.invMassScales.angular0 = prepDesc.invMassScales.angular1 = 1.0f;
prepDesc.body0WorldOffset = PxVec3(0.0f);
PxVec3p unused_ra, unused_rb;
//TAG::solverprepcall
prepDesc.numRows = prepDesc.disableConstraint ? 0 : (*shaderDesc.solverPrep)(rows,
prepDesc.body0WorldOffset,
MAX_CONSTRAINT_ROWS,
prepDesc.invMassScales,
shaderDesc.constantBlock,
prepDesc.bodyFrame0, prepDesc.bodyFrame1, prepDesc.extendedLimits, unused_ra, unused_rb);
prepDesc.rows = rows;
return ConstraintHelper::setupSolverConstraint(prepDesc, allocator, dt, invdt, Z);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControlPF.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxIntrinsics.h"
#include "DySolverBody.h"
#include "DySolverConstraint1D.h"
#include "DySolverContact.h"
#include "DyThresholdTable.h"
#include "DySolverControl.h"
#include "DyArticulationPImpl.h"
#include "foundation/PxThread.h"
#include "DySolverConstraintDesc.h"
#include "DySolverContext.h"
#include "DySolverControlPF.h"
#include "DyArticulationCpuGpu.h"
namespace physx
{
namespace Dy
{
void solve1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4_Block (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExt1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solve1D4Block_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void writeBack1DBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void ext1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void writeBack1D4Block (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFriction_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtFrictionBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtContactCoulombBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulomb_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFriction_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveExtFrictionBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
//Pre-block 1d/2d friction stuff...
void solveContactCoulombPreBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_ConcludeStatic (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveContactCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS);
void solveFrictionCoulombPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS);
static SolveBlockMethod gVTableSolveBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlock, // DY_SC_TYPE_RB_CONTACT
solve1DBlock, // DY_SC_TYPE_RB_1D
solveExtContactCoulombBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlock, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_Static, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4_Block, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlock, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_Static // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveWriteBackBlockMethod gVTableSolveWriteBackBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_RB_CONTACT
solve1DBlockWriteBack, // DY_SC_TYPE_RB_1D
solveExtContactCoulombBlockWriteBack, // DY_SC_TYPE_EXT_CONTACT
solveExt1DBlockWriteBack, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombBlockWriteBack, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_WriteBackStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_WriteBack, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlockWriteBack, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlockWriteBack, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_WriteBackStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
static SolveBlockMethod gVTableSolveConcludeBlockCoulomb[] PX_UNUSED_ATTRIBUTE =
{
0,
solveContactCoulombConcludeBlock, // DY_SC_TYPE_RB_CONTACT
solve1DConcludeBlock, // DY_SC_TYPE_RB_1D
solveExtContactCoulombConcludeBlock, // DY_SC_TYPE_EXT_CONTACT
solveExt1DConcludeBlock, // DY_SC_TYPE_EXT_1D
solveContactCoulomb_BStaticConcludeBlock, // DY_SC_TYPE_STATIC_CONTACT
solveContactCoulombConcludeBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT
solveContactCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_RB_CONTACT
solveContactCoulombPreBlock_ConcludeStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT
solve1D4Block_Conclude, // DY_SC_TYPE_BLOCK_1D,
solveFrictionBlock, // DY_SC_TYPE_FRICTION
solveFriction_BStaticBlock, // DY_SC_TYPE_STATIC_FRICTION
solveExtFrictionBlock, // DY_SC_TYPE_EXT_FRICTION
solveFrictionCoulombPreBlock_Conclude, // DY_SC_TYPE_BLOCK_FRICTION
solveFrictionCoulombPreBlock_ConcludeStatic // DY_SC_TYPE_BLOCK_STATIC_FRICTION
};
// PT: code shared with patch friction solver. Ideally should move to a shared DySolverCore.cpp file.
void solveNoContactsCase( PxU32 bodyListSize, PxSolverBody* PX_RESTRICT bodyListStart, Cm::SpatialVector* PX_RESTRICT motionVelocityArray,
PxU32 articulationListSize, ArticulationSolverDesc* PX_RESTRICT articulationListStart, Cm::SpatialVectorF* PX_RESTRICT Z, Cm::SpatialVectorF* PX_RESTRICT deltaV,
PxU32 positionIterations, PxU32 velocityIterations, PxF32 dt, PxF32 invDt);
void saveMotionVelocities(PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray);
void SolverCoreGeneralPF::solveV_Blocks(SolverIslandParams& params) const
{
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.writeBackIteration = false;
cache.deltaV = params.deltaV;
cache.Z = params.Z;
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
const PxU32 bodyListSize = params.bodyListSize;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
const PxU32 velocityIterations = params.velocityIterations;
const PxU32 positionIterations = params.positionIterations;
const PxU32 numConstraintHeaders = params.numConstraintHeaders;
const PxU32 articulationListSize = params.articulationListSize;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
if(numConstraintHeaders == 0)
{
solveNoContactsCase(bodyListSize, bodyListStart, motionVelocityArray,
articulationListSize, articulationListStart, cache.Z, cache.deltaV,
positionIterations, velocityIterations, params.dt, params.invDt);
return;
}
BatchIterator contactIterator(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIterator(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
const PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
//0-(n-1) iterations
PxI32 normalIter = 0;
PxI32 frictionIter = 0;
for (PxU32 iteration = positionIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
++normalIter;
}
if(frictionBatchCount>0)
{
const PxU32 numIterations = positionIterations * 2;
for (PxU32 iteration = numIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, iteration == 1 ? gVTableSolveConcludeBlockCoulomb : gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
saveMotionVelocities(bodyListSize, bodyListStart, motionVelocityArray);
for (PxU32 i = 0; i < articulationListSize; i++)
ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, cache.deltaV);
const PxU32 velItersMinOne = velocityIterations - 1;
PxU32 iteration = 0;
for(; iteration < velItersMinOne; ++iteration)
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveBlockCoulomb, normalIter);
for (PxU32 i = 0; i < articulationListSize; ++i)
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
++normalIter;
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveBlockCoulomb, frictionIter);
++frictionIter;
}
}
PxI32* outThresholdPairs = params.outThresholdPairs;
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
PxU32 thresholdStreamLength = params.thresholdStreamLength;
cache.writeBackIteration = true;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
cache.mSharedThresholdStream = thresholdStream;
//PGS always runs one velocity iteration
{
SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount,
cache, contactIterator, gVTableSolveWriteBackBlockCoulomb, normalIter);
++normalIter;
for (PxU32 i = 0; i < articulationListSize; ++i)
{
articulationListStart[i].articulation->solveInternalConstraints(params.dt, params.invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articulationListStart[i].articulation->writebackInternalConstraints(false);
}
if(frictionBatchCount > 0)
{
SolveBlockParallel(frictionConstraintList, frictionBatchCount, frictionIter * frictionBatchCount, frictionBatchCount,
cache, frictionIterator, gVTableSolveWriteBackBlockCoulomb, frictionIter);
++frictionIter;
}
}
//Write back remaining threshold streams
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
const PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
void SolverCoreGeneralPF::solveVParallelAndWriteBack(SolverIslandParams& params,
Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const
{
const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT;
const bool isTGS = false;
SolverContext cache;
cache.solverBodyArray = params.bodyDataList;
const PxI32 UnrollCount = PxI32(params.batchSize);
const PxI32 SaveUnrollCount = 64;
const PxI32 ArticCount = 2;
const PxI32 TempThresholdStreamSize = 32;
ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize];
const PxI32 batchCount = PxI32(params.numConstraintHeaders);
const PxI32 frictionBatchCount = PxI32(params.numFrictionConstraintHeaders);//frictionConstraintBatches.size();
cache.mThresholdStream = tempThresholdStream;
cache.mThresholdStreamLength = TempThresholdStreamSize;
cache.mThresholdStreamIndex = 0;
cache.Z = Z;
cache.deltaV = deltaV;
const PxReal dt = params.dt;
const PxReal invDt = params.invDt;
ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart;
const PxI32 positionIterations = PxI32(params.positionIterations);
const PxU32 velocityIterations = params.velocityIterations;
const PxI32 bodyListSize = PxI32(params.bodyListSize);
const PxI32 articulationListSize = PxI32(params.articulationListSize);
PX_ASSERT(velocityIterations >= 1);
PX_ASSERT(positionIterations >= 1);
PxI32* constraintIndex = ¶ms.constraintIndex;
PxI32* constraintIndexCompleted = ¶ms.constraintIndexCompleted;
PxI32* frictionConstraintIndex = ¶ms.frictionConstraintIndex;
PxI32 endIndexCount = UnrollCount;
PxI32 index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
PxI32 frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
BatchIterator contactIter(params.constraintBatchHeaders, params.numConstraintHeaders);
BatchIterator frictionIter(params.frictionConstraintBatches, params.numFrictionConstraintHeaders);
PxU32* headersPerPartition = params.headersPerPartition;
PxU32 nbPartitions = params.nbPartitions;
PxU32* frictionHeadersPerPartition = params.frictionHeadersPerPartition;
PxU32 nbFrictionPartitions = params.nbFrictionPartitions;
PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList;
PxSolverConstraintDesc* PX_RESTRICT frictionConstraintList = params.frictionConstraintList;
PxI32 maxNormalIndex = 0;
PxI32 maxProgress = 0;
PxI32 frictionEndIndexCount = UnrollCount;
PxI32 maxFrictionIndex = 0;
PxI32 articSolveStart = 0;
PxI32 articSolveEnd = 0;
PxI32 maxArticIndex = 0;
PxI32 articIndexCounter = 0;
PxI32 targetArticIndex = 0;
PxI32* articIndex = ¶ms.articSolveIndex;
PxI32* articIndexCompleted = ¶ms.articSolveIndexCompleted;
PxI32 normalIteration = 0;
PxI32 frictionIteration = 0;
PxU32 a = 0;
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
for(; a < positionIterations - 1 + i; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, solveTable,
normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize;
++normalIteration;
}
}
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 i = 0; i < 2; ++i)
{
SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlockCoulomb : gVTableSolveConcludeBlockCoulomb;
const PxI32 numIterations = positionIterations *2;
for(; a < numIterations - 1 + i; ++a)
{
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxProgress += frictionHeadersPerPartition[b];
maxFrictionIndex += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
solveTable, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
}
}
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
PxI32* bodyListIndex = ¶ms.bodyListIndex;
PxI32* bodyListIndexCompleted = ¶ms.bodyListIndexCompleted;
PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart;
Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray;
PxI32 endIndexCount2 = SaveUnrollCount;
PxI32 index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
{
PxI32 nbConcluded = 0;
while(index2 < articulationListSize)
{
const PxI32 remainder = PxMin(SaveUnrollCount, (articulationListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
ArticulationPImpl::saveVelocity(articulationListStart[index2].articulation, cache.deltaV);
}
nbConcluded += remainder;
if(endIndexCount2 == 0)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount;
endIndexCount2 = SaveUnrollCount;
}
}
index2 -= articulationListSize;
//save velocity
while(index2 < bodyListSize)
{
const PxI32 remainder = PxMin(endIndexCount2, (bodyListSize - index2));
endIndexCount2 -= remainder;
for(PxI32 b = 0; b < remainder; ++b, ++index2)
{
PxPrefetchLine(&bodyListStart[index2 + 8]);
PxPrefetchLine(&motionVelocityArray[index2 + 8]);
PxSolverBody& body = bodyListStart[index2];
Cm::SpatialVector& motionVel = motionVelocityArray[index2];
motionVel.linear = body.linearVelocity;
motionVel.angular = body.angularState;
PX_ASSERT(motionVel.linear.isFinite());
PX_ASSERT(motionVel.angular.isFinite());
}
nbConcluded += remainder;
//Branch not required because this is the last time we use this atomic variable
//if(index2 < articulationListSizePlusbodyListSize)
{
index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount - articulationListSize;
endIndexCount2 = SaveUnrollCount;
}
}
if(nbConcluded)
{
PxMemoryBarrier();
PxAtomicAdd(bodyListIndexCompleted, nbConcluded);
}
}
WAIT_FOR_PROGRESS(bodyListIndexCompleted, (bodyListSize + articulationListSize));
a = 0;
for(; a < velocityIterations-1; ++a)
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++normalIteration;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter, gVTableSolveBlockCoulomb,
frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, true, isTGS, 0.f, biasCoefficient);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
const PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize;
}
ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream;
const PxU32 thresholdStreamLength = params.thresholdStreamLength;
PxI32* outThresholdPairs = params.outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
// last velocity + write-back iteration
{
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
for(PxU32 b = 0; b < nbPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxNormalIndex += headersPerPartition[b];
maxProgress += headersPerPartition[b];
PxI32 nbSolved = 0;
while(index < maxNormalIndex)
{
const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount);
SolveBlockParallel(constraintList, remainder, index, batchCount,
cache, contactIter, gVTableSolveWriteBackBlockCoulomb, normalIteration);
index += remainder;
endIndexCount -= remainder;
nbSolved += remainder;
if(endIndexCount == 0)
{
endIndexCount = UnrollCount;
index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++normalIteration;
cache.mSharedOutThresholdPairs = outThresholdPairs;
cache.mSharedThresholdStream = thresholdStream;
cache.mSharedThresholdStreamLength = thresholdStreamLength;
for(PxU32 b = 0; b < nbFrictionPartitions; ++b)
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxFrictionIndex += frictionHeadersPerPartition[b];
maxProgress += frictionHeadersPerPartition[b];
PxI32 nbSolved = 0;
while(frictionIndex < maxFrictionIndex)
{
const PxI32 remainder = PxMin(maxFrictionIndex - frictionIndex, frictionEndIndexCount);
SolveBlockParallel(frictionConstraintList, remainder, frictionIndex, frictionBatchCount, cache, frictionIter,
gVTableSolveWriteBackBlockCoulomb, frictionIteration);
frictionIndex += remainder;
frictionEndIndexCount -= remainder;
nbSolved += remainder;
if(frictionEndIndexCount == 0)
{
frictionEndIndexCount = UnrollCount;
frictionIndex = PxAtomicAdd(frictionConstraintIndex, UnrollCount) - UnrollCount;
}
}
if(nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(constraintIndexCompleted, nbSolved);
}
}
++frictionIteration;
{
WAIT_FOR_PROGRESS(constraintIndexCompleted, maxProgress);
maxArticIndex += articulationListSize;
targetArticIndex += articulationListSize;
while (articSolveStart < maxArticIndex)
{
const PxI32 endIdx = PxMin(articSolveEnd, maxArticIndex);
PxI32 nbSolved = 0;
while (articSolveStart < endIdx)
{
articulationListStart[articSolveStart - articIndexCounter].articulation->solveInternalConstraints(dt, invDt, cache.Z, cache.deltaV, false, isTGS, 0.f, biasCoefficient);
articulationListStart[articSolveStart - articIndexCounter].articulation->writebackInternalConstraints(false);
articSolveStart++;
nbSolved++;
}
if (nbSolved)
{
PxMemoryBarrier();
PxAtomicAdd(articIndexCompleted, nbSolved);
}
PxI32 remaining = articSolveEnd - articSolveStart;
if (remaining == 0)
{
articSolveStart = PxAtomicAdd(articIndex, ArticCount) - ArticCount;
articSolveEnd = articSolveStart + ArticCount;
}
}
articIndexCounter += articulationListSize; // not strictly necessary but better safe than sorry
WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex);
}
// At this point we've awaited the completion all rigid partitions and all articulations
// No more syncing on the outside of this function is required.
if(cache.mThresholdStreamIndex > 0)
{
//Write back to global buffer
PxI32 threshIndex = PxAtomicAdd(outThresholdPairs, PxI32(cache.mThresholdStreamIndex)) - PxI32(cache.mThresholdStreamIndex);
for(PxU32 b = 0; b < cache.mThresholdStreamIndex; ++b)
{
thresholdStream[b + threshIndex] = cache.mThresholdStream[b];
}
cache.mThresholdStreamIndex = 0;
}
}
}
}
}
//#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.