file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/PhysX/physx/snippets/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; }
11,775
C++
35.012232
173
0.759745
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
3,005
C++
33.953488
138
0.756739
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; }
6,213
C++
35.339181
151
0.730565
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; }
2,361
C++
39.033898
102
0.778484
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
2,390
C
41.696428
74
0.76569
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(); }
3,658
C++
25.323741
94
0.723619
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
4,411
C
62.942028
236
0.818635
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
1,921
C
50.945945
74
0.767309
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; }
3,409
C++
36.888888
101
0.787914
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; }
2,331
C++
38.525423
105
0.776491
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; }
6,836
C++
32.679803
98
0.597572
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); }
2,164
C++
36.327586
74
0.756007
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
1,955
C
46.707316
74
0.770844
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
2,222
C
43.459999
77
0.772277
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
2,238
C
42.90196
75
0.773012
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
3,310
C
42.565789
81
0.620846
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
1,971
C
43.818181
74
0.764079
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; }
2,822
C++
37.671232
74
0.726435
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); }
16,972
C++
39.315914
367
0.737155
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
2,379
C
42.272727
76
0.765448
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)); } }
14,149
C++
40.374269
278
0.778076
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
4,852
C
36.330769
128
0.771228
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(); }
3,416
C++
27.714285
102
0.734485
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
2,504
C
35.304347
74
0.741214
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
2,100
C
38.641509
74
0.760952
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
6,616
C
35.96648
143
0.797612
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
7,683
C
33.303571
198
0.729793
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
2,767
C
49.327272
103
0.791832
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
2,533
C
35.724637
74
0.744177
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
2,693
C
33.538461
88
0.734497
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
2,799
C
34.443038
81
0.73562
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
17,924
C
50.65706
367
0.767742
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
2,002
C
47.853657
76
0.776723
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
2,498
C
35.217391
74
0.740592
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
5,026
C
33.909722
113
0.729009
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
9,495
C
40.286956
284
0.807056
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); }
95,660
C++
34.104954
243
0.740268
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
5,490
C
21.141129
86
0.684699
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; } } }
4,357
C++
38.261261
93
0.800551
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
6,679
C
38.064327
140
0.76239
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); } } }
66,380
C++
43.136303
185
0.737391
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
13,138
C
33.395288
181
0.752169
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); } } }
36,257
C++
36.887147
150
0.75362
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; } } } }
10,042
C++
32.929054
168
0.723362
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; } } }
21,066
C++
40.799603
153
0.73996
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
4,036
C
38.970297
174
0.777255
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
3,007
C
39.106666
137
0.749584
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
16,271
C
38.115385
195
0.77168
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; } } }
33,521
C++
39.98044
221
0.755407
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
6,417
C
35.885057
125
0.76609
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
3,643
C
34.37864
119
0.763382
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
2,361
C
39.033898
137
0.767471
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
4,400
C
34.208
172
0.784773
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); } } }
47,064
C++
37.736625
150
0.748895
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
2,362
C
35.353846
74
0.754022
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
6,443
C
27.64
144
0.767344
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
5,154
C
39.590551
108
0.794529
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; }
4,574
C++
39.131579
163
0.749016
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
2,899
C
50.785713
180
0.779579
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); } } }
24,180
C++
38.771382
171
0.722498
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 = &params.constraintIndex; PxI32* constraintIndexCompleted = &params.constraintIndexCompleted; PxI32* frictionConstraintIndex = &params.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 = &params.articSolveIndex; PxI32* articIndexCompleted = &params.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 = &params.bodyListIndex; PxI32* bodyListIndexCompleted = &params.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
29,280
C++
35.647059
173
0.762705
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionPatchStreamPair.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_FRICTION_PATCH_STREAM_PAIR_H #define DY_FRICTION_PATCH_STREAM_PAIR_H #include "foundation/PxSimpleTypes.h" #include "PxvConfig.h" #include "foundation/PxMutex.h" #include "foundation/PxArray.h" // Each narrow phase thread has an input stream of friction patches from the // previous frame and an output stream of friction patches which will be // saved for next frame. The patches persist for exactly one frame at which // point they get thrown away. // There is a stream pair per thread. A contact callback reserves space // for its friction patches and gets a cookie in return that can stash // for next frame. Cookies are valid for one frame only. // // note that all friction patches reserved are guaranteed to be contiguous; // this might turn out to be a bit inefficient if we often have a large // number of friction patches #include "PxcNpMemBlockPool.h" namespace physx { class FrictionPatchStreamPair { public: FrictionPatchStreamPair(PxcNpMemBlockPool& blockPool); // reserve can fail and return null. Read should never fail template<class FrictionPatch> FrictionPatch* reserve(const PxU32 size); template<class FrictionPatch> const FrictionPatch* findInputPatches(const PxU8* ptr) const; void reset(); PxcNpMemBlockPool& getBlockPool() { return mBlockPool;} private: PxcNpMemBlockPool& mBlockPool; PxcNpMemBlock* mBlock; PxU32 mUsed; FrictionPatchStreamPair& operator=(const FrictionPatchStreamPair&); }; PX_FORCE_INLINE FrictionPatchStreamPair::FrictionPatchStreamPair(PxcNpMemBlockPool& blockPool): mBlockPool(blockPool), mBlock(NULL), mUsed(0) { } PX_FORCE_INLINE void FrictionPatchStreamPair::reset() { mBlock = NULL; mUsed = 0; } // reserve can fail and return null. Read should never fail template <class FrictionPatch> FrictionPatch* FrictionPatchStreamPair::reserve(const PxU32 size) { if(size>PxcNpMemBlock::SIZE) { return reinterpret_cast<FrictionPatch*>(-1); } PX_ASSERT(size <= PxcNpMemBlock::SIZE); FrictionPatch* ptr = NULL; if(mBlock == NULL || mUsed + size > PxcNpMemBlock::SIZE) { mBlock = mBlockPool.acquireFrictionBlock(); mUsed = 0; } if(mBlock) { ptr = reinterpret_cast<FrictionPatch*>(mBlock->data+mUsed); mUsed += size; } return ptr; } template <class FrictionPatch> const FrictionPatch* FrictionPatchStreamPair::findInputPatches(const PxU8* ptr) const { return reinterpret_cast<const FrictionPatch*>(ptr); } } #endif
4,132
C
31.801587
95
0.762585
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DyFeatherstoneArticulation.h" #include "DyArticulationCpuGpu.h" using namespace physx; using namespace Gu; #include "PxsMaterialManager.h" #include "DyContactPrepShared.h" #include "DyConstraintPrep.h" #include "DySolverContext.h" #include "DySolverConstraint1DStep.h" #include "DyTGS.h" using namespace aos; namespace physx { namespace Dy { PX_FORCE_INLINE void computeBlockStreamByteSizesStep(const bool useExtContacts, const CorrelationBuffer& c, PxU32& _solverConstraintByteSize, PxU32& _frictionPatchByteSize, PxU32& _numFrictionPatches, PxU32& _axisConstraintCount, PxReal torsionalPatchRadius) { 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(SolverContactHeaderStep); solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointStepExt) : c.frictionPatchContactCounts[i] * sizeof(SolverContactPointStep); solverConstraintByteSize += sizeof(PxF32) * ((c.frictionPatchContactCounts[i] + 3)&(~3)); //Add on space for applied impulses axisConstraintCount += c.frictionPatchContactCounts[i]; if (haveFriction) { PxU32 nbAnchors = PxU32(c.frictionPatches[i].anchorCount * 2); if (torsionalPatchRadius > 0.f && c.frictionPatches[i].anchorCount == 1) nbAnchors++; solverConstraintByteSize += useExtContacts ? nbAnchors * sizeof(SolverContactFrictionStepExt) : nbAnchors * sizeof(SolverContactFrictionStep); axisConstraintCount += nbAnchors; } } } 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, PxReal torsionalPatchRadius) { 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. computeBlockStreamByteSizesStep( useExtContacts, cBuffer, solverConstraintByteSize, frictionPatchByteSize, numFrictionPatches, axisConstraintCount, torsionalPatchRadius); //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)); } class SolverExtBodyStep { public: union { const FeatherstoneArticulation* mArticulation; const PxTGSSolverBodyVel* mBody; }; const PxTGSSolverBodyTxInertia* mTxI; const PxTGSSolverBodyData* mData; PxU32 mLinkIndex; SolverExtBodyStep(const void* bodyOrArticulation, const PxTGSSolverBodyTxInertia* txI, const PxTGSSolverBodyData* data, PxU32 linkIndex) : mBody(reinterpret_cast<const PxTGSSolverBodyVel*>(bodyOrArticulation)), mTxI(txI), mData(data), mLinkIndex(linkIndex) {} PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const; PxVec3 getLinVel() const; PxVec3 getAngVel() const; Cm::SpatialVectorV getVelocity() const; bool isKinematic() const { return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) && mBody->isKinematic; } PxReal getCFM() const { return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) ? 0.f : mArticulation->getCfm(mLinkIndex); } }; Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBodyStep& body) { if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return Cm::SpatialVector(linear, body.mTxI->sqrtInvInertia * angular); return Cm::SpatialVector(linear, angular); } Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBodyStep& body) { if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { return Cm::SpatialVectorV(linear, M33MulV3(M33Load(body.mTxI->sqrtInvInertia), angular)); } return Cm::SpatialVectorV(linear, angular); } PxReal getImpulseResponse(const SolverExtBodyStep& b0, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxReal dom0, PxReal angDom0, const SolverExtBodyStep& b1, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal dom1, PxReal angDom1, bool allowSelfCollision) { PxReal response; if (allowSelfCollision && b0.mArticulation == b1.mArticulation) { Cm::SpatialVectorF Z[64]; b0.mArticulation->getImpulseSelfResponse(b0.mLinkIndex, b1.mLinkIndex, Z, impulse0.scale(dom0, angDom0), impulse1.scale(dom1, angDom1), deltaV0, deltaV1); response = impulse0.dot(deltaV0) + impulse1.dot(deltaV1); } else { if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV0.linear = impulse0.linear * b0.mData->invMass * dom0; deltaV0.angular =/* b0.mBody->sqrtInvInertia * */impulse0.angular * angDom0; } else { //ArticulationHelper::getImpulseResponse(*b0.mFsData, b0.mLinkIndex, impulse0.scale(dom0, angDom0), deltaV0); const FeatherstoneArticulation* articulation = b0.mArticulation; Cm::SpatialVectorF Z[64]; articulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0); } response = impulse0.dot(deltaV0); if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV1.linear = impulse1.linear * b1.mData->invMass * dom1; deltaV1.angular = /*b1.mBody->sqrtInvInertia * */impulse1.angular * angDom1; } else { const FeatherstoneArticulation* articulation = b1.mArticulation; Cm::SpatialVectorF Z[64]; articulation->getImpulseResponse(b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1); //ArticulationHelper::getImpulseResponse(*b1.mFsData, b1.mLinkIndex, impulse1.scale(dom1, angDom1), deltaV1); } response += impulse1.dot(deltaV1); } return response; } FloatV getImpulseResponse(const SolverExtBodyStep& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const FloatV& dom0, const FloatV& angDom0, const SolverExtBodyStep& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const FloatV& dom1, const FloatV& angDom1, bool /*allowSelfCollision*/) { Vec3V response; { if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV0.linear = V3Scale(impulse0.linear, FMul(FLoad(b0.mData->invMass), dom0)); deltaV0.angular = V3Scale(impulse0.angular, angDom0); } else { b0.mArticulation->getImpulseResponse(b0.mLinkIndex, NULL, impulse0.scale(dom0, angDom0), deltaV0); } response = V3Add(V3Mul(impulse0.linear, deltaV0.linear), V3Mul(impulse0.angular, deltaV0.angular)); if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV1.linear = V3Scale(impulse1.linear, FMul(FLoad(b1.mData->invMass), dom1)); deltaV1.angular = V3Scale(impulse1.angular, angDom1); } else { b1.mArticulation->getImpulseResponse(b1.mLinkIndex, NULL, impulse1.scale(dom1, angDom1), deltaV1); } response = V3Add(response, V3Add(V3Mul(impulse1.linear, deltaV1.linear), V3Mul(impulse1.angular, deltaV1.angular))); } return V3SumElems(response); } PxReal SolverExtBodyStep::projectVelocity(const PxVec3& linear, const PxVec3& angular) const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return mData->projectVelocity(linear, angular); else { Cm::SpatialVectorV velocities = mArticulation->getLinkVelocity(mLinkIndex); FloatV fv = velocities.dot(Cm::SpatialVector(linear, angular)); PxF32 f; FStore(fv, &f); /*PxF32 f; FStore(getVelocity(*mFsData)[mLinkIndex].dot(Cm::SpatialVector(linear, angular)), &f); return f;*/ return f; } } static FloatV constructContactConstraintStep(const Mat33V& sqrtInvInertia0, const Mat33V& sqrtInvInertia1, const FloatVArg invMassNorLenSq0, const FloatVArg invMassNorLenSq1, const FloatVArg angD0, const FloatVArg angD1, const Vec3VArg bodyFrame0p, const Vec3VArg bodyFrame1p, const QuatV& /*bodyFrame0q*/, const QuatV& /*bodyFrame1q*/, const Vec3VArg normal, const FloatVArg norVel0, const FloatVArg norVel1, const VecCrossV& norCross, const Vec3VArg angVel0, const Vec3VArg angVel1, const FloatVArg invDtp8, const FloatVArg invStepDt, const FloatVArg totalDt, const FloatVArg invTotalDt, const FloatVArg restDistance, const FloatVArg restitution, const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointStep& solverContact, const FloatVArg /*ccdMaxSeparation*/, const bool isKinematic0, const bool isKinematic1, const Vec3VArg solverOffsetSlop, const FloatVArg dt, const FloatVArg damping) { const FloatV zero = FZero(); const Vec3V point = V3LoadA(contact.point); const FloatV separation = FLoad(contact.separation); const FloatV cTargetVel = V3Dot(normal, V3LoadA(contact.targetVel)); const Vec3V ra = V3Sub(point, bodyFrame0p); const Vec3V rb = V3Sub(point, bodyFrame1p); Vec3V raXn = V3Cross(ra, norCross); Vec3V rbXn = V3Cross(rb, norCross); const FloatV angV0 = V3Dot(raXn, angVel0); const FloatV angV1 = V3Dot(rbXn, angVel1); const FloatV vRelAng = FSub(angV0, angV1); const FloatV vRelLin = FSub(norVel0, norVel1); const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(vRelLin,zero), FMax(), FDiv(vRelAng, vRelLin)), FOne())); const FloatV vrel1 = FAdd(norVel0, angV0); const FloatV vrel2 = FAdd(norVel1, angV1); const FloatV vrel = FSub(vrel1, vrel2); raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn); const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn); const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn); const FloatV i0 = FMul(V3Dot(raXnInertia, raXnInertia), angD0); const FloatV i1 = FMul(V3Dot(rbXnInertia, rbXnInertia), angD1); const FloatV resp0 = FAdd(invMassNorLenSq0, i0); const FloatV resp1 = FSub(i1, invMassNorLenSq1); const FloatV unitResponse = FAdd(resp0, resp1); const FloatV penetration = FSub(separation, restDistance); const BoolV isSeparated = FIsGrtr(penetration, zero); const FloatV penetrationInvDt = FMul(penetration, invTotalDt); const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt)); //The following line was replaced by an equivalent to avoid triggering an assert when FAdd sums totalDt to infinity which happens if vrel==0 //const FloatV ratio = FSel(isGreater2, FAdd(totalDt, FDiv(penetration, vrel)), zero); const FloatV ratio = FAdd(totalDt, FSel(isGreater2, FDiv(penetration, vrel), FNeg(totalDt))); FloatV scaledBias; FloatV velMultiplier; FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(unitResponse), FZero()); if (FAllGrtr(zero, restitution)) { //-ve restitution, so we treat it as a -spring coefficient. const FloatV nrdt = FMul(dt, restitution); const FloatV a = FMul(dt, FSub(damping, nrdt)); const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne())); velMultiplier = FMul(x, a); //scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier)); scaledBias = FMul(nrdt, FMul(x, unitResponse)); } else { scaledBias = FNeg(FSel(isSeparated, invStepDt, invDtp8)); velMultiplier = recipResponse; } FloatV totalError = penetration; const FloatV sumVRel(vrel); FloatV targetVelocity = FAdd(cTargetVel, FSel(isGreater2, FMul(FNeg(sumVRel), restitution), zero)); totalError = FScaleAdd(targetVelocity, ratio, totalError); if(isKinematic0) targetVelocity = FSub(targetVelocity, vrel1); if(isKinematic1) targetVelocity = FAdd(targetVelocity, vrel2); //KS - don't store scaled by angD0/angD1 here! It'll corrupt the velocity projection... V3StoreA(raXnInertia, solverContact.raXnI); V3StoreA(rbXnInertia, solverContact.rbXnI); FStore(velMultiplier, &solverContact.velMultiplier); FStore(totalError, &solverContact.separation); FStore(scaledBias, &solverContact.biasCoefficient); FStore(targetVelocity, &solverContact.targetVelocity); FStore(recipResponse, &solverContact.recipResponse); solverContact.maxImpulse = contact.maxImpulse; return penetration; } static void setupFinalizeSolverConstraints(Sc::ShapeInteraction* shapeInteraction, const PxContactPoint* buffer, const CorrelationBuffer& c, const PxTransform& bodyFrame0, const PxTransform& bodyFrame1, PxU8* workspace, const PxTGSSolverBodyVel& b0, const PxTGSSolverBodyVel& b1, const PxTGSSolverBodyTxInertia& txI0, const PxTGSSolverBodyTxInertia& txI1, const PxTGSSolverBodyData& data0, const PxTGSSolverBodyData& data1, const PxReal invDtF32, const PxReal totalDtF32, const PxReal invTotalDtF32, 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 bool disableStrongFriction, const PxReal torsionalPatchRadiusF32, const PxReal minTorsionalPatchRadiusF32, const PxReal biasCoefficient, const PxReal solverOffsetSlop) { const bool hasTorsionalFriction = torsionalPatchRadiusF32 > 0.f || minTorsionalPatchRadiusF32 > 0.f; // 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 bool isKinematic0 = b0.isKinematic; const bool isKinematic1 = b1.isKinematic; const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation); const PxU8 flags = PxU8(hasForceThreshold ? SolverContactHeaderStep::eHAS_FORCE_THRESHOLDS : 0); PxU8* PX_RESTRICT ptr = workspace; const PxU8 type = PxTo8(staticOrKinematicBody ? DY_SC_TYPE_STATIC_CONTACT : DY_SC_TYPE_RB_CONTACT); const FloatV zero = FZero(); const FloatV d0 = FLoad(invMassScale0); const FloatV d1 = FLoad(invMassScale1); const FloatV angD0 = FLoad(invInertiaScale0); const FloatV angD1 = FLoad(invInertiaScale1); const Vec3V offsetSlop = V3Load(solverOffsetSlop); 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 PxReal maxPenBias = PxMax(data0.penBiasClamp, 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(b0.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData //const Vec3V linVel1 = V3LoadU_SafeReadW(b1.linearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData //const Vec3V angVel0 = V3LoadU_SafeReadW(b0.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData //const Vec3V angVel1 = V3LoadU_SafeReadW(b1.angularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData const Vec3V linVel0 = V3LoadU_SafeReadW(data0.originalLinearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData const Vec3V linVel1 = V3LoadU_SafeReadW(data1.originalLinearVelocity); // PT: safe because 'invMass' follows 'initialLinVel' in PxSolverBodyData const Vec3V angVel0 = V3LoadU_SafeReadW(data0.originalAngularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData const Vec3V angVel1 = V3LoadU_SafeReadW(data1.originalAngularVelocity); // PT: safe because 'reportThreshold' follows 'initialAngVel' in PxSolverBodyData PX_ALIGN(16, const Mat33V sqrtInvInertia0) ( V3LoadU_SafeReadW(txI0.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33 V3LoadU_SafeReadW(txI0.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33 V3LoadU(txI0.sqrtInvInertia.column2) ); PX_ALIGN(16, const Mat33V sqrtInvInertia1) ( V3LoadU_SafeReadW(txI1.sqrtInvInertia.column0), // PT: safe because 'column1' follows 'column0' in PxMat33 V3LoadU_SafeReadW(txI1.sqrtInvInertia.column1), // PT: safe because 'column2' follows 'column1' in PxMat33 V3LoadU(txI1.sqrtInvInertia.column2) ); const FloatV invDt = FLoad(invDtF32); const FloatV dt = FLoad(dtF32); const FloatV totalDt = FLoad(totalDtF32); const FloatV invTotalDt = FLoad(invTotalDtF32); const PxReal scale = PxMin(0.8f, biasCoefficient); const FloatV p8 = FLoad(scale); const FloatV bounceThreshold = FLoad(bounceThresholdF32); const FloatV invDtp8 = FMul(invDt, p8); const PxReal frictionBiasScale = disableStrongFriction ? 0.f : invDtF32 * scale; 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; const PxReal combinedRestitution = contactBase0->restitution; const PxReal combinedDamping = contactBase0->damping; SolverContactHeaderStep* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStep*>(ptr); ptr += sizeof(SolverContactHeaderStep); PxPrefetchLine(ptr, 128); PxPrefetchLine(ptr, 256); header->shapeInteraction = shapeInteraction; header->flags = flags; header->minNormalForce = 0.f; FStore(invMass0_dom0fV, &header->invMass0); FStore(FNeg(invMass1_dom1fV), &header->invMass1); const FloatV restitution = FLoad(combinedRestitution); const FloatV damping = FLoad(combinedDamping); PxU32 pointStride = sizeof(SolverContactPointStep); PxU32 frictionStride = sizeof(SolverContactFrictionStep); 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 norVel0 = V3Dot(linVel0, normal); const FloatV norVel1 = V3Dot(linVel1, normal); const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq); const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq); V3StoreA(normal, header->normal); header->maxPenBias = contactBase0->restitution < 0.f ? -PX_MAX_F32 : maxPenBias; FloatV maxPenetration = FMax(); 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]; SolverContactPointStep* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStep*>(p); p += pointStride; maxPenetration = FMin(maxPenetration, constructContactConstraintStep(sqrtInvInertia0, sqrtInvInertia1, invMassNorLenSq0, invMassNorLenSq1, angD0, angD1, bodyFrame0p, bodyFrame1p, bodyFrame0q, bodyFrame1q, normal, norVel0, norVel1, norCross, angVel0, angVel1, invDtp8, invDt, totalDt, invTotalDt, restDistance, restitution, bounceThreshold, contact, *solverContact, ccdMaxSeparation, isKinematic0, isKinematic1, offsetSlop, dt, 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 staticFriction = contactBase0->staticFriction; const PxReal dynamicFriction = contactBase0->dynamicFriction; const bool disableFriction = !!(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 = (disableFriction == 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 = V3Normalize(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); const FloatV norVel00 = V3Dot(linVel0, t0); const FloatV norVel01 = V3Dot(linVel1, t0); const FloatV norVel10 = V3Dot(linVel0, t1); const FloatV norVel11 = V3Dot(linVel1, t1); const Vec3V relTr = V3Sub(bodyFrame0p, bodyFrame1p); header->frictionBrokenWritebackByte = writeback; PxReal frictionScale = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f; for (PxU32 j = 0; j < frictionPatch.anchorCount; j++) { PxPrefetchLine(ptr, 256); PxPrefetchLine(ptr, 384); SolverContactFrictionStep* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStep*>(ptr); ptr += frictionStride; SolverContactFrictionStep* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStep*>(ptr); ptr += frictionStride; Vec3V body0Anchor = V3LoadU(frictionPatch.body0Anchors[j]); Vec3V body1Anchor = V3LoadU(frictionPatch.body1Anchors[j]); Vec3V ra = QuatRotate(bodyFrame0q, body0Anchor); Vec3V rb = QuatRotate(bodyFrame1q, body1Anchor); PxU32 index = c.contactID[i][j]; index = index == 0xFFFF ? c.contactPatches[c.correlationListHeads[i]].start : index; const Vec3V tvel = V3LoadA(buffer[index].targetVel); const Vec3V error = V3Add(V3Sub(ra, rb), relTr); { Vec3V raXn = V3Cross(ra, t0); Vec3V rbXn = V3Cross(rb, t0); raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn); const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn); const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn); const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnInertia, raXnInertia), angD0)); const FloatV resp1 = FSub(FMul(V3Dot(rbXnInertia, rbXnInertia), angD1), invMassNorLenSq1); const FloatV unitResponse = FAdd(resp0, resp1); const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero); //const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero); FloatV targetVel = V3Dot(tvel, t0); if(isKinematic0) targetVel = FSub(targetVel, FAdd(norVel00, V3Dot(raXn, angVel0))); if (isKinematic1) targetVel = FAdd(targetVel, FAdd(norVel01, V3Dot(rbXn, angVel1))); f0->normalXYZ_ErrorW = V4SetW(t0, V3Dot(error, t0)); //f0->raXnXYZ_targetVelW = V4SetW(body0Anchor, targetVel); //f0->rbXnXYZ_biasW = V4SetW(body1Anchor, FZero()); /*f0->raXn_biasScaleW = V4SetW(Vec4V_From_Vec3V(raXn), frictionBiasScale); f0->rbXn_errorW = V4SetW(rbXn, V3Dot(error, t0));*/ f0->raXnI_targetVelW = V4SetW(raXnInertia, targetVel); f0->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier); f0->appliedForce = 0.f; f0->frictionScale = frictionScale; f0->biasScale = frictionBiasScale; } { FloatV targetVel = V3Dot(tvel, t1); Vec3V raXn = V3Cross(ra, t1); Vec3V rbXn = V3Cross(rb, t1); raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn); const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, raXn); const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, rbXn); const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnInertia, raXnInertia), angD0)); const FloatV resp1 = FSub(FMul(V3Dot(rbXnInertia, rbXnInertia), angD1), invMassNorLenSq1); const FloatV unitResponse = FAdd(resp0, resp1); const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero); //const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero); if (isKinematic0) targetVel = FSub(targetVel, FAdd(norVel10, V3Dot(raXn, angVel0))); if (isKinematic1) targetVel = FAdd(targetVel, FAdd(norVel11, V3Dot(rbXn, angVel1))); f1->normalXYZ_ErrorW = V4SetW(t1, V3Dot(error, t1)); //f1->raXnXYZ_targetVelW = V4SetW(body0Anchor, targetVel); //f1->rbXnXYZ_biasW = V4SetW(body1Anchor, FZero()); //f1->raXn_biasScaleW = V4SetW(Vec4V_From_Vec3V(V3Cross(ra, t1)), frictionBiasScale); //f1->rbXn_errorW = V4SetW(V3Cross(rb, t1), V3Dot(error, t1)); f1->raXnI_targetVelW = V4SetW(raXnInertia, targetVel); f1->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier); f1->appliedForce = 0.f; f1->frictionScale = frictionScale; f1->biasScale = frictionBiasScale; } } if (hasTorsionalFriction && frictionPatch.anchorCount == 1) { const FloatV torsionalPatchRadius = FLoad(torsionalPatchRadiusF32); const FloatV minTorsionalPatchRadius = FLoad(minTorsionalPatchRadiusF32); const FloatV torsionalFriction = FMax(minTorsionalPatchRadius, FSqrt(FMul(FMax(zero, FNeg(maxPenetration)), torsionalPatchRadius))); header->numFrictionConstr++; SolverContactFrictionStep* PX_RESTRICT f = reinterpret_cast<SolverContactFrictionStep*>(ptr); ptr += frictionStride; const Vec3V raXnInertia = M33MulV3(sqrtInvInertia0, normal); const Vec3V rbXnInertia = M33MulV3(sqrtInvInertia1, normal); const FloatV resp0 = FMul(V3Dot(raXnInertia, raXnInertia), angD0); const FloatV resp1 = FMul(V3Dot(rbXnInertia, rbXnInertia), angD1); const FloatV unitResponse = FAdd(resp0, resp1); const FloatV velMultiplier = FSel(FIsGrtr(unitResponse, zero), FDiv(p8, unitResponse), zero); FloatV targetVel = zero; if (isKinematic0) targetVel = V3Dot(normal, angVel0); if (isKinematic1) targetVel = V3Dot(normal, angVel1); f->normalXYZ_ErrorW = V4Zero(); f->raXnI_targetVelW = V4SetW(raXnInertia, targetVel); f->rbXnI_velMultiplierW = V4SetW(rbXnInertia, velMultiplier); f->biasScale = 0.f; f->appliedForce = 0.f; FStore(torsionalFriction, &f->frictionScale); } } frictionPatchWritebackAddrIndex++; } } static FloatV setupExtSolverContactStep(const SolverExtBodyStep& b0, const SolverExtBodyStep& 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 invStepDt, const FloatVArg totalDt, const FloatVArg dt, const FloatVArg restDistance, const FloatVArg restitution, const FloatVArg damping, const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPointStepExt& solverContact, const FloatVArg /*ccdMaxSeparation*/, const bool isKinematic0, const bool isKinematic1, const FloatVArg cfm, const Cm::SpatialVectorV& v0, const Cm::SpatialVectorV& v1, const Vec3VArg solverOffsetSlop, const FloatVArg norVel0, const FloatVArg norVel1) { const FloatV zero = FZero(); const FloatV separation = FLoad(contact.separation); FloatV penetration = FSub(separation, restDistance); const Vec3V ra = V3Sub(V3LoadA(contact.point),bodyFrame0p); const Vec3V rb = V3Sub(V3LoadA(contact.point), bodyFrame1p); Vec3V raXn = V3Cross(ra, normal); Vec3V rbXn = V3Cross(rb, normal); Cm::SpatialVectorV deltaV0, deltaV1; const FloatV vRelAng = V3SumElems(V3Sub(V3Mul(v0.angular, raXn), V3Mul(v1.angular, rbXn))); const FloatV vRelLin = FSub(norVel0, norVel1); const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(vRelLin, zero), FOne(), FDiv(vRelAng, vRelLin)), FOne())); raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn); const FloatV angV0 = V3Dot(v0.angular, raXn); const FloatV angV1 = V3Dot(v1.angular, rbXn); const Cm::SpatialVectorV resp0 = createImpulseResponseVector(normal, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(normal), V3Neg(rbXn), b1); FloatV unitResponse = getImpulseResponse( b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, false); const FloatV vrel = FAdd(vRelAng, vRelLin); FloatV scaledBias, velMultiplier; FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(FAdd(unitResponse, cfm)), zero); if (FAllGrtr(zero, restitution)) { const FloatV nrdt = FMul(dt, restitution); const FloatV a = FMul(dt, FSub(damping, nrdt)); const FloatV x = FRecip(FScaleAdd(a, unitResponse, FOne())); velMultiplier = FMul(x, a); //scaledBias = FSel(isSeparated, FNeg(invStepDt), FDiv(FMul(nrdt, FMul(x, unitResponse)), velMultiplier)); scaledBias = FMul(nrdt, FMul(x, unitResponse)); } else { velMultiplier = recipResponse; scaledBias = FNeg(FSel(FIsGrtr(penetration, zero), invStepDt, invDtp8)); } const FloatV penetrationInvDt = FMul(penetration, invDt); const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt)); FloatV targetVelocity = FSel(isGreater2, FMul(FNeg(vrel), restitution), zero); const FloatV cTargetVel = V3Dot(V3LoadA(contact.targetVel), normal); targetVelocity = FAdd(targetVelocity, cTargetVel); //const FloatV deltaF = FMax(FMul(FSub(targetVelocity, FAdd(vrel, FMax(zero, penetrationInvDt))), velMultiplier), zero); const FloatV deltaF = FMax(FMul(FAdd(targetVelocity, FSub(FNeg(penetrationInvDt), vrel)), velMultiplier), zero); const FloatV ratio = FSel(isGreater2, FAdd(totalDt, FDiv(penetration, vrel)), zero); penetration = FScaleAdd(targetVelocity, ratio, penetration); if (isKinematic0) targetVelocity = FSub(targetVelocity, FAdd(norVel0, angV0)); if(isKinematic1) targetVelocity = FAdd(targetVelocity, FAdd(norVel1, angV1)); FStore(scaledBias, &solverContact.biasCoefficient); FStore(targetVelocity, &solverContact.targetVelocity); FStore(recipResponse, &solverContact.recipResponse); const Vec4V raXnI_Sepw = V4SetW(Vec4V_From_Vec3V(resp0.angular), penetration); const Vec4V rbXnI_velMulW = V4SetW(Vec4V_From_Vec3V(V3Neg(resp1.angular)), velMultiplier); //solverContact.raXnI = resp0.angular; //solverContact.rbXnI = -resp1.angular; V4StoreA(raXnI_Sepw, &solverContact.raXnI.x); V4StoreA(rbXnI_velMulW, &solverContact.rbXnI.x); solverContact.linDeltaVA = deltaV0.linear; solverContact.angDeltaVA = deltaV0.angular; solverContact.linDeltaVB = deltaV1.linear; solverContact.angDeltaVB = deltaV1.angular; solverContact.maxImpulse = contact.maxImpulse; return deltaF; } //PX_INLINE void computeFrictionTangents(const PxVec3& vrel, const PxVec3& unitNormal, PxVec3& t0, PxVec3& t1) //{ // PX_ASSERT(PxAbs(unitNormal.magnitude() - 1)<1e-3f); // t0 = vrel - unitNormal * unitNormal.dot(vrel); // PxReal ll = t0.magnitudeSquared(); // if (ll > 0.1f) //can set as low as 0. // { // t0 *= PxRecipSqrt(ll); // t1 = unitNormal.cross(t0); // } // else // PxNormalToTangents(unitNormal, t0, t1); //fallback //} PxVec3 SolverExtBodyStep::getLinVel() const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return mBody->linearVelocity; else { Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex); PxVec3 result; V3StoreU(velocity.linear, result); return result; } } Cm::SpatialVectorV SolverExtBodyStep::getVelocity() const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return Cm::SpatialVectorV(V3LoadA(mData->originalLinearVelocity), V3LoadA(mData->originalAngularVelocity)); else return mArticulation->getLinkVelocity(mLinkIndex); } void setupFinalizeExtSolverContactsStep( const PxContactPoint* buffer, const CorrelationBuffer& c, const PxTransform& bodyFrame0, const PxTransform& bodyFrame1, PxU8* workspace, const SolverExtBodyStep& b0, const SolverExtBodyStep& b1, const PxReal invDtF32, const PxReal invTotalDtF32, const PxReal totalDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal invMassScale0, PxReal invInertiaScale0, PxReal invMassScale1, PxReal invInertiaScale1, const PxReal restDist, PxU8* frictionDataPtr, PxReal ccdMaxContactDist, const PxReal torsionalPatchRadiusF32, const PxReal minTorsionalPatchRadiusF32, const PxReal biasCoefficient, const PxReal solverOffsetSlop) { // 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 bool haveFriction = PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;*/ const bool isKinematic0 = b0.isKinematic(); const bool isKinematic1 = b1.isKinematic(); const FloatV ccdMaxSeparation = FLoad(ccdMaxContactDist); bool hasTorsionalFriction = torsionalPatchRadiusF32 > 0.f || minTorsionalPatchRadiusF32 > 0.f; const FloatV quarter = FLoad(0.25f); PxU8* PX_RESTRICT ptr = workspace; const FloatV zero = FZero(); const PxF32 maxPenBias0 = b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY ? b0.mData->penBiasClamp : b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex); const PxF32 maxPenBias1 = b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY ? b1.mData->penBiasClamp : b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex); const PxReal maxPenBias = PxMax(maxPenBias0, maxPenBias1); const Cm::SpatialVectorV v0 = b0.getVelocity(); const Cm::SpatialVectorV v1 = b1.getVelocity(); const FloatV d0 = FLoad(invMassScale0); const FloatV d1 = FLoad(invMassScale1); const FloatV angD0 = FLoad(invInertiaScale0); const FloatV angD1 = FLoad(invInertiaScale1); const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p); const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p); Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero(); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d0); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d1); const FloatV restDistance = FLoad(restDist); PxU32 frictionPatchWritebackAddrIndex = 0; PxPrefetchLine(c.contactID); PxPrefetchLine(c.contactID, 128); const FloatV invDt = FLoad(invDtF32); const FloatV invTotalDt = FLoad(invTotalDtF32); const PxReal scale = PxMin(0.8f, biasCoefficient); const FloatV p8 = FLoad(scale); const FloatV bounceThreshold = FLoad(bounceThresholdF32); const FloatV totalDt = FLoad(totalDtF32); const FloatV dt = FLoad(dtF32); const FloatV invDtp8 = FMul(invDt, p8); const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM())); PxU8 flags = 0; const Vec3V offsetSlop = V3Load(solverOffsetSlop); 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); //0==anchorCount is allowed if all the contacts in the manifold have a large offset. const PxContactPoint* contactBase0 = buffer + c.contactPatches[c.correlationListHeads[i]].start; const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(contactBase0->staticFriction)); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4SetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, FLoad(contactBase0->dynamicFriction)); const PxReal frictionBiasScale = disableStrongFriction ? 0.f : invDtF32 * 0.8f; SolverContactHeaderStep* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStep*>(ptr); ptr += sizeof(SolverContactHeaderStep); PxPrefetchLine(ptr + 128); PxPrefetchLine(ptr + 256); PxPrefetchLine(ptr + 384); const bool haveFriction = (disableStrongFriction == 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 = PxTo8(DY_SC_TYPE_EXT_CONTACT); header->flags = flags; const FloatV restitution = FLoad(contactBase0->restitution); const FloatV damping = FLoad(contactBase0->damping); header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W; header->angDom0 = invInertiaScale0; header->angDom1 = invInertiaScale1; const PxU32 pointStride = sizeof(SolverContactPointStepExt); const PxU32 frictionStride = sizeof(SolverContactFrictionStepExt); const Vec3V normal = V3LoadU(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal); V3StoreA(normal, header->normal); header->maxPenBias = maxPenBias; FloatV maxPenetration = FZero(); FloatV accumulatedImpulse = FZero(); const FloatV norVel0 = V3Dot(v0.linear, normal); const FloatV norVel1 = V3Dot(v1.linear, 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++) { const PxContactPoint& contact = contactBase[j]; SolverContactPointStepExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStepExt*>(p); p += pointStride; accumulatedImpulse = FAdd(accumulatedImpulse, setupExtSolverContactStep(b0, b1, d0, d1, angD0, angD1, bodyFrame0p, bodyFrame1p, normal, invTotalDt, invDtp8, invDt, totalDt, dt, restDistance, restitution, damping, bounceThreshold, contact, *solverContact, ccdMaxSeparation, isKinematic0, isKinematic1, cfm, v0, v1, offsetSlop, norVel0, norVel1)); maxPenetration = FMin(FLoad(contact.separation), maxPenetration); } ptr = p; } accumulatedImpulse = FMul(FDiv(accumulatedImpulse, FLoad(PxF32(contactCount))), quarter); FStore(accumulatedImpulse, &header->minNormalForce); PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr); PxMemZero(forceBuffer, sizeof(PxF32) * contactCount); ptr += sizeof(PxF32) * ((contactCount + 3) & (~3)); header->broken = 0; if (haveFriction) { //const Vec3V normal = Vec3V_From_PxVec3(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal); const Vec3V linVrel = V3Sub(v0.linear, v1.linear); //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(normal, t0Cross); const VecCrossV t1Cross = V3PrepareCross(t1); //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; PxReal frictionScale = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f; for (PxU32 j = 0; j < frictionPatch.anchorCount; j++) { SolverContactFrictionStepExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStepExt*>(ptr); ptr += frictionStride; SolverContactFrictionStepExt* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStepExt*>(ptr); ptr += frictionStride; Vec3V ra = V3LoadU(bodyFrame0.q.rotate(frictionPatch.body0Anchors[j])); Vec3V rb = V3LoadU(bodyFrame1.q.rotate(frictionPatch.body1Anchors[j])); Vec3V error = V3Sub(V3Add(ra, bodyFrame0p), V3Add(rb,bodyFrame1p)); { Vec3V raXn = V3Cross(ra, t0Cross); Vec3V rbXn = V3Cross(rb, t0Cross); raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn); Cm::SpatialVectorV deltaV0, deltaV1; const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1); FloatV resp = getImpulseResponse(b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, false); const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero); PxU32 index = c.contactPatches[c.correlationListHeads[i]].start; FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t0); if(isKinematic0) targetVel = FSub(targetVel, v0.dot(resp0)); if(isKinematic1) targetVel = FSub(targetVel, v1.dot(resp1)); f0->normalXYZ_ErrorW = V4SetW(Vec4V_From_Vec3V(t0), V3Dot(error, t0)); f0->raXnI_targetVelW = V4SetW(Vec4V_From_Vec3V(resp0.angular), targetVel); f0->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), velMultiplier); f0->appliedForce = 0.f; f0->biasScale = frictionBiasScale; f0->linDeltaVA = deltaV0.linear; f0->linDeltaVB = deltaV1.linear; f0->angDeltaVA = deltaV0.angular; f0->angDeltaVB = deltaV1.angular; f0->frictionScale = frictionScale; } { Vec3V raXn = V3Cross(ra, t1Cross); Vec3V rbXn = V3Cross(rb, t1Cross); raXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(offsetSlop, V3Abs(rbXn)), V3Zero(), rbXn); Cm::SpatialVectorV deltaV0, deltaV1; const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t1, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t1), V3Neg(rbXn), b1); FloatV resp = getImpulseResponse(b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, false); const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero); PxU32 index = c.contactPatches[c.correlationListHeads[i]].start; FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t1); if (isKinematic0) targetVel = FSub(targetVel, v0.dot(resp0)); if (isKinematic1) targetVel = FSub(targetVel, v1.dot(resp1)); f1->normalXYZ_ErrorW = V4SetW(Vec4V_From_Vec3V(t1), V3Dot(error, t1)); f1->raXnI_targetVelW = V4SetW(Vec4V_From_Vec3V(resp0.angular), targetVel); f1->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), velMultiplier); f1->appliedForce = 0.f; f1->biasScale = frictionBiasScale; f1->linDeltaVA = deltaV0.linear; f1->linDeltaVB = deltaV1.linear; f1->angDeltaVA = deltaV0.angular; f1->angDeltaVB = deltaV1.angular; f1->frictionScale = frictionScale; } } if (hasTorsionalFriction && frictionPatch.anchorCount == 1) { const FloatV torsionalPatchRadius = FLoad(torsionalPatchRadiusF32); const FloatV minTorsionalPatchRadius = FLoad(minTorsionalPatchRadiusF32); const FloatV torsionalFriction = FMax(minTorsionalPatchRadius, FSqrt(FMul(FMax(zero, FNeg(maxPenetration)), torsionalPatchRadius))); header->numFrictionConstr++; SolverContactFrictionStepExt* PX_RESTRICT f = reinterpret_cast<SolverContactFrictionStepExt*>(ptr); ptr += frictionStride; const Cm::SpatialVector resp0 = createImpulseResponseVector(PxVec3(0.f), header->normal, b0); const Cm::SpatialVector resp1 = createImpulseResponseVector(PxVec3(0.f), -header->normal, b1); Cm::SpatialVector deltaV0, deltaV1; PxReal ur = getImpulseResponse(b0, resp0, deltaV0, invMassScale0, invInertiaScale0, b1, resp1, deltaV1, invMassScale1, invInertiaScale1, false); FloatV resp = FLoad(ur); const FloatV velMultiplier = FSel(FIsGrtr(resp, FEps()), FDiv(p8, FAdd(cfm, resp)), zero); f->normalXYZ_ErrorW = V4Zero(); f->raXnI_targetVelW = V4SetW(V3LoadA(resp0.angular), zero); f->rbXnI_velMultiplierW = V4SetW(V4Neg(Vec4V_From_Vec3V(V3LoadA(resp1.angular))), velMultiplier); f->biasScale = 0.f; f->appliedForce = 0.f; FStore(torsionalFriction, &f->frictionScale); f->linDeltaVA = V3LoadA(deltaV0.linear); f->linDeltaVB = V3LoadA(deltaV1.linear); f->angDeltaVA = V3LoadA(deltaV0.angular); f->angDeltaVB = V3LoadA(deltaV1.angular); } } frictionPatchWritebackAddrIndex++; } } 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) { PxPrefetchLine(contactDesc.body0); PxPrefetchLine(contactDesc.body1); 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, PxMax(contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius)); // 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); PX_ASSERT((solverConstraintByteSize & 0xf) == 0); 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) { if (useExtContacts) { const SolverExtBodyStep b0(reinterpret_cast<const void*>(contactDesc.body0), contactDesc.body0TxI, contactDesc.bodyData0, desc.linkIndexA); const SolverExtBodyStep b1(reinterpret_cast<const void*>(contactDesc.body1), contactDesc.body1TxI, contactDesc.bodyData1, desc.linkIndexB); setupFinalizeExtSolverContactsStep(contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint, b0, b1, invDtF32, invTotalDtF32, totalDtF32, dtF32, bounceThresholdF32, contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1, contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius, biasCoefficient, contactDesc.offsetSlop); } else { const PxTGSSolverBodyVel& b0 = *contactDesc.body0; const PxTGSSolverBodyVel& b1 = *contactDesc.body1; setupFinalizeSolverConstraints(getInteraction(contactDesc), contactDesc.contacts, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint, b0, b1, *contactDesc.body0TxI, *contactDesc.body1TxI, *contactDesc.bodyData0, *contactDesc.bodyData1, invDtF32, totalDtF32, invTotalDtF32, dtF32, bounceThresholdF32, contactDesc.invMassScales.linear0, contactDesc.invMassScales.angular0, contactDesc.invMassScales.linear1, contactDesc.invMassScales.angular1, hasForceThreshold, staticOrKinematicBody, contactDesc.restDistance, frictionDataPtr, contactDesc.maxCCDSeparation, disableStrongFriction, contactDesc.torsionalPatchRadius, contactDesc.minTorsionalPatchRadius, biasCoefficient, 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; } bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal invTotalDt, const PxReal totalDtF32, const PxReal dt, const PxReal bounceThresholdF32, const PxReal frictionOffsetThreshold, const PxReal correlationDistance, const PxReal biasCoefficient, PxConstraintAllocator& constraintAllocator) { 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; contactDesc.invMassScales.angular0 = (contactDesc.bodyState0 != PxSolverContactDesc::eARTICULATION && contactDesc.body0->isKinematic) ? 0.f : contactDesc.invMassScales.angular0; contactDesc.invMassScales.angular1 = (contactDesc.bodyState1 != PxSolverContactDesc::eARTICULATION && contactDesc.body1->isKinematic) ? 0.f : contactDesc.invMassScales.angular1; bool hasMaxImpulse = false, hasTargetVelocity = false; numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1, contactDesc.maxImpulse); 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 createFinalizeSolverContactsStep(contactDesc, c, invDtF32, invTotalDt, totalDtF32, dt, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, biasCoefficient, constraintAllocator); } static FloatV solveDynamicContactsStep(SolverContactPointStep* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal, const FloatVArg invMassA, const FloatVArg invMassB, Vec3V& linVel0_, Vec3V& angState0_, Vec3V& linVel1_, Vec3V& angState1_, PxF32* PX_RESTRICT forceBuffer, const Vec3V& angMotion0, const Vec3V& angMotion1, const Vec3V& linRelMotion, const FloatVArg maxPenBias, const FloatVArg angD0, const FloatVArg angD1, const FloatVArg minPen, const FloatVArg elapsedTime) { Vec3V linVel0 = linVel0_; Vec3V angState0 = angState0_; Vec3V linVel1 = linVel1_; Vec3V angState1 = angState1_; const FloatV zero = FZero(); FloatV accumulatedNormalImpulse = zero; const Vec3V delLinVel0 = V3Scale(contactNormal, invMassA); const Vec3V delLinVel1 = V3Scale(contactNormal, invMassB); const FloatV deltaV = V3Dot(linRelMotion, contactNormal); for (PxU32 i = 0; i<nbContactPoints; i++) { SolverContactPointStep& c = contacts[i]; PxPrefetchLine(&contacts[i], 128); const Vec3V raXnI = V3LoadA(c.raXnI); const Vec3V rbXnI = V3LoadA(c.rbXnI); const FloatV angDelta0 = V3Dot(angMotion0, raXnI); const FloatV angDelta1 = V3Dot(angMotion1, rbXnI); const FloatV deltaAng = FSub(angDelta0, angDelta1); const FloatV targetVel = FLoad(c.targetVelocity); //const FloatV tVelBias = FLoad(c.targetVelBias); const FloatV deltaBias = FSub(FAdd(deltaV, deltaAng), FMul(targetVel, elapsedTime)); const FloatV biasCoefficient = FLoad(c.biasCoefficient); FloatV sep = FMax(minPen, FAdd(FLoad(c.separation), deltaBias)); const FloatV bias = FMin(FNeg(maxPenBias), FMul(biasCoefficient, sep)); const Vec3V v0 = V3MulAdd(linVel0, contactNormal, V3Mul(angState0, raXnI)); const Vec3V v1 = V3MulAdd(linVel1, contactNormal, V3Mul(angState1, rbXnI)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); const FloatV velMultiplier = FLoad(c.velMultiplier); const FloatV biasNV = FMul(bias, FLoad(c.recipResponse)); const FloatV tVelBias = FNegScaleSub(FSub(normalVel, targetVel), velMultiplier, biasNV); const FloatV appliedForce = FLoad(forceBuffer[i]); const FloatV maxImpulse = FLoad(c.maxImpulse); //KS - todo - hook up! //Compute the normal velocity of the constraint. const FloatV _deltaF = FMax(tVelBias, FNeg(appliedForce)); const FloatV _newForce = FAdd(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(raXnI, FMul(deltaF, angD0), angState0); angState1 = V3NegScaleSub(rbXnI, FMul(deltaF, angD1), angState1); FStore(newForce, &forceBuffer[i]); accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newForce); } linVel0_ = linVel0; angState0_ = angState0; linVel1_ = linVel1; angState1_ = angState1; return accumulatedNormalImpulse; } void solveContact(const PxSolverConstraintDesc& desc, bool doFriction, const PxReal minPenetration, const PxReal elapsedTimeF32) { PxTGSSolverBodyVel& b0 = *desc.tgsBodyA; PxTGSSolverBodyVel& b1 = *desc.tgsBodyB; const FloatV minPen = FLoad(minPenetration); Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularVelocity); Vec3V angState1 = V3LoadA(b1.angularVelocity); const Vec3V angMotion0 = V3LoadA(b0.deltaAngDt); const Vec3V angMotion1 = V3LoadA(b1.deltaAngDt); const Vec3V linMotion0 = V3LoadA(b0.deltaLinDt); const Vec3V linMotion1 = V3LoadA(b1.deltaLinDt); const Vec3V relMotion = V3Sub(linMotion0, linMotion1); const FloatV zero = FZero(); const FloatV elapsedTime = FLoad(elapsedTimeF32); const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; while (currPtr < last) { SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr); currPtr += sizeof(SolverContactHeaderStep); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; SolverContactPointStep* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStep*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPointStep); PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr); currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); SolverContactFrictionStep* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStep*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFrictionStep); const FloatV invMassA = FLoad(hdr->invMass0); const FloatV invMassB = FLoad(hdr->invMass1); const FloatV angDom0 = FLoad(hdr->angDom0); const FloatV angDom1 = FLoad(hdr->angDom1); //const FloatV sumMass = FAdd(invMassA, invMassB); const Vec3V contactNormal = V3LoadA(hdr->normal); const FloatV maxPenBias = FLoad(hdr->maxPenBias); const FloatV accumulatedNormalImpulse = solveDynamicContactsStep(contacts, numNormalConstr, contactNormal, invMassA, invMassB, linVel0, angState0, linVel1, angState1, forceBuffer,angMotion0, angMotion1, relMotion, maxPenBias, angDom0, angDom1, minPen, elapsedTime); FStore(accumulatedNormalImpulse, &hdr->minNormalForce); if (numFrictionConstr && doFriction) { const FloatV staticFrictionCof = hdr->getStaticFriction(); const FloatV dynamicFrictionCof = hdr->getDynamicFriction(); const FloatV maxFrictionImpulse = FMul(staticFrictionCof, accumulatedNormalImpulse); const FloatV maxDynFrictionImpulse = FMul(dynamicFrictionCof, accumulatedNormalImpulse); const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse); BoolV broken = BFFFF(); //We will have either 4 or 2 frictions (with friction pairs). //With torsional friction, we may have 3 (a single friction anchor + twist). const PxU32 numFrictionPairs = (numFrictionConstr&6); for (PxU32 i = 0; i<numFrictionPairs; i += 2) { SolverContactFrictionStep& f0 = frictions[i]; SolverContactFrictionStep& f1 = frictions[i + 1]; PxPrefetchLine(&frictions[i + 2], 128); const FloatV frictionScale = FLoad(f0.frictionScale); const Vec4V normalXYZ_ErrorW0 = f0.normalXYZ_ErrorW; const Vec4V raXnI_targetVelW0 = f0.raXnI_targetVelW; const Vec4V rbXnI_velMultiplierW0 = f0.rbXnI_velMultiplierW; const Vec4V normalXYZ_ErrorW1 = f1.normalXYZ_ErrorW; const Vec4V raXnI_targetVelW1 = f1.raXnI_targetVelW; const Vec4V rbXnI_velMultiplierW1 = f1.rbXnI_velMultiplierW; const Vec3V normal0 = Vec3V_From_Vec4V(normalXYZ_ErrorW0); const Vec3V normal1 = Vec3V_From_Vec4V(normalXYZ_ErrorW1); const FloatV initialError0 = V4GetW(normalXYZ_ErrorW0); const FloatV initialError1 = V4GetW(normalXYZ_ErrorW1); const FloatV biasScale = FLoad(f0.biasScale); //Bias scale will be common const Vec3V raXnI0 = Vec3V_From_Vec4V(raXnI_targetVelW0); const Vec3V rbXnI0 = Vec3V_From_Vec4V(rbXnI_velMultiplierW0); const Vec3V raXnI1 = Vec3V_From_Vec4V(raXnI_targetVelW1); const Vec3V rbXnI1 = Vec3V_From_Vec4V(rbXnI_velMultiplierW1); const FloatV appliedForce0 = FLoad(f0.appliedForce); const FloatV appliedForce1 = FLoad(f1.appliedForce); const FloatV targetVel0 = V4GetW(raXnI_targetVelW0); const FloatV targetVel1 = V4GetW(raXnI_targetVelW1); FloatV deltaV0 = FAdd(FSub(V3Dot(raXnI0, angMotion0), V3Dot(rbXnI0, angMotion1)), V3Dot(normal0, relMotion)); FloatV deltaV1 = FAdd(FSub(V3Dot(raXnI1, angMotion0), V3Dot(rbXnI1, angMotion1)), V3Dot(normal1, relMotion)); deltaV0 = FSub(deltaV0, FMul(targetVel0, elapsedTime)); deltaV1 = FSub(deltaV1, FMul(targetVel1, elapsedTime)); const FloatV error0 = FAdd(initialError0, deltaV0); const FloatV error1 = FAdd(initialError1, deltaV1); const FloatV bias0 = FMul(error0, biasScale); const FloatV bias1 = FMul(error1, biasScale); const FloatV velMultiplier0 = V4GetW(rbXnI_velMultiplierW0); const FloatV velMultiplier1 = V4GetW(rbXnI_velMultiplierW1); const Vec3V delLinVel00 = V3Scale(normal0, invMassA); const Vec3V delLinVel10 = V3Scale(normal0, invMassB); const Vec3V delLinVel01 = V3Scale(normal1, invMassA); const Vec3V delLinVel11 = V3Scale(normal1, invMassB); const Vec3V v00 = V3MulAdd(linVel0, normal0, V3Mul(angState0, raXnI0)); const Vec3V v10 = V3MulAdd(linVel1, normal0, V3Mul(angState1, rbXnI0)); const FloatV normalVel0 = V3SumElems(V3Sub(v00, v10)); const Vec3V v01 = V3MulAdd(linVel0, normal1, V3Mul(angState0, raXnI1)); const Vec3V v11 = V3MulAdd(linVel1, normal1, V3Mul(angState1, rbXnI1)); const FloatV normalVel1 = V3SumElems(V3Sub(v01, v11)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp10 = FNegScaleSub(FSub(bias0, targetVel0), velMultiplier0, appliedForce0); const FloatV tmp11 = FNegScaleSub(FSub(bias1, targetVel1), velMultiplier1, appliedForce1); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse0 = FNegScaleSub(normalVel0, velMultiplier0, tmp10); const FloatV totalImpulse1 = FNegScaleSub(normalVel1, velMultiplier1, tmp11); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const FloatV totalImpulse = FSqrt(FAdd(FMul(totalImpulse0, totalImpulse0), FMul(totalImpulse1, totalImpulse1))); const BoolV clamp = FIsGrtr(totalImpulse, FMul(frictionScale, maxFrictionImpulse)); const FloatV totalClamped = FSel(clamp, FMin(FMul(frictionScale, maxDynFrictionImpulse), totalImpulse), totalImpulse); const FloatV ratio = FSel(FIsGrtr(totalImpulse, zero), FDiv(totalClamped, totalImpulse), zero); const FloatV newAppliedForce0 = FMul(totalImpulse0, ratio); const FloatV newAppliedForce1 = FMul(totalImpulse1, ratio); broken = BOr(broken, clamp); FloatV deltaF0 = FSub(newAppliedForce0, appliedForce0); FloatV deltaF1 = FSub(newAppliedForce1, appliedForce1); // we could get rid of the stall here by calculating and clamping delta separately, but // the complexity isn't really worth it. linVel0 = V3ScaleAdd(delLinVel00, deltaF0, V3ScaleAdd(delLinVel01, deltaF1, linVel0)); linVel1 = V3NegScaleSub(delLinVel10, deltaF0, V3NegScaleSub(delLinVel11, deltaF1, linVel1)); angState0 = V3ScaleAdd(raXnI0, FMul(deltaF0, angDom0), V3ScaleAdd(raXnI1, FMul(deltaF1, angDom0), angState0)); angState1 = V3NegScaleSub(rbXnI0, FMul(deltaF0, angDom1), V3NegScaleSub(rbXnI1, FMul(deltaF1, angDom1), angState1)); f0.setAppliedForce(newAppliedForce0); f1.setAppliedForce(newAppliedForce1); } for (PxU32 i = numFrictionPairs; i<numFrictionConstr; i++) { SolverContactFrictionStep& f = frictions[i]; const FloatV frictionScale = FLoad(f.frictionScale); const Vec4V raXnI_targetVelW = f.raXnI_targetVelW; const Vec4V rbXnI_velMultiplierW = f.rbXnI_velMultiplierW; const Vec3V raXnI = Vec3V_From_Vec4V(raXnI_targetVelW); const Vec3V rbXnI = Vec3V_From_Vec4V(rbXnI_velMultiplierW); const FloatV appliedForce = FLoad(f.appliedForce); const FloatV targetVel = V4GetW(raXnI_targetVelW); const FloatV velMultiplier = V4GetW(rbXnI_velMultiplierW); const Vec3V v0 =V3Mul(angState0, raXnI); const Vec3V v1 =V3Mul(angState1, rbXnI); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp1 = FNegScaleSub(FNeg(targetVel), velMultiplier, appliedForce); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const BoolV clamp = FIsGrtr(FAbs(totalImpulse), FMul(frictionScale, maxFrictionImpulse)); const FloatV totalClamped = FMin(FMul(frictionScale, maxDynFrictionImpulse), FMax(FMul(frictionScale, negMaxDynFrictionImpulse), totalImpulse)); const FloatV newAppliedForce = FSel(clamp, totalClamped, totalImpulse); broken = BOr(broken, clamp); FloatV deltaF = FSub(newAppliedForce, appliedForce); // we could get rid of the stall here by calculating and clamping delta separately, but // the complexity isn't really worth it. angState0 = V3ScaleAdd(raXnI, FMul(deltaF, angDom0), angState0); angState1 = V3NegScaleSub(rbXnI, FMul(deltaF, angDom1), angState1); f.setAppliedForce(newAppliedForce); } Store_From_BoolV(broken, &hdr->broken); } } PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularVelocity.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularVelocity.isFinite()); // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(linVel1, b1.linearVelocity); V3StoreA(angState0, b0.angularVelocity); V3StoreA(angState1, b1.angularVelocity); PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularVelocity.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularVelocity.isFinite()); PX_ASSERT(currPtr == last); } void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext* /*cache*/) { // PxReal normalForce = 0; PxU8* PX_RESTRICT cPtr = desc.constraint; PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack); PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16; bool forceThreshold = false; while (cPtr < last) { const SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeaderStep*>(cPtr); cPtr += sizeof(SolverContactHeaderStep); forceThreshold = hdr->flags & SolverContactHeaderStep::eHAS_FORCE_THRESHOLDS; const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; //if(cPtr < last) PxPrefetchLine(cPtr, 256); PxPrefetchLine(cPtr, 384); const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointStepExt) : sizeof(SolverContactPointStep); cPtr += pointStride * numNormalConstr; PxF32* forceBuffer = reinterpret_cast<PxF32*>(cPtr); cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); if (vForceWriteback != NULL) { for (PxU32 i = 0; i<numNormalConstr; i++) { PxReal appliedForce = forceBuffer[i]; *vForceWriteback++ = appliedForce; // normalForce += appliedForce; } } const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionStepExt) : sizeof(SolverContactFrictionStep); if (hdr->broken && hdr->frictionBrokenWritebackByte != NULL) { *hdr->frictionBrokenWritebackByte = 1; } cPtr += frictionStride * numFrictionConstr; } PX_ASSERT(cPtr == last); PX_UNUSED(forceThreshold); #if 0 if (cache && forceThreshold && desc.linkIndexA == PxSolverConstraintDesc::NO_LINK && desc.linkIndexB == PxSolverConstraintDesc::NO_LINK && normalForce != 0 && (desc.bodyA->reportThreshold < PX_MAX_REAL || desc.bodyB->reportThreshold < PX_MAX_REAL)) { ThresholdStreamElement elt; elt.normalForce = normalForce; elt.threshold = PxMin<float>(desc.bodyA->reportThreshold, desc.bodyB->reportThreshold); elt.nodeIndexA = desc.bodyA->nodeIndex; elt.nodeIndexB = desc.bodyB->nodeIndex; elt.shapeInteraction = reinterpret_cast<const SolverContactHeader*>(desc.constraint)->shapeInteraction; PxOrder(elt.nodeIndexA, elt.nodeIndexB); PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB); PX_ASSERT(cache->mThresholdStreamIndex<cache->mThresholdStreamLength); cache->mThresholdStream[cache->mThresholdStreamIndex++] = elt; } #endif } 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()); } void setSolverConstantsStep(PxReal& error, PxReal& biasScale, PxReal& targetVel, PxReal& maxBias, PxReal& velMultiplier, PxReal& rcpResponse, const Px1DConstraint& c, PxReal normalVel, PxReal unitResponse, PxReal minRowResponse, PxReal erp, PxReal dt, PxReal /*totalDt*/, PxReal biasClamp, PxReal recipdt, PxReal recipTotalDt, PxReal velTarget) { PX_ASSERT(PxIsFinite(unitResponse)); PxReal recipResponse = unitResponse <= minRowResponse ? 0 : 1.0f / unitResponse; //PX_ASSERT(recipResponse < 1e5f); PxReal geomError = c.geometricError; rcpResponse = recipResponse; if (c.flags & Px1DConstraintFlag::eSPRING) { const PxReal a = dt * (dt*c.mods.spring.stiffness + c.mods.spring.damping); const PxReal aDamp = dt * dt * (c.mods.spring.damping + c.mods.spring.stiffness); const PxReal b = dt * (c.mods.spring.damping * (c.velocityTarget));// - c.mods.spring.stiffness * geomError); maxBias = PX_MAX_F32; PxReal errorTerm; if (c.flags & Px1DConstraintFlag::eACCELERATION_SPRING) { const PxReal x = 1.0f / (1.0f + a); const PxReal xDamp = 1.0f / (1.0f + aDamp); targetVel = x * b; velMultiplier = -x * a; errorTerm = -x * c.mods.spring.stiffness * dt; biasScale = errorTerm - xDamp*c.mods.spring.damping*dt; } else { const PxReal x = 1.0f / (1.0f + a*unitResponse); const PxReal xDamp = 1.0f / (1.0f + aDamp*unitResponse); targetVel = x * b*unitResponse; velMultiplier = -x * a*unitResponse; errorTerm = -x * c.mods.spring.stiffness * unitResponse * dt; biasScale = errorTerm - xDamp*c.mods.spring.damping*unitResponse*dt; } error = geomError * errorTerm; } else { velMultiplier = -1.f; if (c.flags & Px1DConstraintFlag::eRESTITUTION && -normalVel>c.mods.bounce.velocityThreshold) { error = 0.f; biasScale = 0.f; targetVel = c.mods.bounce.restitution*-normalVel; maxBias = 0.f; } else { biasScale = -recipdt*erp;// *recipResponse; if (c.flags & Px1DConstraintFlag::eDEPRECATED_DRIVE_ROW) { error = 0.f; targetVel = c.velocityTarget - geomError *recipTotalDt; } else { error = geomError * biasScale; //KS - if there is a velocity target, then we cannot also have bias otherwise the two compete against each-other. //Therefore, we set the velocity target targetVel = c.velocityTarget;// *recipResponse; } maxBias = biasClamp;// *recipResponse; /*PxReal errorBias = PxClamp(geomError*erp*recipdt, -biasClamp, biasClamp); constant = (c.velocityTarget - errorBias) * recipResponse;*/ } } targetVel -= velMultiplier * velTarget; } 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) { 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 bool isKinematic0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc.tgsBodyA->isKinematic; const bool isKinematic1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY && desc.tgsBodyB->isKinematic; const PxU32 stride = isExtended ? sizeof(SolverConstraint1DExtStep) : sizeof(SolverConstraint1DStep); const PxU32 constraintLength = sizeof(SolverConstraint1DHeaderStep) + 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); PX_ASSERT((constraintLength & 0xf) == 0); desc.constraintLengthOver16 = PxTo16(constraintLength / 16); desc.writeBack = prepDesc.writeback; PxMemSet(desc.constraint, 0, constraintLength); SolverConstraint1DHeaderStep* header = reinterpret_cast<SolverConstraint1DHeaderStep*>(desc.constraint); PxU8* constraints = desc.constraint + sizeof(SolverConstraint1DHeaderStep); init(*header, PxTo8(prepDesc.numRows), isExtended, prepDesc.invMassScales); header->body0WorldOffset = prepDesc.body0WorldOffset; header->linBreakImpulse = prepDesc.linBreakForce * totalDt; header->angBreakImpulse = prepDesc.angBreakForce * totalDt; header->breakable = PxU8((prepDesc.linBreakForce != PX_MAX_F32) || (prepDesc.angBreakForce != PX_MAX_F32)); header->invMass0D0 = prepDesc.bodyData0->invMass * prepDesc.invMassScales.linear0; header->invMass1D1 = prepDesc.bodyData1->invMass * prepDesc.invMassScales.linear1; header->rAWorld = prepDesc.cA2w - prepDesc.bodyFrame0.p; header->rBWorld = prepDesc.cB2w - prepDesc.bodyFrame1.p; /*printf("prepDesc.cA2w.p = (%f, %f, %f), prepDesc.cB2w.p = (%f, %f, %f)\n", prepDesc.cA2w.x, prepDesc.cA2w.y, prepDesc.cA2w.z, prepDesc.cB2w.x, prepDesc.cB2w.y, prepDesc.cB2w.z);*/ Px1DConstraint* sorted[MAX_CONSTRAINT_ROWS]; PX_ALIGN(16, PxVec4) angSqrtInvInertia0[MAX_CONSTRAINT_ROWS]; PX_ALIGN(16, PxVec4) angSqrtInvInertia1[MAX_CONSTRAINT_ROWS]; for (PxU32 i = 0; i < prepDesc.numRows; ++i) { if (prepDesc.rows[i].flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT) { if (prepDesc.rows[i].solveHint == PxConstraintSolveHint::eEQUALITY) prepDesc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_EQUALITY; else if (prepDesc.rows[i].solveHint == PxConstraintSolveHint::eINEQUALITY) prepDesc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_INEQUALITY; } } preprocessRows(sorted, prepDesc.rows, angSqrtInvInertia0, angSqrtInvInertia1, prepDesc.numRows, prepDesc.body0TxI->sqrtInvInertia, prepDesc.body1TxI->sqrtInvInertia, prepDesc.bodyData0->invMass, prepDesc.bodyData1->invMass, prepDesc.invMassScales, isExtended || prepDesc.disablePreprocessing, prepDesc.improvedSlerp); const PxReal erp = 0.5f * biasCoefficient; const PxReal recipDt = invdt; const PxReal angSpeedLimit = invTotalDt*0.75f; const PxReal linSpeedLimit = isExtended ? invTotalDt*1.5f*lengthScale : invTotalDt*15.f*lengthScale; PxU32 orthoCount = 0; PxU32 outCount = 0; const SolverExtBodyStep eb0(reinterpret_cast<const void*>(prepDesc.body0), prepDesc.body0TxI, prepDesc.bodyData0, desc.linkIndexA); const SolverExtBodyStep eb1(reinterpret_cast<const void*>(prepDesc.body1), prepDesc.body1TxI, prepDesc.bodyData1, desc.linkIndexB); PxReal cfm = 0.f; if (isExtended) { cfm = PxMax(eb0.getCFM(), eb1.getCFM()); } for (PxU32 i = 0; i<prepDesc.numRows; i++) { PxPrefetchLine(constraints, 128); SolverConstraint1DStep &s = *reinterpret_cast<SolverConstraint1DStep *>(constraints); Px1DConstraint& c = *sorted[i]; PxReal driveScale = c.flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && prepDesc.driveLimitsAreForces ? PxMin(totalDt, 1.0f) : 1.0f; PxReal unitResponse; PxReal normalVel = 0.0f; PxReal vel0, vel1; if (!isExtended) { const PxVec3 angSqrtInvInertia0V3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z); const PxVec3 angSqrtInvInertia1V3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z); init(s, c.linear0, c.linear1, c.angular0, c.angular1, c.minImpulse * driveScale, c.maxImpulse * driveScale); /*unitResponse = prepDesc.body0->getResponse(c.linear0, c.angular0, s.ang0, prepDesc.mInvMassScales.linear0, prepDesc.mInvMassScales.angular0) + prepDesc.body1->getResponse(-c.linear1, -c.angular1, s.ang1, prepDesc.mInvMassScales.linear1, prepDesc.mInvMassScales.angular1);*/ const PxReal linSumMass = s.lin0.magnitudeSquared() * prepDesc.bodyData0->invMass * prepDesc.invMassScales.linear0 + s.lin1.magnitudeSquared() * prepDesc.bodyData1->invMass * prepDesc.invMassScales.linear1; PxReal resp0 = angSqrtInvInertia0V3.magnitudeSquared() * prepDesc.invMassScales.angular0; PxReal resp1 = angSqrtInvInertia1V3.magnitudeSquared() * prepDesc.invMassScales.angular1; unitResponse = resp0 + resp1 + linSumMass; //s.recipResponseOrLinearSumMass = linSumMass; vel0 = prepDesc.bodyData0->projectVelocity(s.lin0, s.ang0); vel1 = prepDesc.bodyData1->projectVelocity(s.lin1, s.ang1); normalVel = vel0 - vel1; //if (c.solveHint & PxConstraintSolveHint::eEQUALITY) if(!(c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT)) { s.ang0 = PxVec3(0.f); s.ang1 = PxVec3(0.f); s.angularErrorScale = 0.f; } } else { const Cm::SpatialVector resp0 = createImpulseResponseVector(c.linear0, c.angular0, eb0); const Cm::SpatialVector resp1 = createImpulseResponseVector(-c.linear1, -c.angular1, eb1); init(s, resp0.linear, -resp1.linear, resp0.angular, -resp1.angular, c.minImpulse * driveScale, c.maxImpulse * driveScale); SolverConstraint1DExtStep& e = static_cast<SolverConstraint1DExtStep&>(s); Cm::SpatialVector& delta0 = unsimdRef(e.deltaVA); Cm::SpatialVector& delta1 = unsimdRef(e.deltaVB); unitResponse = getImpulseResponse(eb0, resp0, delta0, prepDesc.invMassScales.linear0, prepDesc.invMassScales.angular0, eb1, resp1, delta1, prepDesc.invMassScales.linear1, prepDesc.invMassScales.angular1, false); //PxReal totalVelChange = (delta0 - delta1).magnitude(); //PX_UNUSED(totalVelChange); if (unitResponse < DY_ARTICULATION_MIN_RESPONSE) { continue; } else unitResponse += cfm; { vel0 = eb0.projectVelocity(s.lin0, s.ang0); vel1 = eb1.projectVelocity(s.lin1, s.ang1); normalVel = vel0 - vel1; } if (!(c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT)) { s.angularErrorScale = 0.f; } } PxReal recipResponse = 0.f; PxReal velTarget = 0.f; if (isKinematic0) velTarget -= vel0; if (isKinematic1) velTarget += vel1; setSolverConstantsStep(s.error, s.biasScale, s.velTarget, s.maxBias, s.velMultiplier, recipResponse, c, normalVel, unitResponse, prepDesc.minResponseThreshold, erp, dt, totalDt, c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? angSpeedLimit : linSpeedLimit, recipDt, invTotalDt, velTarget); s.recipResponse = recipResponse; if (c.flags & Px1DConstraintFlag::eOUTPUT_FORCE) s.flags |= DY_SC_FLAG_OUTPUT_FORCE; if ((c.flags & Px1DConstraintFlag::eKEEPBIAS)) s.flags |= DY_SC_FLAG_KEEP_BIAS; if (c.solveHint & 1) s.flags |= DY_SC_FLAG_INEQUALITY; if (!(isExtended || prepDesc.disablePreprocessing)) { //KS - the code that orthogonalizes constraints on-the-fly only works if the linear and angular constraints have already been pre-orthogonalized if (c.solveHint == PxConstraintSolveHint::eROTATIONAL_EQUALITY) { s.flags |= DY_SC_FLAG_ROT_EQ; PX_ASSERT(orthoCount < 3); /*angOrtho0[orthoCount] = PxVec3(angSqrtInvInertia0[i].x, angSqrtInvInertia0[i].y, angSqrtInvInertia0[i].z); angOrtho1[orthoCount] = PxVec3(angSqrtInvInertia1[i].x, angSqrtInvInertia1[i].y, angSqrtInvInertia1[i].z); recipResponses[orthoCount] = recipResponse;*/ header->angOrthoAxis0_recipResponseW[orthoCount] = PxVec4(angSqrtInvInertia0[i].x*prepDesc.invMassScales.angular0, angSqrtInvInertia0[i].y*prepDesc.invMassScales.angular0, angSqrtInvInertia0[i].z*prepDesc.invMassScales.angular0, recipResponse); header->angOrthoAxis1_Error[orthoCount].x = angSqrtInvInertia1[i].x*prepDesc.invMassScales.angular1; header->angOrthoAxis1_Error[orthoCount].y = angSqrtInvInertia1[i].y*prepDesc.invMassScales.angular1; header->angOrthoAxis1_Error[orthoCount].z = angSqrtInvInertia1[i].z*prepDesc.invMassScales.angular1; header->angOrthoAxis1_Error[orthoCount].w = c.geometricError; orthoCount++; } else if (c.solveHint & PxConstraintSolveHint::eEQUALITY) s.flags |= DY_SC_FLAG_ORTHO_TARGET; } constraints += stride; outCount++; } //KS - we now need to re-set count because we may have skipped degenerate rows when solving articulation constraints. //In this case, the degenerate rows would have produced no force. Skipping them is just an optimization header->count = PxU8(outCount); return prepDesc.numRows; } 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) { // LL shouldn't see broken constraints PX_ASSERT(!(reinterpret_cast<ConstraintWriteback*>(prepDesc.writeback)->broken)); prepDesc.desc->constraintLengthOver16 = 0; //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.f; prepDesc.body0WorldOffset = PxVec3(0.0f); //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, prepDesc.cA2w, prepDesc.cB2w); prepDesc.rows = rows; if (prepDesc.bodyState0 != PxSolverContactDesc::eARTICULATION && prepDesc.body0->isKinematic) prepDesc.invMassScales.angular0 = 0.f; if (prepDesc.bodyState1 != PxSolverContactDesc::eARTICULATION && prepDesc.body1->isKinematic) prepDesc.invMassScales.angular1 = 0.f; return setupSolverConstraintStep(prepDesc, allocator, dt, totalDt, invdt, invTotalDt, lengthScale, biasCoefficient); } void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, const Vec3V& linMotion0, const Vec3V& linMotion1, const Vec3V& angMotion0, const Vec3V& angMotion1, const QuatV& rotA, const QuatV& rotB, const PxReal elapsedTimeF32, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1) { PxU8* PX_RESTRICT bPtr = desc.constraint; const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr); SolverConstraint1DExtStep* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExtStep*>(bPtr + sizeof(SolverConstraint1DHeaderStep)); const FloatV elapsedTime = FLoad(elapsedTimeF32); const Vec3V raPrev = V3LoadA(header->rAWorld); const Vec3V rbPrev = V3LoadA(header->rBWorld); const Vec3V ra = QuatRotate(rotA, V3LoadA(header->rAWorld)); const Vec3V rb = QuatRotate(rotB, V3LoadA(header->rBWorld)); const Vec3V raMotion = V3Sub(V3Add(ra, linMotion0), raPrev); const Vec3V rbMotion = V3Sub(V3Add(rb, linMotion1), rbPrev); Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); const PxU32 count = header->count; for (PxU32 i = 0; i<count; ++i, base++) { PxPrefetchLine(base + 1); SolverConstraint1DExtStep& c = *base; const Vec3V clinVel0 = V3LoadA(c.lin0); const Vec3V clinVel1 = V3LoadA(c.lin1); const Vec3V cangVel0 = V3LoadA(c.ang0); const Vec3V cangVel1 = V3LoadA(c.ang1); const FloatV recipResponse = FLoad(c.recipResponse); const FloatV targetVel = FLoad(c.velTarget); const FloatV deltaAng = FMul(FSub(V3Dot(cangVel0, angMotion0), V3Dot(cangVel1, angMotion1)), FLoad(c.angularErrorScale)); const FloatV errorChange = FNegScaleSub(targetVel, elapsedTime, FAdd(FSub(V3Dot(raMotion, clinVel0), V3Dot(rbMotion, clinVel1)), deltaAng)); const FloatV biasScale = FLoad(c.biasScale); const FloatV maxBias = FLoad(c.maxBias); const FloatV vMul = FMul(recipResponse, FLoad(c.velMultiplier)); const FloatV appliedForce = FLoad(c.appliedForce); const FloatV unclampedBias = FScaleAdd(errorChange, biasScale, FLoad(c.error)); const FloatV minBias = c.flags & DY_SC_FLAG_INEQUALITY ? FNeg(FMax()) : FNeg(maxBias); const FloatV bias = FClamp(unclampedBias, minBias, maxBias); const FloatV constant = FMul(recipResponse, FAdd(bias, targetVel)); const FloatV maxImpulse = FLoad(c.maxImpulse); const FloatV minImpulse = FLoad(c.minImpulse); const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angVel0, cangVel0)); const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angVel1, cangVel1)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); const FloatV unclampedForce = FAdd(appliedForce, FScaleAdd(vMul, normalVel, constant)); const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce))); const FloatV deltaF = FSub(clampedForce, appliedForce); FStore(clampedForce, &c.appliedForce); //PX_ASSERT(FAllGrtr(FLoad(1000.f), FAbs(deltaF))); FStore(clampedForce, &base->appliedForce); li0 = V3ScaleAdd(clinVel0, deltaF, li0); ai0 = V3ScaleAdd(cangVel0, deltaF, ai0); li1 = V3ScaleAdd(clinVel1, deltaF, li1); ai1 = V3ScaleAdd(cangVel1, deltaF, ai1); linVel0 = V3ScaleAdd(base->deltaVA.linear, deltaF, linVel0); angVel0 = V3ScaleAdd(base->deltaVA.angular, deltaF, angVel0); linVel1 = V3ScaleAdd(base->deltaVB.linear, deltaF, linVel1); angVel1 = V3ScaleAdd(base->deltaVB.angular, deltaF, angVel1); /*PX_ASSERT(FAllGrtr(FLoad(40.f * 40.f), V3Dot(linVel0, linVel0))); PX_ASSERT(FAllGrtr(FLoad(40.f * 40.f), V3Dot(linVel1, linVel1))); PX_ASSERT(FAllGrtr(FLoad(20.f * 20.f), V3Dot(angVel0, angVel0))); PX_ASSERT(FAllGrtr(FLoad(20.f * 20.f), V3Dot(angVel1, angVel1)));*/ } linImpulse0 = V3Scale(li0, FLoad(header->linearInvMassScale0)); linImpulse1 = V3Scale(li1, FLoad(header->linearInvMassScale1)); angImpulse0 = V3Scale(ai0, FLoad(header->angularInvMassScale0)); angImpulse1 = V3Scale(ai1, FLoad(header->angularInvMassScale1)); } //Port of scalar implementation to SIMD maths with some interleaving of instructions void solveExt1DStep(const PxSolverConstraintDesc& desc, const PxReal elapsedTimeF32, SolverContext& cache, const PxTGSSolverBodyTxInertia* const txInertias) { Vec3V linVel0, angVel0, linVel1, angVel1; Vec3V linMotion0, angMotion0, linMotion1, angMotion1; QuatV rotA, rotB; Dy::FeatherstoneArticulation* artA = getArticulationA(desc); Dy::FeatherstoneArticulation* artB = getArticulationB(desc); if (artA == artB) { Cm::SpatialVectorV v0, v1; artA->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1); linVel0 = v0.linear; angVel0 = v0.angular; linVel1 = v1.linear; angVel1 = v1.angular; const Cm::SpatialVectorV motionV0 = artA->getLinkMotionVector(desc.linkIndexA); //PxcFsGetMotionVector(*artA, desc.linkIndexA); const Cm::SpatialVectorV motionV1 = artB->getLinkMotionVector(desc.linkIndexB); //PxcFsGetMotionVector(*artB, desc.linkIndexB); linMotion0 = motionV0.linear; angMotion0 = motionV0.angular; linMotion1 = motionV1.linear; angMotion1 = motionV1.angular; rotA = aos::QuatVLoadU(&artA->getDeltaQ(desc.linkIndexA).x); rotB = aos::QuatVLoadU(&artB->getDeltaQ(desc.linkIndexB).x); } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.tgsBodyA->linearVelocity); angVel0 = V3LoadA(desc.tgsBodyA->angularVelocity); linMotion0 = V3LoadA(desc.tgsBodyA->deltaLinDt); angMotion0 = V3LoadA(desc.tgsBodyA->deltaAngDt); rotA = aos::QuatVLoadA(&txInertias[desc.bodyADataIndex].deltaBody2World.q.x); } else { const Cm::SpatialVectorV v = artA->pxcFsGetVelocity(desc.linkIndexA); rotA = aos::QuatVLoadU(&artA->getDeltaQ(desc.linkIndexA).x); const Cm::SpatialVectorV motionV = artA->getLinkMotionVector(desc.linkIndexA);//PxcFsGetMotionVector(*artA, desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; linMotion0 = motionV.linear; angMotion0 = motionV.angular; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.tgsBodyB->linearVelocity); angVel1 = V3LoadA(desc.tgsBodyB->angularVelocity); linMotion1 = V3LoadA(desc.tgsBodyB->deltaLinDt); angMotion1 = V3LoadA(desc.tgsBodyB->deltaAngDt); rotB = aos::QuatVLoadA(&txInertias[desc.bodyBDataIndex].deltaBody2World.q.x); } else { Cm::SpatialVectorV v = artB->pxcFsGetVelocity(desc.linkIndexB); rotB = aos::QuatVLoadU(&artB->getDeltaQ(desc.linkIndexB).x); Cm::SpatialVectorV motionV = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; linMotion1 = motionV.linear; angMotion1 = motionV.angular; } } Vec3V li0, li1, ai0, ai1; solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, linMotion0, linMotion1, angMotion0, angMotion1, rotA, rotB, elapsedTimeF32, li0, li1, ai0, ai1); if (artA == artB) { artA->pxcFsApplyImpulses(desc.linkIndexA, li0, ai0, desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV); } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.tgsBodyA->linearVelocity); V3StoreA(angVel0, desc.tgsBodyA->angularVelocity); } else { artA->pxcFsApplyImpulse(desc.linkIndexA, li0, ai0, cache.Z, cache.deltaV); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.tgsBodyB->linearVelocity); V3StoreA(angVel1, desc.tgsBodyB->angularVelocity); } else { artB->pxcFsApplyImpulse(desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV); } } } //Port of scalar implementation to SIMD maths with some interleaving of instructions void solve1DStep(const PxSolverConstraintDesc& desc, const PxTGSSolverBodyTxInertia* const txInertias, const PxReal elapsedTime) { PxU8* PX_RESTRICT bPtr = desc.constraint; if (bPtr == NULL) return; PxTGSSolverBodyVel& b0 = *desc.tgsBodyA; PxTGSSolverBodyVel& b1 = *desc.tgsBodyB; const FloatV elapsed = FLoad(elapsedTime); const PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex]; const PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex]; const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr); SolverConstraint1DStep* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep*>(bPtr + sizeof(SolverConstraint1DHeaderStep)); Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularVelocity); Vec3V angState1 = V3LoadA(b1.angularVelocity); Mat33V sqrtInvInertia0 = Mat33V(V3LoadU(txI0.sqrtInvInertia.column0), V3LoadU(txI0.sqrtInvInertia.column1), V3LoadU(txI0.sqrtInvInertia.column2)); Mat33V sqrtInvInertia1 = Mat33V(V3LoadU(txI1.sqrtInvInertia.column0), V3LoadU(txI1.sqrtInvInertia.column1), V3LoadU(txI1.sqrtInvInertia.column2)); const FloatV invMass0 = FLoad(header->invMass0D0); const FloatV invMass1 = FLoad(header->invMass1D1); const FloatV invInertiaScale0 = FLoad(header->angularInvMassScale0); const FloatV invInertiaScale1 = FLoad(header->angularInvMassScale1); const QuatV deltaRotA = aos::QuatVLoadA(&txI0.deltaBody2World.q.x); const QuatV deltaRotB = aos::QuatVLoadA(&txI1.deltaBody2World.q.x); const Vec3V raPrev = V3LoadA(header->rAWorld); const Vec3V rbPrev = V3LoadA(header->rBWorld); const Vec3V ra = QuatRotate(deltaRotA, raPrev); const Vec3V rb = QuatRotate(deltaRotB, rbPrev); const Vec3V ang0 = V3LoadA(b0.deltaAngDt); const Vec3V ang1 = V3LoadA(b1.deltaAngDt); const Vec3V lin0 = V3LoadA(b0.deltaLinDt); const Vec3V lin1 = V3LoadA(b1.deltaLinDt); const Vec3V raMotion = V3Sub(V3Add(ra, lin0), raPrev); const Vec3V rbMotion = V3Sub(V3Add(rb, lin1), rbPrev); const VecCrossV raCross = V3PrepareCross(ra); const VecCrossV rbCross = V3PrepareCross(rb); const Vec4V ang0Ortho0_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[0].x); const Vec4V ang0Ortho1_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[1].x); const Vec4V ang0Ortho2_recipResponseW = V4LoadA(&header->angOrthoAxis0_recipResponseW[2].x); const Vec4V ang1Ortho0_Error0 = V4LoadA(&header->angOrthoAxis1_Error[0].x); const Vec4V ang1Ortho1_Error1 = V4LoadA(&header->angOrthoAxis1_Error[1].x); const Vec4V ang1Ortho2_Error2 = V4LoadA(&header->angOrthoAxis1_Error[2].x); const FloatV recipResponse0 = V4GetW(ang0Ortho0_recipResponseW); const FloatV recipResponse1 = V4GetW(ang0Ortho1_recipResponseW); const FloatV recipResponse2 = V4GetW(ang0Ortho2_recipResponseW); const Vec3V ang0Ortho0 = Vec3V_From_Vec4V(ang0Ortho0_recipResponseW); const Vec3V ang0Ortho1 = Vec3V_From_Vec4V(ang0Ortho1_recipResponseW); const Vec3V ang0Ortho2 = Vec3V_From_Vec4V(ang0Ortho2_recipResponseW); const Vec3V ang1Ortho0 = Vec3V_From_Vec4V(ang1Ortho0_Error0); const Vec3V ang1Ortho1 = Vec3V_From_Vec4V(ang1Ortho1_Error1); const Vec3V ang1Ortho2 = Vec3V_From_Vec4V(ang1Ortho2_Error2); FloatV error0 = FAdd(V4GetW(ang1Ortho0_Error0), FSub(V3Dot(ang0Ortho0, ang0), V3Dot(ang1Ortho0, ang1))); FloatV error1 = FAdd(V4GetW(ang1Ortho1_Error1), FSub(V3Dot(ang0Ortho1, ang0), V3Dot(ang1Ortho1, ang1))); FloatV error2 = FAdd(V4GetW(ang1Ortho2_Error2), FSub(V3Dot(ang0Ortho2, ang0), V3Dot(ang1Ortho2, ang1))); const PxU32 count = header->count; for (PxU32 i = 0; i<count; ++i, base++) { PxPrefetchLine(base + 1); SolverConstraint1DStep& c = *base; const Vec3V clinVel0 = V3LoadA(c.lin0); const Vec3V clinVel1 = V3LoadA(c.lin1); const Vec3V cangVel0_ = V3LoadA(c.ang0); const Vec3V cangVel1_ = V3LoadA(c.ang1); const FloatV angularErrorScale = FLoad(c.angularErrorScale); const FloatV biasScale = FLoad(c.biasScale); const FloatV maxBias = FLoad(c.maxBias); const FloatV targetVel = FLoad(c.velTarget); const FloatV appliedForce = FLoad(c.appliedForce); const FloatV velMultiplier = FLoad(c.velMultiplier); const FloatV maxImpulse = FLoad(c.maxImpulse); const FloatV minImpulse = FLoad(c.minImpulse); Vec3V cangVel0 = V3Add(cangVel0_, V3Cross(raCross, clinVel0)); Vec3V cangVel1 = V3Add(cangVel1_, V3Cross(rbCross, clinVel1)); FloatV error = FLoad(c.error); const FloatV minBias = (c.flags & DY_SC_FLAG_INEQUALITY) ? FNeg(FMax()) : FNeg(maxBias); Vec3V raXnI = M33MulV3(sqrtInvInertia0, cangVel0); Vec3V rbXnI = M33MulV3(sqrtInvInertia1, cangVel1); if (c.flags & DY_SC_FLAG_ORTHO_TARGET) { //Re-orthogonalize the constraints before velocity projection and impulse response calculation //Can be done in using instruction parallelism because angular locked axes are orthogonal to linear axes! const FloatV proj0 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho0, V3Mul(rbXnI, ang1Ortho0))), recipResponse0); const FloatV proj1 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho1, V3Mul(rbXnI, ang1Ortho1))), recipResponse1); const FloatV proj2 = FMul(V3SumElems(V3MulAdd(raXnI, ang0Ortho2, V3Mul(rbXnI, ang1Ortho2))), recipResponse2); const Vec3V delta0 = V3ScaleAdd(ang0Ortho0, proj0, V3ScaleAdd(ang0Ortho1, proj1, V3Scale(ang0Ortho2, proj2))); const Vec3V delta1 = V3ScaleAdd(ang1Ortho0, proj0, V3ScaleAdd(ang1Ortho1, proj1, V3Scale(ang1Ortho2, proj2))); raXnI = V3Sub(raXnI, delta0); rbXnI = V3Sub(rbXnI, delta1); error = FSub(error, FScaleAdd(error0, proj0, FScaleAdd(error1, proj1, FMul(error2, proj2)))); } const FloatV deltaAng = FMul(angularErrorScale, FSub(V3Dot(raXnI, ang0), V3Dot(rbXnI, ang1))); FloatV errorChange = FNegScaleSub(targetVel, elapsed, FAdd(FSub(V3Dot(raMotion, clinVel0), V3Dot(rbMotion, clinVel1)), deltaAng)); const FloatV resp0 = FScaleAdd(invMass0, V3Dot(clinVel0, clinVel0), V3SumElems(V3Mul(V3Scale(raXnI, invInertiaScale0), raXnI))); const FloatV resp1 = FSub(FMul(invMass1, V3Dot(clinVel1, clinVel1)), V3SumElems(V3Mul(V3Scale(rbXnI, invInertiaScale1), rbXnI))); const FloatV response = FAdd(resp0, resp1); const FloatV recipResponse = FSel(FIsGrtr(response, FZero()), FRecip(response), FZero()); const FloatV vMul = FMul(recipResponse, velMultiplier); const FloatV unclampedBias = FScaleAdd(errorChange, biasScale, error); const FloatV bias = FClamp(unclampedBias, minBias, maxBias); const FloatV constant = FMul(recipResponse, FAdd(bias, targetVel)); const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angState0, raXnI)); const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angState1, rbXnI)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); const FloatV unclampedForce = FAdd(appliedForce, FScaleAdd(vMul, normalVel, constant)); const FloatV clampedForce = FClamp(unclampedForce, minImpulse, maxImpulse); const FloatV deltaF = FSub(clampedForce, appliedForce); FStore(clampedForce, &c.appliedForce); linVel0 = V3ScaleAdd(clinVel0, FMul(deltaF, invMass0), linVel0); linVel1 = V3NegScaleSub(clinVel1, FMul(deltaF, invMass1), linVel1); angState0 = V3ScaleAdd(raXnI, FMul(deltaF, invInertiaScale0), angState0); angState1 = V3ScaleAdd(rbXnI, FMul(deltaF, invInertiaScale1), angState1); } V3StoreA(linVel0, b0.linearVelocity); V3StoreA(angState0, b0.angularVelocity); V3StoreA(linVel1, b1.linearVelocity); V3StoreA(angState1, b1.angularVelocity); PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularVelocity.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularVelocity.isFinite()); } //Port of scalar implementation to SIMD maths with some interleaving of instructions void conclude1DStep(const PxSolverConstraintDesc& desc) { PxU8* PX_RESTRICT bPtr = desc.constraint; if (bPtr == NULL) return; const SolverConstraint1DHeaderStep* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep*>(bPtr); PxU8* PX_RESTRICT base = bPtr + sizeof(SolverConstraint1DHeaderStep); const PxU32 stride = header->type == DY_SC_TYPE_RB_1D ? sizeof(SolverConstraint1DStep) : sizeof(SolverConstraint1DExtStep); const PxU32 count = header->count; for (PxU32 i = 0; i<count; ++i, base+=stride) { SolverConstraint1DStep& c = *reinterpret_cast<SolverConstraint1DStep*>(base); PxPrefetchLine(&c + 1); if (!(c.flags & DY_SC_FLAG_KEEP_BIAS)) { c.biasScale = 0.f; c.error = 0.f; } } } void concludeContact(const PxSolverConstraintDesc& desc) { PX_UNUSED(desc); //const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); ////hopefully pointer aliasing doesn't bite. //PxU8* PX_RESTRICT currPtr = desc.constraint; //SolverContactHeaderStep* PX_RESTRICT firstHdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr); //bool isExtended = firstHdr->type == DY_SC_TYPE_EXT_CONTACT; //const PxU32 contactStride = isExtended ? sizeof(SolverContactPointStepExt) : sizeof(SolverContactPointStep); //const PxU32 frictionStride = isExtended ? sizeof(SolverContactFrictionStepExt) : sizeof(SolverContactFrictionStep); //while (currPtr < last) //{ // SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr); // currPtr += sizeof(SolverContactHeaderStep); // const PxU32 numNormalConstr = hdr->numNormalConstr; // const PxU32 numFrictionConstr = hdr->numFrictionConstr; // /*PxU8* PX_RESTRICT contacts = currPtr; // prefetchLine(contacts);*/ // currPtr += numNormalConstr * contactStride; // //PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr); // currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); // PxU8* PX_RESTRICT frictions = currPtr; // currPtr += numFrictionConstr * frictionStride; // /*for (PxU32 i = 0; i < numNormalConstr; ++i) // { // SolverContactPointStep& c = *reinterpret_cast<SolverContactPointStep*>(contacts); // contacts += contactStride; // if(c.separation <= 0.f) // c.biasCoefficient = 0.f; // }*/ // for (PxU32 i = 0; i < numFrictionConstr; ++i) // { // SolverContactFrictionStep& f = *reinterpret_cast<SolverContactFrictionStep*>(frictions); // frictions += frictionStride; // f.biasScale = 0.f; // } //} //PX_ASSERT(currPtr == last); } void writeBack1D(const PxSolverConstraintDesc& desc) { ConstraintWriteback* writeback = reinterpret_cast<ConstraintWriteback*>(desc.writeBack); if (writeback) { SolverConstraint1DHeaderStep* header = reinterpret_cast<SolverConstraint1DHeaderStep*>(desc.constraint); PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeaderStep); const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExtStep) : sizeof(SolverConstraint1DStep); PxVec3 lin(0), ang(0); const PxU32 count = header->count; for (PxU32 i = 0; i<count; i++) { const SolverConstraint1DStep* c = reinterpret_cast<SolverConstraint1DStep*>(base); if (c->flags & DY_SC_FLAG_OUTPUT_FORCE) { lin += c->lin0 * c->appliedForce; ang += (c->ang0 + c->lin0.cross(header->rAWorld)) * c->appliedForce; } base += stride; } ang -= header->body0WorldOffset.cross(lin); writeback->linearImpulse = lin; writeback->angularImpulse = ang; writeback->broken = header->breakable ? PxU32(lin.magnitude()>header->linBreakImpulse || ang.magnitude()>header->angBreakImpulse) : 0; //KS - the amount of memory we allocated may now be significantly larger than the number of constraint rows. This is because //we discard degenerate rows in the articulation constraint prep code. //PX_ASSERT(desc.constraint + (desc.constraintLengthOver16 * 16) == base); } } static FloatV solveExtContactsStep(SolverContactPointStepExt* contacts, const PxU32 nbContactPoints, const Vec3VArg contactNormal, Vec3V& linVel0, Vec3V& angVel0, Vec3V& linVel1, Vec3V& angVel1, Vec3V& li0, Vec3V& ai0, Vec3V& li1, Vec3V& ai1, const Vec3V& linDeltaA, const Vec3V& linDeltaB, const Vec3V& angDeltaA, const Vec3V angDeltaB, const FloatV& maxPenBias, PxF32* PX_RESTRICT appliedForceBuffer, const FloatV& minPen, const FloatV& elapsedTime) { const FloatV deltaV = V3Dot(contactNormal, V3Sub(linDeltaA, linDeltaB)); FloatV accumulatedNormalImpulse = FZero(); for (PxU32 i = 0; i<nbContactPoints; i++) { SolverContactPointStepExt& c = contacts[i]; PxPrefetchLine(&contacts[i + 1]); const Vec3V raXn = V3LoadA(c.raXnI); const Vec3V rbXn = V3LoadA(c.rbXnI); const FloatV appliedForce = FLoad(appliedForceBuffer[i]); const FloatV velMultiplier = FLoad(c.velMultiplier); const FloatV recipResponse = FLoad(c.recipResponse); //Component of relative velocity at contact point that is along the contact normal. //n.[(va + wa X ra) - (vb + wb X rb)] Vec3V v = V3MulAdd(linVel0, contactNormal, V3Mul(angVel0, raXn)); v = V3Sub(v, V3MulAdd(linVel1, contactNormal, V3Mul(angVel1, rbXn))); const FloatV normalVel = V3SumElems(v); const FloatV angDelta0 = V3Dot(angDeltaA, raXn); const FloatV angDelta1 = V3Dot(angDeltaB, rbXn); const FloatV deltaAng = FSub(angDelta0, angDelta1); const FloatV targetVel = FLoad(c.targetVelocity); const FloatV deltaBias = FSub(FAdd(deltaV, deltaAng), FMul(targetVel, elapsedTime)); //const FloatV deltaBias = FAdd(deltaV, deltaAng); const FloatV biasCoefficient = FLoad(c.biasCoefficient); FloatV sep = FMax(minPen, FAdd(FLoad(c.separation), deltaBias)); const FloatV bias = FMin(FNeg(maxPenBias), FMul(biasCoefficient, sep)); const FloatV tVelBias = FMul(bias, recipResponse); const FloatV _deltaF = FMax(FSub(tVelBias, FMul(FSub(normalVel, targetVel), velMultiplier)), FNeg(appliedForce)); const FloatV _newForce = FAdd(appliedForce, _deltaF); const FloatV newForce = FMin(_newForce, FLoad(c.maxImpulse)); const FloatV deltaF = FSub(newForce, appliedForce); const Vec3V raXnI = c.angDeltaVA; const Vec3V rbXnI = c.angDeltaVB; linVel0 = V3ScaleAdd(c.linDeltaVA, deltaF, linVel0); angVel0 = V3ScaleAdd(raXnI, deltaF, angVel0); linVel1 = V3ScaleAdd(c.linDeltaVB, deltaF, linVel1); angVel1 = V3ScaleAdd(rbXnI, deltaF, angVel1); li0 = V3ScaleAdd(contactNormal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0); li1 = V3ScaleAdd(contactNormal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1); const FloatV newAppliedForce = FAdd(appliedForce, deltaF); FStore(newAppliedForce, &appliedForceBuffer[i]); accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newAppliedForce); } return accumulatedNormalImpulse; } void solveExtContactStep( const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& linDelta0, Vec3V& linDelta1, Vec3V& angDelta0, Vec3V& angDelta1, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool /*doFriction*/, const PxReal minPenetration, const PxReal elapsedTimeF32) { const FloatV elapsedTime = FLoad(elapsedTimeF32); const FloatV minPen = FLoad(minPenetration); const FloatV zero = FZero(); const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16; //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; const Vec3V relMotion = V3Sub(linDelta0, linDelta1); while (currPtr < last) { SolverContactHeaderStep* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStep*>(currPtr); currPtr += sizeof(SolverContactHeaderStep); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; SolverContactPointStepExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepExt*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPointStepExt); PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(currPtr); currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); SolverContactFrictionStepExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepExt*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFrictionStepExt); Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); const Vec3V contactNormal = V3LoadA(hdr->normal); const FloatV accumulatedNormalImpulse = FMax(solveExtContactsStep( contacts, numNormalConstr, contactNormal, linVel0, angVel0, linVel1, angVel1, li0, ai0, li1, ai1, linDelta0, linDelta1, angDelta0, angDelta1, FLoad(hdr->maxPenBias), appliedForceBuffer, minPen, elapsedTime), FLoad(hdr->minNormalForce)); if (numFrictionConstr) { PxPrefetchLine(frictions); const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse); const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse); BoolV broken = BFFFF(); const PxU32 numFrictionPairs = numFrictionConstr &6; for (PxU32 i = 0; i<numFrictionPairs; i += 2) { SolverContactFrictionStepExt& f0 = frictions[i]; SolverContactFrictionStepExt& f1 = frictions[i+1]; PxPrefetchLine(&frictions[i + 2]); const Vec4V normalXYZ_ErrorW0 = f0.normalXYZ_ErrorW; const Vec4V raXn_targetVelW0 = f0.raXnI_targetVelW; const Vec4V rbXn_velMultiplierW0 = f0.rbXnI_velMultiplierW; const Vec4V normalXYZ_ErrorW1 = f1.normalXYZ_ErrorW; const Vec4V raXn_targetVelW1 = f1.raXnI_targetVelW; const Vec4V rbXn_velMultiplierW1 = f1.rbXnI_velMultiplierW; const Vec3V normal0 = Vec3V_From_Vec4V(normalXYZ_ErrorW0); const Vec3V raXn0 = Vec3V_From_Vec4V(raXn_targetVelW0); const Vec3V rbXn0 = Vec3V_From_Vec4V(rbXn_velMultiplierW0); const Vec3V raXnI0 = f0.angDeltaVA; const Vec3V rbXnI0 = f0.angDeltaVB; const Vec3V normal1 = Vec3V_From_Vec4V(normalXYZ_ErrorW1); const Vec3V raXn1 = Vec3V_From_Vec4V(raXn_targetVelW1); const Vec3V rbXn1 = Vec3V_From_Vec4V(rbXn_velMultiplierW1); const Vec3V raXnI1 = f1.angDeltaVA; const Vec3V rbXnI1 = f1.angDeltaVB; const FloatV frictionScale = FLoad(f0.frictionScale); const FloatV biasScale = FLoad(f0.biasScale); const FloatV appliedForce0 = FLoad(f0.appliedForce); const FloatV velMultiplier0 = V4GetW(rbXn_velMultiplierW0); const FloatV targetVel0 = V4GetW(raXn_targetVelW0); const FloatV initialError0 = V4GetW(normalXYZ_ErrorW0); const FloatV appliedForce1 = FLoad(f1.appliedForce); const FloatV velMultiplier1 = V4GetW(rbXn_velMultiplierW1); const FloatV targetVel1 = V4GetW(raXn_targetVelW1); const FloatV initialError1 = V4GetW(normalXYZ_ErrorW1); const FloatV error0 = FAdd(initialError0, FNegScaleSub(targetVel0, elapsedTime, FAdd(FSub(V3Dot(raXn0, angDelta0), V3Dot(rbXn0, angDelta1)), V3Dot(normal0, relMotion)))); const FloatV error1 = FAdd(initialError1, FNegScaleSub(targetVel1, elapsedTime, FAdd(FSub(V3Dot(raXn1, angDelta0), V3Dot(rbXn1, angDelta1)), V3Dot(normal1, relMotion)))); const FloatV bias0 = FMul(error0, biasScale); const FloatV bias1 = FMul(error1, biasScale); const Vec3V v00 = V3MulAdd(linVel0, normal0, V3Mul(angVel0, raXn0)); const Vec3V v10 = V3MulAdd(linVel1, normal0, V3Mul(angVel1, rbXn0)); const FloatV normalVel0 = V3SumElems(V3Sub(v00, v10)); const Vec3V v01 = V3MulAdd(linVel0, normal1, V3Mul(angVel0, raXn1)); const Vec3V v11 = V3MulAdd(linVel1, normal1, V3Mul(angVel1, rbXn1)); const FloatV normalVel1 = V3SumElems(V3Sub(v01, v11)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp10 = FNegScaleSub(FSub(bias0, targetVel0), velMultiplier0, appliedForce0); const FloatV tmp11 = FNegScaleSub(FSub(bias1, targetVel1), velMultiplier1, appliedForce1); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse0 = FNegScaleSub(normalVel0, velMultiplier0, tmp10); const FloatV totalImpulse1 = FNegScaleSub(normalVel1, velMultiplier1, tmp11); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const FloatV totalImpulse = FSqrt(FAdd(FMul(totalImpulse0, totalImpulse0), FMul(totalImpulse1, totalImpulse1))); const BoolV clamp = FIsGrtr(totalImpulse, FMul(maxFrictionImpulse, frictionScale)); const FloatV totalClamped = FSel(clamp, FMin(FMul(maxDynFrictionImpulse, frictionScale), totalImpulse), totalImpulse); const FloatV ratio = FSel(FIsGrtr(totalImpulse, zero), FDiv(totalClamped, totalImpulse), zero); const FloatV newAppliedForce0 = FMul(ratio, totalImpulse0); const FloatV newAppliedForce1 = FMul(ratio, totalImpulse1); broken = BOr(broken, clamp); const FloatV deltaF0 = FSub(newAppliedForce0, appliedForce0); const FloatV deltaF1 = FSub(newAppliedForce1, appliedForce1); linVel0 = V3ScaleAdd(f0.linDeltaVA, deltaF0, V3ScaleAdd(f1.linDeltaVA, deltaF1, linVel0)); angVel0 = V3ScaleAdd(raXnI0, deltaF0, V3ScaleAdd(raXnI1, deltaF1, angVel0)); linVel1 = V3ScaleAdd(f0.linDeltaVB, deltaF0, V3ScaleAdd(f1.linDeltaVB, deltaF1, linVel1)); angVel1 = V3ScaleAdd(rbXnI0, deltaF0, V3ScaleAdd(rbXnI1, deltaF1, angVel1)); /*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/ li0 = V3ScaleAdd(normal0, deltaF0, V3ScaleAdd(normal1, deltaF1, li0)); ai0 = V3ScaleAdd(raXn0, deltaF0, V3ScaleAdd(raXn1, deltaF1, ai0)); li1 = V3ScaleAdd(normal0, deltaF0, V3ScaleAdd(normal1, deltaF1, li1)); ai1 = V3ScaleAdd(rbXn0, deltaF0, V3ScaleAdd(rbXn1, deltaF1, ai1)); f0.setAppliedForce(newAppliedForce0); f1.setAppliedForce(newAppliedForce1); } for (PxU32 i = numFrictionPairs; i<numFrictionConstr; i++) { SolverContactFrictionStepExt& f = frictions[i]; PxPrefetchLine(&frictions[i + 1]); const Vec4V raXn_targetVelW = f.raXnI_targetVelW; const Vec4V rbXn_velMultiplierW = f.rbXnI_velMultiplierW; const Vec3V raXn = Vec3V_From_Vec4V(raXn_targetVelW); const Vec3V rbXn = Vec3V_From_Vec4V(rbXn_velMultiplierW); const Vec3V raXnI = f.angDeltaVA; const Vec3V rbXnI = f.angDeltaVB; const FloatV frictionScale = FLoad(f.frictionScale); const FloatV appliedForce = FLoad(f.appliedForce); const FloatV velMultiplier = V4GetW(rbXn_velMultiplierW); const FloatV targetVel = V4GetW(raXn_targetVelW); const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse); //const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse); const Vec3V v0 = V3Mul(angVel0, raXn); const Vec3V v1 = V3Mul(angVel1, rbXn); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp1 = FNegScaleSub(FNeg(targetVel), velMultiplier, appliedForce); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const BoolV clamp = FIsGrtr(FAbs(totalImpulse), FMul(maxFrictionImpulse, frictionScale)); const FloatV totalClamped = FMin(FMul(maxDynFrictionImpulse, frictionScale), FMax(FMul(negMaxDynFrictionImpulse, frictionScale), totalImpulse)); const FloatV newAppliedForce = FSel(clamp, totalClamped, totalImpulse); broken = BOr(broken, clamp); FloatV deltaF = FSub(newAppliedForce, appliedForce); linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0); angVel0 = V3ScaleAdd(raXnI, deltaF, angVel0); linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1); angVel1 = V3ScaleAdd(rbXnI, deltaF, angVel1); /*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/ ai0 = V3ScaleAdd(raXn, deltaF, ai0); ai1 = V3ScaleAdd(rbXn, deltaF, ai1); f.setAppliedForce(newAppliedForce); } Store_From_BoolV(broken, &hdr->broken); } linImpulse0 = V3ScaleAdd(li0, hdr->getDominance0(), linImpulse0); angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0); linImpulse1 = V3NegScaleSub(li1, hdr->getDominance1(), linImpulse1); angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1); } PX_ASSERT(currPtr == last); } static void solveExtContactStep(const PxSolverConstraintDesc& desc, bool doFriction, PxReal minPenetration, PxReal elapsedTimeF32, SolverContext& cache) { Vec3V linVel0, angVel0, linVel1, angVel1; Vec3V linDelta0, angDelta0, linDelta1, angDelta1; Dy::FeatherstoneArticulation* artA = getArticulationA(desc); Dy::FeatherstoneArticulation* artB = getArticulationB(desc); if (artA == artB) { Cm::SpatialVectorV v0, v1; artA->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1); linVel0 = v0.linear; angVel0 = v0.angular; linVel1 = v1.linear; angVel1 = v1.angular; Cm::SpatialVectorV motionV0 = artA->getLinkMotionVector(desc.linkIndexA);// PxcFsGetMotionVector(*artA, desc.linkIndexA); Cm::SpatialVectorV motionV1 = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB); linDelta0 = motionV0.linear; angDelta0 = motionV0.angular; linDelta1 = motionV1.linear; angDelta1 = motionV1.angular; } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.tgsBodyA->linearVelocity); angVel0 = V3LoadA(desc.tgsBodyA->angularVelocity); linDelta0 = V3LoadA(desc.tgsBodyA->deltaLinDt); angDelta0 = V3LoadA(desc.tgsBodyA->deltaAngDt); } else { Cm::SpatialVectorV v = artA->pxcFsGetVelocity(desc.linkIndexA); Cm::SpatialVectorV deltaV = artA->getLinkMotionVector(desc.linkIndexA);// PxcFsGetMotionVector(*artA, desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; linDelta0 = deltaV.linear; angDelta0 = deltaV.angular; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.tgsBodyB->linearVelocity); angVel1 = V3LoadA(desc.tgsBodyB->angularVelocity); linDelta1 = V3LoadA(desc.tgsBodyB->deltaLinDt); angDelta1 = V3LoadA(desc.tgsBodyB->deltaAngDt); } else { Cm::SpatialVectorV v = artB->pxcFsGetVelocity(desc.linkIndexB); Cm::SpatialVectorV deltaV = artB->getLinkMotionVector(desc.linkIndexB);// PxcFsGetMotionVector(*artB, desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; linDelta1 = deltaV.linear; angDelta1 = deltaV.angular; } } /*PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel0, linVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(linVel1, linVel1))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel0, angVel0))); PX_ASSERT(FAllGrtr(FLoad(100.f * 100.f), V3Dot(angVel1, angVel1)));*/ Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero(); solveExtContactStep(desc, linVel0, linVel1, angVel0, angVel1, linDelta0, linDelta1, angDelta0, angDelta1, linImpulse0, linImpulse1, angImpulse0, angImpulse1, doFriction, minPenetration, elapsedTimeF32); if (artA == artB) { artA->pxcFsApplyImpulses(desc.linkIndexA, linImpulse0, angImpulse0, desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.tgsBodyA->linearVelocity); V3StoreA(angVel0, desc.tgsBodyA->angularVelocity); } else { artA->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.tgsBodyB->linearVelocity); V3StoreA(angVel1, desc.tgsBodyB->angularVelocity); } else { artB->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } } } void solveContactBlock(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(txInertias); PX_UNUSED(cache); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) solveContact(desc[i], true, minPenetration, elapsedTime); } void solve1DBlock(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(minPenetration); PX_UNUSED(cache); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) solve1DStep(desc[i], txInertias, elapsedTime); } void solveExtContactBlock(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(txInertias); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) solveExtContactStep(desc[i], true, minPenetration, elapsedTime, cache); } void solveExt1DBlock(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(minPenetration); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) solveExt1DStep(desc[i], elapsedTime, cache, txInertias); } void writeBackContact(DY_TGS_WRITEBACK_METHOD_PARAMS) { for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) writeBackContact(desc[i], cache); } void writeBack1D(DY_TGS_WRITEBACK_METHOD_PARAMS) { PX_UNUSED(cache); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) writeBack1D(desc[i]); } void solveConclude1DBlock(DY_TGS_CONCLUDE_METHOD_PARAMS) { PX_UNUSED(cache); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) { solve1DStep(desc[i], txInertias, elapsedTime); conclude1DStep(desc[i]); } } void solveConclude1DBlockExt(DY_TGS_CONCLUDE_METHOD_PARAMS) { for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) { solveExt1DStep(desc[i], elapsedTime, cache, txInertias); conclude1DStep(desc[i]); } } void solveConcludeContactBlock(DY_TGS_CONCLUDE_METHOD_PARAMS) { PX_UNUSED(txInertias); PX_UNUSED(cache); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) { solveContact(desc[i], true, -PX_MAX_F32, elapsedTime); concludeContact(desc[i]); } } void solveConcludeContactExtBlock(DY_TGS_CONCLUDE_METHOD_PARAMS) { PX_UNUSED(txInertias); for (PxU32 i = hdr.startIndex, endIdx = hdr.startIndex + hdr.stride; i < endIdx; ++i) { solveExtContactStep(desc[i], true, -PX_MAX_F32, elapsedTime, cache); concludeContact(desc[i]); } } } }
134,052
C++
38.884856
209
0.738572
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGS.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_H #define DY_TGS_H #include "foundation/PxPreprocessor.h" #include "foundation/PxSimpleTypes.h" namespace physx { struct PxConstraintBatchHeader; struct PxSolverConstraintDesc; struct PxTGSSolverBodyTxInertia; namespace Dy { struct SolverContext; // PT: using defines like we did in Gu (GU_OVERLAP_FUNC_PARAMS, etc). Additionally this gives a // convenient way to find the TGS solver methods, which are scattered in different files and use // the same function names as other functions (with a different signature). #define DY_TGS_SOLVE_METHOD_PARAMS const PxConstraintBatchHeader& hdr, const PxSolverConstraintDesc* desc, const PxTGSSolverBodyTxInertia* const txInertias, PxReal minPenetration, PxReal elapsedTime, SolverContext& cache #define DY_TGS_CONCLUDE_METHOD_PARAMS const PxConstraintBatchHeader& hdr, const PxSolverConstraintDesc* desc, const PxTGSSolverBodyTxInertia* const txInertias, PxReal elapsedTime, SolverContext& cache #define DY_TGS_WRITEBACK_METHOD_PARAMS const PxConstraintBatchHeader& hdr, const PxSolverConstraintDesc* desc, SolverContext* cache typedef void (*TGSSolveBlockMethod) (DY_TGS_SOLVE_METHOD_PARAMS); typedef void (*TGSSolveConcludeMethod) (DY_TGS_CONCLUDE_METHOD_PARAMS); typedef void (*TGSWriteBackMethod) (DY_TGS_WRITEBACK_METHOD_PARAMS); extern TGSSolveBlockMethod g_SolveTGSMethods[]; extern TGSSolveConcludeMethod g_SolveConcludeTGSMethods[]; extern TGSWriteBackMethod g_WritebackTGSMethods[]; } } #endif
3,206
C
49.109374
223
0.781659
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraints.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "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 "DySolverConstraintsShared.h" #include "DyFeatherstoneArticulation.h" #include "DyPGS.h" using namespace physx; using namespace Dy; //Port of scalar implementation to SIMD maths with some interleaving of instructions static void solve1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxSolverBody& b0 = *desc.bodyA; PxSolverBody& b1 = *desc.bodyB; PxU8* PX_RESTRICT bPtr = desc.constraint; if (bPtr == NULL) return; //PxU32 length = desc.constraintLength; const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr); SolverConstraint1D* PX_RESTRICT base = reinterpret_cast<SolverConstraint1D*>(bPtr + sizeof(SolverConstraint1DHeader)); Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); Vec3V angState1 = V3LoadA(b1.angularState); const FloatV invMass0 = FLoad(header->invMass0D0); const FloatV invMass1 = FLoad(header->invMass1D1); const FloatV invInertiaScale0 = FLoad(header->angularInvMassScale0); const FloatV invInertiaScale1 = FLoad(header->angularInvMassScale1); const PxU32 count = header->count; for(PxU32 i=0; i<count;++i, base++) { PxPrefetchLine(base+1); SolverConstraint1D& c = *base; const Vec3V clinVel0 = V3LoadA(c.lin0); const Vec3V clinVel1 = V3LoadA(c.lin1); const Vec3V cangVel0 = V3LoadA(c.ang0); const Vec3V cangVel1 = V3LoadA(c.ang1); const FloatV constant = FLoad(c.constant); const FloatV vMul = FLoad(c.velMultiplier); const FloatV iMul = FLoad(c.impulseMultiplier); const FloatV appliedForce = FLoad(c.appliedForce); //const FloatV targetVel = FLoad(c.targetVelocity); const FloatV maxImpulse = FLoad(c.maxImpulse); const FloatV minImpulse = FLoad(c.minImpulse); const Vec3V v0 = V3MulAdd(linVel0, clinVel0, V3Mul(angState0, cangVel0)); const Vec3V v1 = V3MulAdd(linVel1, clinVel1, V3Mul(angState1, cangVel1)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); const FloatV unclampedForce = FScaleAdd(iMul, appliedForce, FScaleAdd(vMul, normalVel, constant)); const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce))); const FloatV deltaF = FSub(clampedForce, appliedForce); FStore(clampedForce, &c.appliedForce); linVel0 = V3ScaleAdd(clinVel0, FMul(deltaF, invMass0), linVel0); linVel1 = V3NegScaleSub(clinVel1, FMul(deltaF, invMass1), linVel1); angState0 = V3ScaleAdd(cangVel0, FMul(deltaF, invInertiaScale0), angState0); //This should be negScaleSub but invInertiaScale1 is negated already angState1 = V3ScaleAdd(cangVel1, FMul(deltaF, invInertiaScale1), angState1); } V3StoreA(linVel0, b0.linearVelocity); V3StoreA(angState0, b0.angularState); V3StoreA(linVel1, b1.linearVelocity); V3StoreA(angState1, b1.angularState); PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularState.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularState.isFinite()); } namespace physx { namespace Dy { void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint); if (header == NULL) return; PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeader); const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D); const PxU32 count = header->count; for(PxU32 i=0; i<count; i++) { SolverConstraint1D& c = *reinterpret_cast<SolverConstraint1D*>(base); c.constant = c.unbiasedConstant; base += stride; } //The final row may no longer be at the end of the reserved memory range. This can happen if there were degenerate //constraint rows with articulations, in which case the rows are skipped. //PX_ASSERT(desc.constraint + getConstraintLength(desc) == base); } // ============================================================== static void solveContact(const PxSolverConstraintDesc& desc, SolverContext& cache) { PxSolverBody& b0 = *desc.bodyA; PxSolverBody& b1 = *desc.bodyB; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); Vec3V angState1 = V3LoadA(b1.angularState); const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; while(currPtr < last) { SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr); currPtr += sizeof(SolverContactHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPoint); PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr); currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFriction); const FloatV invMassA = FLoad(hdr->invMass0); const FloatV invMassB = FLoad(hdr->invMass1); const FloatV angDom0 = FLoad(hdr->angDom0); const FloatV angDom1 = FLoad(hdr->angDom1); const Vec3V contactNormal = Vec3V_From_Vec4V_WUndefined(hdr->normal_minAppliedImpulseForFrictionW); const FloatV accumulatedNormalImpulse = solveDynamicContacts(contacts, numNormalConstr, contactNormal, invMassA, invMassB, angDom0, angDom1, linVel0, angState0, linVel1, angState1, forceBuffer); if(cache.doFriction && numFrictionConstr) { const FloatV staticFrictionCof = hdr->getStaticFriction(); const FloatV dynamicFrictionCof = hdr->getDynamicFriction(); const FloatV maxFrictionImpulse = FMul(staticFrictionCof, accumulatedNormalImpulse); const FloatV maxDynFrictionImpulse = FMul(dynamicFrictionCof, accumulatedNormalImpulse); const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse); BoolV broken = BFFFF(); if(cache.writeBackIteration) PxPrefetchLine(hdr->frictionBrokenWritebackByte); for(PxU32 i=0;i<numFrictionConstr;i++) { SolverContactFriction& f = frictions[i]; PxPrefetchLine(&frictions[i],128); const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW; const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW; const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW; const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW); const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW); const Vec3V rbXn = Vec3V_From_Vec4V(rbXnXYZ_biasW); const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW); const FloatV bias = V4GetW(rbXnXYZ_biasW); const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); const Vec3V delLinVel0 = V3Scale(normal, invMassA); const Vec3V delLinVel1 = V3Scale(normal, invMassB); const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angState0, raXn)); const Vec3V v1 = V3MulAdd(linVel1, normal, V3Mul(angState1, rbXn)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel), velMultiplier, appliedForce); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const BoolV clamp = FIsGrtr(FAbs(totalImpulse), maxFrictionImpulse); const FloatV totalClamped = FMin(maxDynFrictionImpulse, FMax(negMaxDynFrictionImpulse, totalImpulse)); const FloatV newAppliedForce = FSel(clamp, totalClamped,totalImpulse); broken = BOr(broken, clamp); FloatV deltaF = FSub(newAppliedForce, appliedForce); // we could get rid of the stall here by calculating and clamping delta separately, but // the complexity isn't really worth it. linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0); linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1); angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0); angState1 = V3NegScaleSub(rbXn, FMul(deltaF, angDom1), angState1); f.setAppliedForce(newAppliedForce); } Store_From_BoolV(broken, &hdr->broken); } } PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularState.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularState.isFinite()); // Write back V3StoreU(linVel0, b0.linearVelocity); V3StoreU(linVel1, b1.linearVelocity); V3StoreU(angState0, b0.angularState); V3StoreU(angState1, b1.angularState); PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularState.isFinite()); PX_ASSERT(b1.linearVelocity.isFinite()); PX_ASSERT(b1.angularState.isFinite()); PX_ASSERT(currPtr == last); } static void solveContact_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache) { PxSolverBody& b0 = *desc.bodyA; //PxSolverBody& b1 = *desc.bodyB; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); const PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; while(currPtr < last) { SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr); currPtr += sizeof(SolverContactHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr); //PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPoint); PxF32* forceBuffer = reinterpret_cast<PxF32*>(currPtr); currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFriction); const FloatV invMassA = FLoad(hdr->invMass0); const Vec3V contactNormal = Vec3V_From_Vec4V_WUndefined(hdr->normal_minAppliedImpulseForFrictionW); const FloatV angDom0 = FLoad(hdr->angDom0); const FloatV accumulatedNormalImpulse = solveStaticContacts(contacts, numNormalConstr, contactNormal, invMassA, angDom0, linVel0, angState0, forceBuffer); if(cache.doFriction && numFrictionConstr) { const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse); const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse); BoolV broken = BFFFF(); if(cache.writeBackIteration) PxPrefetchLine(hdr->frictionBrokenWritebackByte); for(PxU32 i=0;i<numFrictionConstr;i++) { SolverContactFriction& f = frictions[i]; PxPrefetchLine(&frictions[i],128); const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW; const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW; const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW; const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW); const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW); const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW); const FloatV bias = V4GetW(rbXnXYZ_biasW); const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse); const Vec3V delLinVel0 = V3Scale(normal, invMassA); //const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse); const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angState0, raXn)); const FloatV normalVel = V3SumElems(v0); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel),velMultiplier,appliedForce); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const BoolV clamp = FIsGrtr(FAbs(totalImpulse), maxFrictionImpulse); const FloatV totalClamped = FMin(maxDynFrictionImpulse, FMax(negMaxDynFrictionImpulse, totalImpulse)); broken = BOr(broken, clamp); const FloatV newAppliedForce = FSel(clamp, totalClamped,totalImpulse); FloatV deltaF = FSub(newAppliedForce, appliedForce); // we could get rid of the stall here by calculating and clamping delta separately, but // the complexity isn't really worth it. linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0); angState0 = V3ScaleAdd(raXn, FMul(deltaF, angDom0), angState0); f.setAppliedForce(newAppliedForce); } Store_From_BoolV(broken, &hdr->broken); } } PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularState.isFinite()); // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(angState0, b0.angularState); PX_ASSERT(b0.linearVelocity.isFinite()); PX_ASSERT(b0.angularState.isFinite()); PX_ASSERT(currPtr == last); } void concludeContact(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxU8* PX_RESTRICT cPtr = desc.constraint; const FloatV zero = FZero(); PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); while(cPtr < last) { const SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeader*>(cPtr); cPtr += sizeof(SolverContactHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; //if(cPtr < last) //PxPrefetchLine(cPtr, 512); PxPrefetchLine(cPtr,128); PxPrefetchLine(cPtr,256); PxPrefetchLine(cPtr,384); const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt) : sizeof(SolverContactPoint); for(PxU32 i=0;i<numNormalConstr;i++) { SolverContactPoint *c = reinterpret_cast<SolverContactPoint*>(cPtr); cPtr += pointStride; //c->scaledBias = PxMin(c->scaledBias, 0.f); c->biasedErr = c->unbiasedErr; } cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); //Jump over force buffers const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionExt) : sizeof(SolverContactFriction); for(PxU32 i=0;i<numFrictionConstr;i++) { SolverContactFriction *f = reinterpret_cast<SolverContactFriction*>(cPtr); cPtr += frictionStride; f->setBias(zero); } } PX_ASSERT(cPtr == last); } void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext& cache, PxSolverBodyData& bd0, PxSolverBodyData& bd1) { PxReal normalForce = 0; PxU8* PX_RESTRICT cPtr = desc.constraint; PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack); PxU8* PX_RESTRICT last = desc.constraint + getConstraintLength(desc); bool forceThreshold = false; while(cPtr < last) { const SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactHeader*>(cPtr); cPtr += sizeof(SolverContactHeader); forceThreshold = hdr->flags & SolverContactHeader::eHAS_FORCE_THRESHOLDS; const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; //if(cPtr < last) PxPrefetchLine(cPtr, 256); PxPrefetchLine(cPtr, 384); const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt) : sizeof(SolverContactPoint); cPtr += pointStride * numNormalConstr; PxF32* forceBuffer = reinterpret_cast<PxF32*>(cPtr); cPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); if(vForceWriteback!=NULL) { for(PxU32 i=0; i<numNormalConstr; i++) { PxReal appliedForce = forceBuffer[i]; *vForceWriteback++ = appliedForce; normalForce += appliedForce; } } const PxU32 frictionStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactFrictionExt) : sizeof(SolverContactFriction); if(hdr->broken && hdr->frictionBrokenWritebackByte != NULL) { *hdr->frictionBrokenWritebackByte = 1; } cPtr += frictionStride * numFrictionConstr; } PX_ASSERT(cPtr == last); if(forceThreshold && desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY && normalForce !=0 && (bd0.reportThreshold < PX_MAX_REAL || bd1.reportThreshold < PX_MAX_REAL)) { ThresholdStreamElement elt; elt.normalForce = normalForce; elt.threshold = PxMin<float>(bd0.reportThreshold, bd1.reportThreshold); elt.nodeIndexA = PxNodeIndex(bd0.nodeIndex); elt.nodeIndexB = PxNodeIndex(bd1.nodeIndex); elt.shapeInteraction = reinterpret_cast<const SolverContactHeader*>(desc.constraint)->shapeInteraction; PxOrder(elt.nodeIndexA, elt.nodeIndexB); PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB); PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength); cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt; } } // adjust from CoM to joint void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&, PxSolverBodyData&, PxSolverBodyData&) { ConstraintWriteback* writeback = reinterpret_cast<ConstraintWriteback*>(desc.writeBack); if(writeback) { SolverConstraint1DHeader* header = reinterpret_cast<SolverConstraint1DHeader*>(desc.constraint); PxU8* base = desc.constraint + sizeof(SolverConstraint1DHeader); const PxU32 stride = header->type == DY_SC_TYPE_EXT_1D ? sizeof(SolverConstraint1DExt) : sizeof(SolverConstraint1D); PxVec3 lin(0), ang(0); const PxU32 count = header->count; for(PxU32 i=0; i<count; i++) { const SolverConstraint1D* c = reinterpret_cast<SolverConstraint1D*>(base); if(c->flags & DY_SC_FLAG_OUTPUT_FORCE) { lin += c->lin0 * c->appliedForce; ang += c->ang0Writeback * c->appliedForce; } base += stride; } ang -= header->body0WorldOffset.cross(lin); writeback->linearImpulse = lin; writeback->angularImpulse = ang; writeback->broken = header->breakable ? PxU32(lin.magnitude()>header->linBreakImpulse || ang.magnitude()>header->angBreakImpulse) : 0; //If we had degenerate rows, the final constraint row may not end at getConstraintLength bytes from the base anymore //PX_ASSERT(desc.constraint + getConstraintLength(desc) == base); } } void solve1DBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solve1D(desc[a-1], cache); } solve1D(desc[constraintCount-1], cache); } void solve1DConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solve1D(desc[a-1], cache); conclude1D(desc[a-1], cache); } solve1D(desc[constraintCount-1], cache); conclude1D(desc[constraintCount-1], cache); } void solve1DBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex]; solve1D(desc[a-1], cache); writeBack1D(desc[a-1], cache, bd0, bd1); } PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex]; solve1D(desc[constraintCount-1], cache); writeBack1D(desc[constraintCount-1], cache, bd0, bd1); } void writeBack1DBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex]; writeBack1D(desc[a-1], cache, bd0, bd1); } PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex]; writeBack1D(desc[constraintCount-1], cache, bd0, bd1); } void solveContactBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solveContact(desc[a-1], cache); } solveContact(desc[constraintCount-1], cache); } void solveContactConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solveContact(desc[a-1], cache); concludeContact(desc[a-1], cache); } solveContact(desc[constraintCount-1], cache); concludeContact(desc[constraintCount-1], cache); } void solveContactBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex]; solveContact(desc[a-1], cache); writeBackContact(desc[a-1], cache, bd0, bd1); } PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex]; solveContact(desc[constraintCount-1], cache); writeBackContact(desc[constraintCount-1], 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 solveContact_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solveContact_BStatic(desc[a-1], cache); } solveContact_BStatic(desc[constraintCount-1], cache); } void solveContact_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); solveContact_BStatic(desc[a-1], cache); concludeContact(desc[a-1], cache); } solveContact_BStatic(desc[constraintCount-1], cache); concludeContact(desc[constraintCount-1], cache); } void solveContact_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 1; a < constraintCount; ++a) { PxPrefetchLine(desc[a].constraint); PxPrefetchLine(desc[a].constraint, 128); PxPrefetchLine(desc[a].constraint, 256); PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a-1].bodyBDataIndex]; solveContact_BStatic(desc[a-1], cache); writeBackContact(desc[a-1], cache, bd0, bd1); } PxSolverBodyData& bd0 = cache.solverBodyArray[desc[constraintCount-1].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[constraintCount-1].bodyBDataIndex]; solveContact_BStatic(desc[constraintCount-1], cache); writeBackContact(desc[constraintCount-1], cache, bd0, bd1); if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4)) { //Not enough space to write 4 more thresholds back! //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 clearExt1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxU8* PX_RESTRICT bPtr = desc.constraint; const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr); SolverConstraint1DExt* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExt*>(bPtr + sizeof(SolverConstraint1DHeader)); const PxU32 count = header->count; for (PxU32 i=0; i<count; ++i, base++) { base->appliedForce = 0.f; } } void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& li0, Vec3V& li1, Vec3V& ai0, Vec3V& ai1) { PxU8* PX_RESTRICT bPtr = desc.constraint; const SolverConstraint1DHeader* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeader*>(bPtr); SolverConstraint1DExt* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DExt*>(bPtr + sizeof(SolverConstraint1DHeader)); const PxU32 count = header->count; for (PxU32 i=0; i<count; ++i, base++) { PxPrefetchLine(base + 1); const Vec4V lin0XYZ_constantW = V4LoadA(&base->lin0.x); const Vec4V lin1XYZ_unbiasedConstantW = V4LoadA(&base->lin1.x); const Vec4V ang0XYZ_velMultiplierW = V4LoadA(&base->ang0.x); const Vec4V ang1XYZ_impulseMultiplierW = V4LoadA(&base->ang1.x); const Vec4V minImpulseX_maxImpulseY_appliedForceZ = V4LoadA(&base->minImpulse); const Vec3V lin0 = Vec3V_From_Vec4V(lin0XYZ_constantW); FloatV constant = V4GetW(lin0XYZ_constantW); const Vec3V lin1 = Vec3V_From_Vec4V(lin1XYZ_unbiasedConstantW); const Vec3V ang0 = Vec3V_From_Vec4V(ang0XYZ_velMultiplierW); FloatV vMul = V4GetW(ang0XYZ_velMultiplierW); const Vec3V ang1 = Vec3V_From_Vec4V(ang1XYZ_impulseMultiplierW); FloatV iMul = V4GetW(ang1XYZ_impulseMultiplierW); const FloatV minImpulse = V4GetX(minImpulseX_maxImpulseY_appliedForceZ); const FloatV maxImpulse = V4GetY(minImpulseX_maxImpulseY_appliedForceZ); const FloatV appliedForce = V4GetZ(minImpulseX_maxImpulseY_appliedForceZ); const Vec3V v0 = V3MulAdd(linVel0, lin0, V3Mul(angVel0, ang0)); const Vec3V v1 = V3MulAdd(linVel1, lin1, V3Mul(angVel1, ang1)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); const FloatV unclampedForce = FScaleAdd(iMul, appliedForce, FScaleAdd(vMul, normalVel, constant)); const FloatV clampedForce = FMin(maxImpulse, (FMax(minImpulse, unclampedForce))); const FloatV deltaF = FSub(clampedForce, appliedForce); FStore(clampedForce, &base->appliedForce); li0 = V3ScaleAdd(lin0, deltaF, li0); ai0 = V3ScaleAdd(ang0, deltaF, ai0); li1 = V3ScaleAdd(lin1, deltaF, li1); ai1 = V3ScaleAdd(ang1, deltaF, ai1); linVel0 = V3ScaleAdd(base->deltaVA.linear, deltaF, linVel0); angVel0 = V3ScaleAdd(base->deltaVA.angular, deltaF, angVel0); linVel1 = V3ScaleAdd(base->deltaVB.linear, deltaF, linVel1); angVel1 = V3ScaleAdd(base->deltaVB.angular, deltaF, angVel1); #if 0 PxVec3 lv0, lv1, av0, av1; V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1); V3StoreU(angVel0, av0); V3StoreU(angVel1, av1); PX_ASSERT(lv0.magnitude() < 30.f); PX_ASSERT(lv1.magnitude() < 30.f); PX_ASSERT(av0.magnitude() < 30.f); PX_ASSERT(av1.magnitude() < 30.f); #endif } li0 = V3Scale(li0, FLoad(header->linearInvMassScale0)); li1 = V3Scale(li1, FLoad(header->linearInvMassScale1)); ai0 = V3Scale(ai0, FLoad(header->angularInvMassScale0)); ai1 = V3Scale(ai1, FLoad(header->angularInvMassScale1)); } //Port of scalar implementation to SIMD maths with some interleaving of instructions void solveExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache) { //PxU32 length = desc.constraintLength; Vec3V linVel0, angVel0, linVel1, angVel1; if (desc.articulationA == desc.articulationB) { Cm::SpatialVectorV v0, v1; getArticulationA(desc)->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1); linVel0 = v0.linear; angVel0 = v0.angular; linVel1 = v1.linear; angVel1 = v1.angular; } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.bodyA->linearVelocity); angVel0 = V3LoadA(desc.bodyA->angularState); } else { Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.bodyB->linearVelocity); angVel1 = V3LoadA(desc.bodyB->angularState); } else { Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; } } Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1); if (desc.articulationA == desc.articulationB) { getArticulationA(desc)->pxcFsApplyImpulses(desc.linkIndexA, li0, ai0, desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV); } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.bodyA->linearVelocity); V3StoreA(angVel0, desc.bodyA->angularState); } else { getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, li0, ai0, cache.Z, cache.deltaV); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.bodyB->linearVelocity); V3StoreA(angVel1, desc.bodyB->angularState); } else { getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, li1, ai1, cache.Z, cache.deltaV); } } } 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) { FloatV accumulatedNormalImpulse = FZero(); for (PxU32 i = 0; i<nbContactPoints; i++) { SolverContactPointExt& c = contacts[i]; PxPrefetchLine(&contacts[i + 1]); const Vec3V raXn = Vec3V_From_Vec4V(c.raXn_velMultiplierW); const Vec3V rbXn = Vec3V_From_Vec4V(c.rbXn_maxImpulseW); const FloatV appliedForce = FLoad(appliedForceBuffer[i]); const FloatV velMultiplier = c.getVelMultiplier(); /*const FloatV targetVel = c.getTargetVelocity(); const FloatV scaledBias = c.getScaledBias();*/ //Compute the normal velocity of the constraint. Vec3V v = V3MulAdd(linVel0, contactNormal, V3Mul(angVel0, raXn)); v = V3Sub(v, V3MulAdd(linVel1, contactNormal, V3Mul(angVel1, rbXn))); const FloatV normalVel = V3SumElems(v); const FloatV biasedErr = c.getBiasedErr();//FNeg(scaledBias); // 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 = FMin(FAdd(FMul(c.getImpulseMultiplier(), appliedForce), _deltaF), c.getMaxImpulse()); const FloatV deltaF = FSub(newForce, appliedForce); linVel0 = V3ScaleAdd(c.linDeltaVA, deltaF, linVel0); angVel0 = V3ScaleAdd(c.angDeltaVA, deltaF, angVel0); linVel1 = V3ScaleAdd(c.linDeltaVB, deltaF, linVel1); angVel1 = V3ScaleAdd(c.angDeltaVB, deltaF, angVel1); li0 = V3ScaleAdd(contactNormal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0); li1 = V3ScaleAdd(contactNormal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1); const FloatV newAppliedForce = FAdd(appliedForce, deltaF); FStore(newAppliedForce, &appliedForceBuffer[i]); accumulatedNormalImpulse = FAdd(accumulatedNormalImpulse, newAppliedForce); #if 0 PxVec3 lv0, lv1, av0, av1; V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1); V3StoreU(angVel0, av0); V3StoreU(angVel1, av1); PX_ASSERT(lv0.magnitude() < 30.f); PX_ASSERT(lv1.magnitude() < 30.f); PX_ASSERT(av0.magnitude() < 30.f); PX_ASSERT(av1.magnitude() < 30.f); #endif } return accumulatedNormalImpulse; } void solveExtContact(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool doFriction) { const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16 * 16; //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; while (currPtr < last) { SolverContactHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeader*>(currPtr); currPtr += sizeof(SolverContactHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; SolverContactPointExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointExt*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPointExt); PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(currPtr); currPtr += sizeof(PxF32) * ((numNormalConstr + 3) & (~3)); SolverContactFrictionExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionExt*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFrictionExt); Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); const Vec3V contactNormal = Vec3V_From_Vec4V(hdr->normal_minAppliedImpulseForFrictionW); const FloatV minNorImpulse = V4GetW(hdr->normal_minAppliedImpulseForFrictionW); const FloatV accumulatedNormalImpulse = FMax(solveExtContacts(contacts, numNormalConstr, contactNormal, linVel0, angVel0, linVel1, angVel1, li0, ai0, li1, ai1, appliedForceBuffer), minNorImpulse); if (doFriction && numFrictionConstr) { PxPrefetchLine(frictions); const FloatV maxFrictionImpulse = FMul(hdr->getStaticFriction(), accumulatedNormalImpulse); const FloatV maxDynFrictionImpulse = FMul(hdr->getDynamicFriction(), accumulatedNormalImpulse); BoolV broken = BFFFF(); for (PxU32 i = 0; i<numFrictionConstr; i++) { SolverContactFrictionExt& f = frictions[i]; PxPrefetchLine(&frictions[i + 1]); const Vec4V normalXYZ_appliedForceW = f.normalXYZ_appliedForceW; const Vec4V raXnXYZ_velMultiplierW = f.raXnXYZ_velMultiplierW; const Vec4V rbXnXYZ_biasW = f.rbXnXYZ_biasW; const Vec3V normal = Vec3V_From_Vec4V(normalXYZ_appliedForceW); /*const Vec3V normal0 = V3Scale(normal, sqrtInvMass0); const Vec3V normal1 = V3Scale(normal, sqrtInvMass1);*/ const Vec3V raXn = Vec3V_From_Vec4V(raXnXYZ_velMultiplierW); const Vec3V rbXn = Vec3V_From_Vec4V(rbXnXYZ_biasW); const FloatV appliedForce = V4GetW(normalXYZ_appliedForceW); const FloatV bias = V4GetW(rbXnXYZ_biasW); const FloatV velMultiplier = V4GetW(raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); const FloatV negMaxDynFrictionImpulse = FNeg(maxDynFrictionImpulse); const FloatV negMaxFrictionImpulse = FNeg(maxFrictionImpulse); const Vec3V v0 = V3MulAdd(linVel0, normal, V3Mul(angVel0, raXn)); const Vec3V v1 = V3MulAdd(linVel1, normal, V3Mul(angVel1, rbXn)); const FloatV normalVel = V3SumElems(V3Sub(v0, v1)); // appliedForce -bias * velMultiplier - a hoisted part of the total impulse computation const FloatV tmp1 = FNegScaleSub(FSub(bias, targetVel), velMultiplier, appliedForce); // Algorithm: // if abs(appliedForce + deltaF) > maxFrictionImpulse // clamp newAppliedForce + deltaF to [-maxDynFrictionImpulse, maxDynFrictionImpulse] // (i.e. clamp deltaF to [-maxDynFrictionImpulse-appliedForce, maxDynFrictionImpulse-appliedForce] // set broken flag to true || broken flag // FloatV deltaF = FMul(FAdd(bias, normalVel), minusVelMultiplier); // FloatV potentialSumF = FAdd(appliedForce, deltaF); const FloatV totalImpulse = FNegScaleSub(normalVel, velMultiplier, tmp1); // On XBox this clamping code uses the vector simple pipe rather than vector float, // which eliminates a lot of stall cycles const BoolV clampLow = FIsGrtr(negMaxFrictionImpulse, totalImpulse); const BoolV clampHigh = FIsGrtr(totalImpulse, maxFrictionImpulse); const FloatV totalClampedLow = FMax(negMaxDynFrictionImpulse, totalImpulse); const FloatV totalClampedHigh = FMin(maxDynFrictionImpulse, totalImpulse); const FloatV newAppliedForce = FSel(clampLow, totalClampedLow, FSel(clampHigh, totalClampedHigh, totalImpulse)); broken = BOr(broken, BOr(clampLow, clampHigh)); FloatV deltaF = FSub(newAppliedForce, appliedForce); linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0); angVel0 = V3ScaleAdd(f.angDeltaVA, deltaF, angVel0); linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1); angVel1 = V3ScaleAdd(f.angDeltaVB, deltaF, angVel1); li0 = V3ScaleAdd(normal, deltaF, li0); ai0 = V3ScaleAdd(raXn, deltaF, ai0); li1 = V3ScaleAdd(normal, deltaF, li1); ai1 = V3ScaleAdd(rbXn, deltaF, ai1); #if 0 PxVec3 lv0, lv1, av0, av1; V3StoreU(linVel0, lv0); V3StoreU(linVel1, lv1); V3StoreU(angVel0, av0); V3StoreU(angVel1, av1); PX_ASSERT(lv0.magnitude() < 30.f); PX_ASSERT(lv1.magnitude() < 30.f); PX_ASSERT(av0.magnitude() < 30.f); PX_ASSERT(av1.magnitude() < 30.f); #endif f.setAppliedForce(newAppliedForce); } Store_From_BoolV(broken, &hdr->broken); } linImpulse0 = V3ScaleAdd(li0, hdr->getDominance0(), linImpulse0); angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0); linImpulse1 = V3NegScaleSub(li1, hdr->getDominance1(), linImpulse1); angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1); /*linImpulse0 = V3ScaleAdd(li0, FZero(), linImpulse0); angImpulse0 = V3ScaleAdd(ai0, FZero(), angImpulse0); linImpulse1 = V3NegScaleSub(li1, FZero(), linImpulse1); angImpulse1 = V3NegScaleSub(ai1, FZero(), angImpulse1);*/ } } static void solveExtContact(const PxSolverConstraintDesc& desc, SolverContext& cache) { Vec3V linVel0, angVel0, linVel1, angVel1; if (desc.articulationA == desc.articulationB) { Cm::SpatialVectorV v0, v1; getArticulationA(desc)->pxcFsGetVelocities(desc.linkIndexA, desc.linkIndexB, v0, v1); linVel0 = v0.linear; angVel0 = v0.angular; linVel1 = v1.linear; angVel1 = v1.angular; } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.bodyA->linearVelocity); angVel0 = V3LoadA(desc.bodyA->angularState); } else { Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.bodyB->linearVelocity); angVel1 = V3LoadA(desc.bodyB->angularState); } else { Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; } } Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero(); //Vec3V origLin0 = linVel0, origAng0 = angVel0, origLin1 = linVel1, origAng1 = angVel1; solveExtContact(desc, linVel0, linVel1, angVel0, angVel1, linImpulse0, linImpulse1, angImpulse0, angImpulse1, cache.doFriction); if (desc.articulationA == desc.articulationB) { getArticulationA(desc)->pxcFsApplyImpulses(desc.linkIndexA, linImpulse0, angImpulse0, desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } else { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.bodyA->linearVelocity); V3StoreA(angVel0, desc.bodyA->angularState); } else { getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.bodyB->linearVelocity); V3StoreA(angVel1, desc.bodyB->angularState); } else { getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } } } void solveExtContactBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveExtContact(desc[a], cache); } void solveExtContactConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { solveExtContact(desc[a], cache); concludeContact(desc[a], cache); } } void solveExtContactBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex]; solveExtContact(desc[a], cache); writeBackContact(desc[a], cache, bd0, bd1); } if(cache.mThresholdStreamIndex > 0) { //Not enough space to write 4 more thresholds back! //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 solveExt1DBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveExt1D(desc[a], cache); } void solveExt1DConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { solveExt1D(desc[a], cache); conclude1D(desc[a], cache); } } void solveExt1DBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex]; solveExt1D(desc[a], cache); writeBack1D(desc[a], cache, bd0, bd1); } } // PT: not sure what happened but the following ones weren't actually used /*void ext1DBlockWriteBack(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache) { for(PxU32 a = 0; a < constraintCount; ++a) { PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc[a].bodyBDataIndex]; writeBack1D(desc[a], cache, bd0, bd1); } } void solveConcludeExtContact(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveExtContact(desc, cache); concludeContact(desc, cache); } void solveConcludeExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveExt1D(desc, cache); conclude1D(desc, cache); } void solveConclude1D(const PxSolverConstraintDesc& desc, SolverContext& cache) { solve1D(desc, cache); conclude1D(desc, cache); } void solveConcludeContact(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveContact(desc, cache); concludeContact(desc, cache); } void solveConcludeContact_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveContact_BStatic(desc, cache); concludeContact(desc, cache); }*/ } }
46,753
C++
35.87224
146
0.740444
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneForwardDynamic.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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/PxMathUtils.h" #include "CmConeLimitHelper.h" #include "DySolverConstraint1D.h" #include "DyFeatherstoneArticulation.h" #include "PxsRigidBody.h" #include "PxcConstraintBlockStream.h" #include "DyArticulationContactPrep.h" #include "DyDynamics.h" #include "DyArticulationPImpl.h" #include "DyFeatherstoneArticulationLink.h" #include "DyFeatherstoneArticulationJointData.h" #include "common/PxProfileZone.h" #include <stdio.h> #ifdef _MSC_VER #pragma warning(disable:4505) #endif namespace physx { namespace Dy { void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool computeSpatialForces); #if (FEATHERSTONE_DEBUG && (PX_DEBUG || PX_CHECKED)) static bool isSpatialVectorEqual(Cm::SpatialVectorF& t0, Cm::SpatialVectorF& t1) { float eps = 0.0001f; bool e0 = PxAbs(t0.top.x - t1.top.x) < eps && PxAbs(t0.top.y - t1.top.y) < eps && PxAbs(t0.top.z - t1.top.z) < eps; bool e1 = PxAbs(t0.bottom.x - t1.bottom.x) < eps && PxAbs(t0.bottom.y - t1.bottom.y) < eps && PxAbs(t0.bottom.z - t1.bottom.z) < eps; return e0 && e1; } static bool isSpatialVectorZero(Cm::SpatialVectorF& t0) { float eps = 0.000001f; const bool c0 = PxAbs(t0.top.x) < eps && PxAbs(t0.top.y) < eps && PxAbs(t0.top.z) < eps; const bool c1 = PxAbs(t0.bottom.x) < eps && PxAbs(t0.bottom.y) < eps && PxAbs(t0.bottom.z) < eps; return c0 && c1; } #endif #if FEATHERSTONE_DEBUG static inline PxMat33 Outer(const PxVec3& a, const PxVec3& b) { return PxMat33(a * b.x, a * b.y, a * b.z); } #endif SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia_ZA_ZIc (const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs, const Cm::UnAlignedSpatialVector* jointMotionMatricesW, const Cm::SpatialVectorF* jointISW, const PxReal* jointTargetArmatures, const PxReal* jointExternalForces, const SpatialMatrix& linkArticulatedInertiaW, const Cm::SpatialVectorF& linkZExtW, const Cm::SpatialVectorF& linkZIntIcW, InvStIs& linkInvStISW, Cm::SpatialVectorF* jointDofISInvStISW, PxReal* jointDofMinusStZExtW, PxReal* jointDofQStZIntIcW, Cm::SpatialVectorF& deltaZAExtParent, Cm::SpatialVectorF& deltaZAIntIcParent) { deltaZAExtParent = linkZExtW; deltaZAIntIcParent = linkZIntIcW; // The goal is to propagate the articulated z.a force of a child link to the articulated z.a. force of its parent link. // We will compute a term that can be added to the articulated z.a. force of the parent link. // This function only references the child link. // Mirtich uses the notation i for the child and i-1 for the parent. // We have a more general configuration that allows a parent to have multiple children but in what follows "i" shall refer to the // child and "i-1" to the parent. // Another goal is to propagate the articulated spatial inertia from the child link to the parent link. // We will compute a term that can be added to the articulated spatial inertia of the parent link. // The Mirtich equivalent is: // I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A] //The term that is to be added to the parent link has the Mirtich formulation: // Delta_Z_i-1 = (Z_i^A + I_i^A * c_i) + [I_i^A * s_i]*[Q_i - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i] //We do not have a single articulated z.a. force as outlined in Mirtich. //Instead we have a term that accounts for external forces and a term that accounts for internal forces. //We can generalise the Mirtich formulate to account for internal and external terms: // Delta_ZExt_i-1 = ZAExt_i + [I_i^A * s_i] * [-s_i^T * ZAExt_i]/[s_i^T * I_i^A * s_i] // Delta_ZInt_i-1 = ZAInt_i + I_i^A * c_i + [I_i^A * s_i] * [Q_i - s_i^T * (ZAInt_i + I_i^A * c_i)]/[s_i^T * I_i^A * s_i] // Delta_Z_i-1 = Delta_ZExt_i-1 + Delta_ZInt_i-1 //We have function input arguments ZExt and ZIntIc. //In Mirtich terms these are ZAExt_i and ZAInt_i + I_i^A * c_i. //Using the function arguments here we have: // Delta_ZExt_i-1 = ZAExt + [I_i^A * s_i] * [-s_i^T * ZAExt]/[s_i^T * I_i^A * s_i] // Delta_ZInt_i-1 = ZAIntIc + [I_i^A * s_i] * [Q_i - s_i^T * ZAIntIc]/[s_i^T * I_i^A * s_i] //Isn't it odd that we add Q_i to the internal term rather than the external term? SpatialMatrix spatialInertia; switch (jointType) { case PxArticulationJointType::ePRISMATIC: case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[0]; #if FEATHERSTONE_DEBUG PxVec3 u = (jointType == PxArticulationJointType::ePRISMATIC) ? sa.bottom : sa.top; PxMat33 armatureV = Outer(u, u) * jointTarget.armature[0]; const PxReal armature = u.dot(armatureV * u); #endif const Cm::SpatialVectorF& Is = jointISW[0]; //Mirtich equivalent: 1/[s_i^T * I_i^A * s_i] PxReal invStIS; { const PxReal stIs = (sa.innerProduct(Is) + jointTargetArmatures[0]); invStIS = ((stIs > 0.f) ? (1.f / stIs) : 0.f); } linkInvStISW.invStIs[0][0] = invStIS; //Mirtich equivalent: [I_i^A * s_i]/[s_i^T * I_i^A * s_i] Cm::SpatialVectorF isID = Is * invStIS; jointDofISInvStISW[0] = isID; //(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0] //Cm::SpatialVector stI1(Is1.angular, Is1.linear); Cm::SpatialVectorF stI(Is.bottom, Is.top); //Mirtich equivalent: I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A //Note we will compute I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A] later in the function. spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI); //[I_i^A * s_i] * [-s_i^T * ZAExt]/[s_i^T * I_i^A * s_i] { const PxReal innerprod = sa.innerProduct(linkZExtW); const PxReal diff = -innerprod; jointDofMinusStZExtW[0] = diff; deltaZAExtParent += isID * diff; } //[I_i^A * s_i] * [Q_i - s_i^T * ZAIntIc]/[s_i^T * I_i^A * s_i] { const PxReal innerprod = sa.innerProduct(linkZIntIcW); const PxReal diff = jointExternalForces[0] - innerprod; jointDofQStZIntIcW[0] = diff; deltaZAIntIcParent += isID * diff; } break; } case PxArticulationJointType::eSPHERICAL: { #if FEATHERSTONE_DEBUG //This is for debugging Temp6x6Matrix bigInertia(articulatedInertia); Temp6x3Matrix bigS(motionMatrix.getColumns()); Temp6x3Matrix bigIs = bigInertia * bigS; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind]; PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind])); PX_ASSERT(bigIs.isColumnEqual(ind, tempIs)); } #endif PxMat33 D(PxIdentity); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { #if FEATHERSTONE_DEBUG const Cm::UnAlignedSpatialVector& sa0 = motionMatrix[ind]; const PxVec3 u = sa0.top; PxMat33 armatureV = Outer(u, u) * jointTarget.armature[ind]; PxVec3 armatureU = armatureV * u; #endif for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[ind2]; #if FEATHERSTONE_DEBUG const PxVec3 u1 = sa.top; const PxReal armature = u1.dot(armatureU); #endif D[ind][ind2] = sa.innerProduct(jointISW[ind]); } D[ind][ind] += jointTargetArmatures[ind]; } //PxMat33 invD = SpatialMatrix::invertSym33(D); PxMat33 invD = D.getInverse(); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { linkInvStISW.invStIs[ind][ind2] = invD[ind][ind2]; } } #if FEATHERSTONE_DEBUG //debugging Temp6x3Matrix bigIsInvD = bigIs * invD; #endif Cm::SpatialVectorF columns[6]; columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f)); const Cm::UnAlignedSpatialVector& sa = jointMotionMatricesW[ind]; const PxReal stZ = sa.innerProduct(linkZExtW); const PxReal stZInt = sa.innerProduct(linkZIntIcW); //link.qstZIc[ind] = jF[ind] - stZ; const PxReal localQstZ = - stZ; const PxReal localQstZInt = jointExternalForces[ind] -stZInt; jointDofMinusStZExtW[ind] = localQstZ; jointDofQStZIntIcW[ind] = localQstZInt; for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { const Cm::SpatialVectorF& Is = jointISW[ind2]; isID += Is * invD[ind][ind2]; } columns[0] += isID * jointISW[ind].bottom.x; columns[1] += isID * jointISW[ind].bottom.y; columns[2] += isID * jointISW[ind].bottom.z; columns[3] += isID * jointISW[ind].top.x; columns[4] += isID * jointISW[ind].top.y; columns[5] += isID * jointISW[ind].top.z; jointDofISInvStISW[ind] = isID; deltaZAExtParent += isID * localQstZ; deltaZAIntIcParent += isID * localQstZInt; #if FEATHERSTONE_DEBUG const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]); PX_ASSERT(equal); #endif } #if FEATHERSTONE_DEBUG Temp6x6Matrix transpose6x6 = bigInertia.getTranspose(); #endif spatialInertia = SpatialMatrix::constructSpatialMatrix(columns); #if FEATHERSTONE_DEBUG Temp6x6Matrix result = bigIsInvD * stI; PX_ASSERT(result.isEqual(columns)); #endif break; } default: return linkArticulatedInertiaW; } //(I - Is*Inv(sIs)*sI) spatialInertia = linkArticulatedInertiaW - spatialInertia; return spatialInertia; } SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia_ZA_ZIc_NonSeparated (const PxArticulationJointType::Enum jointType, const PxU8 nbJointDofs, const Cm::UnAlignedSpatialVector* jointMotionMatrices, const Cm::SpatialVectorF* jointIs, const PxReal* jointTargetArmatures, const PxReal* jointExternalForces, const SpatialMatrix& articulatedInertia, const Cm::SpatialVectorF& ZIc, InvStIs& invStIs, Cm::SpatialVectorF* isInvD, PxReal* qstZIc, Cm::SpatialVectorF& deltaZParent) { deltaZParent = ZIc; // The goal is to propagate the articulated z.a force of a child link to the articulated z.a. force of its parent link. // We will compute a term that can be added to the articulated z.a. force of the parent link. // This function only references the child link. // Mirtich uses the notation i for the child and i-1 for the parent. // We have a more general configuration that allows a parent to have multiple children but in what follows "i" shall refer to the // child and "i-1" to the parent. // Another goal is to propagate the articulated spatial inertia from the child link to the parent link. // We will compute a term that can be added to the articulated spatial inertia of the parent link. // The Mirtich equivalent is: // I_i^A - [I_i^A * s_i^T *Inv(s_i^T *I_i^A * s_i) * s_i^T * I_i^A] //The term that is to be added to the parent link has the Mirtich formulation: // Delta_Z_i-1 = (Z_i^A + I_i^A * c_i) + [I_i^A * s_i]*[Q_i - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i] //We have function input arguments ZIntIc. //In Mirtich terms this is: Z_i + I_i^A * c_i. //Using the function arguments here we have: // Delta_Z_i-1 = ZIc + [I_i^A * s_i] * [Q_i - s_i^T * ZIc]/[s_i^T * I_i^A * s_i] SpatialMatrix spatialInertia; switch (jointType) { case PxArticulationJointType::ePRISMATIC: case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[0]; #if FEATHERSTONE_DEBUG PxVec3 u = (jointType == PxArticulationJointType::ePRISMATIC) ? sa.bottom : sa.top; PxMat33 armatureV = Outer(u, u) * jointTarget.armature[0]; const PxReal armature = u.dot(armatureV * u); #endif const Cm::SpatialVectorF& Is = jointIs[0]; //Mirtich equivalent: 1/[s_i^T * I_i^A * s_i] PxReal iStIs; { const PxReal stIs = (sa.innerProduct(Is) + jointTargetArmatures[0]); iStIs = (stIs > 1e-10f) ? (1.f / stIs) : 0.f; } invStIs.invStIs[0][0] = iStIs; //Mirtich equivalent: [I_i^A * s_i]/[s_i^T * I_i^A * s_i] Cm::SpatialVectorF isID = Is * iStIs; isInvD[0] = isID; //(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0] //Cm::SpatialVector stI1(Is1.angular, Is1.linear); Cm::SpatialVectorF stI(Is.bottom, Is.top); //Mirtich equivalent: I_i^A * s_i^T *[1/(s_i^T *I_i^A * s_i)] * s_i^T * I_i^A //Note we will compute I_i^A - [I_i^A * s_i^T *[1/(s_i^T *I_i^A * s_i)] * s_i^T * I_i^A] later in the function. spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI); //Mirtich equivalent: [I_i^A * s_i] * [-s_i^T * Z_i^A]/[s_i^T * I_i^A * s_i] { const PxReal innerProd = sa.innerProduct(ZIc); const PxReal diff = jointExternalForces[0] - innerProd; qstZIc[0] = diff; deltaZParent += isID * diff; } break; } case PxArticulationJointType::eSPHERICAL: { #if FEATHERSTONE_DEBUG //This is for debugging Temp6x6Matrix bigInertia(articulatedInertia); Temp6x3Matrix bigS(motionMatrix.getColumns()); Temp6x3Matrix bigIs = bigInertia * bigS; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind]; PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind])); PX_ASSERT(bigIs.isColumnEqual(ind, tempIs)); } #endif PxMat33 D(PxIdentity); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { #if FEATHERSTONE_DEBUG const Cm::UnAlignedSpatialVector& sa0 = motionMatrix[ind]; const PxVec3 u = sa0.top; PxMat33 armatureV = Outer(u, u) * jointTarget.armature[ind]; PxVec3 armatureU = armatureV * u; #endif for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[ind2]; #if FEATHERSTONE_DEBUG const PxVec3 u1 = sa.top; const PxReal armature = u1.dot(armatureU); #endif D[ind][ind2] = sa.innerProduct(jointIs[ind]); } D[ind][ind] += jointTargetArmatures[ind]; //D[ind][ind] *= 10.f; } PxMat33 invD = SpatialMatrix::invertSym33(D); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { invStIs.invStIs[ind][ind2] = invD[ind][ind2]; } } #if FEATHERSTONE_DEBUG //debugging Temp6x3Matrix bigIsInvD = bigIs * invD; #endif Cm::SpatialVectorF columns[6]; columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f)); const Cm::UnAlignedSpatialVector& sa = jointMotionMatrices[ind]; const PxReal stZ = sa.innerProduct(ZIc); //link.qstZIc[ind] = jF[ind] - stZ; const PxReal localQstZ = jointExternalForces[ind] - stZ; qstZIc[ind] = localQstZ; for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { const Cm::SpatialVectorF& Is = jointIs[ind2]; isID += Is * invD[ind][ind2]; } columns[0] += isID * jointIs[ind].bottom.x; columns[1] += isID * jointIs[ind].bottom.y; columns[2] += isID * jointIs[ind].bottom.z; columns[3] += isID * jointIs[ind].top.x; columns[4] += isID * jointIs[ind].top.y; columns[5] += isID * jointIs[ind].top.z; isInvD[ind] = isID; deltaZParent += isID * localQstZ; #if FEATHERSTONE_DEBUG const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]); PX_ASSERT(equal); #endif } #if FEATHERSTONE_DEBUG Temp6x6Matrix transpose6x6 = bigInertia.getTranspose(); #endif spatialInertia = SpatialMatrix::constructSpatialMatrix(columns); #if FEATHERSTONE_DEBUG Temp6x6Matrix result = bigIsInvD * stI; PX_ASSERT(result.isEqual(columns)); #endif break; } default: spatialInertia.setZero(); break; } //(I - Is*Inv(sIs)*sI) spatialInertia = articulatedInertia - spatialInertia; return spatialInertia; } SpatialMatrix FeatherstoneArticulation::computePropagateSpatialInertia( const PxArticulationJointType::Enum jointType, const PxU8 nbDofs, const SpatialMatrix& articulatedInertia, const Cm::UnAlignedSpatialVector* motionMatrices, const Cm::SpatialVectorF* linkIs, InvStIs& invStIs, Cm::SpatialVectorF* isInvD) { SpatialMatrix spatialInertia; switch (jointType) { case PxArticulationJointType::ePRISMATIC: case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const Cm::UnAlignedSpatialVector& sa = motionMatrices[0]; const Cm::SpatialVectorF& Is = linkIs[0]; const PxReal stIs = sa.innerProduct(Is); const PxReal iStIs = (stIs > 1e-10f) ? (1.f / stIs) : 0.f; invStIs.invStIs[0][0] = iStIs; Cm::SpatialVectorF isID = Is * iStIs; isInvD[0] = isID; //(6x1)Is = [v0, v1]; (1x6)stI = [v1, v0] //Cm::SpatialVector stI1(Is1.angular, Is1.linear); Cm::SpatialVectorF stI(Is.bottom, Is.top); spatialInertia = SpatialMatrix::constructSpatialMatrix(isID, stI); break; } case PxArticulationJointType::eSPHERICAL: { #if FEATHERSTONE_DEBUG //This is for debugging Temp6x6Matrix bigInertia(articulatedInertia); Temp6x3Matrix bigS(motionMatrix.getColumns()); Temp6x3Matrix bigIs = bigInertia * bigS; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { Cm::SpatialVectorF tempIs = bigInertia * motionMatrix[ind]; PX_ASSERT(isSpatialVectorEqual(tempIs, linkIs[ind])); PX_ASSERT(bigIs.isColumnEqual(ind, tempIs)); } #endif PxMat33 D(PxIdentity); for (PxU8 ind = 0; ind < nbDofs; ++ind) { for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2) { const Cm::UnAlignedSpatialVector& sa = motionMatrices[ind2]; D[ind][ind2] = sa.innerProduct(linkIs[ind]); } } PxMat33 invD = SpatialMatrix::invertSym33(D); for (PxU8 ind = 0; ind < nbDofs; ++ind) { for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2) { invStIs.invStIs[ind][ind2] = invD[ind][ind2]; } } #if FEATHERSTONE_DEBUG //debugging Temp6x3Matrix bigIsInvD = bigIs * invD; #endif Cm::SpatialVectorF columns[6]; columns[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[1] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[2] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[3] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[4] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); columns[5] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); for (PxU8 ind = 0; ind < nbDofs; ++ind) { Cm::SpatialVectorF isID(PxVec3(0.f), PxVec3(0.f)); for (PxU8 ind2 = 0; ind2 < nbDofs; ++ind2) { const Cm::SpatialVectorF& Is = linkIs[ind2]; isID += Is * invD[ind][ind2]; } columns[0] += isID * linkIs[ind].bottom.x; columns[1] += isID * linkIs[ind].bottom.y; columns[2] += isID * linkIs[ind].bottom.z; columns[3] += isID * linkIs[ind].top.x; columns[4] += isID * linkIs[ind].top.y; columns[5] += isID * linkIs[ind].top.z; isInvD[ind] = isID; #if FEATHERSTONE_DEBUG const bool equal = bigIsInvD.isColumnEqual(ind, isInvD.isInvD[ind]); PX_ASSERT(equal); #endif } #if FEATHERSTONE_DEBUG Temp6x6Matrix transpose6x6 = bigInertia.getTranspose(); #endif spatialInertia = SpatialMatrix::constructSpatialMatrix(columns); #if FEATHERSTONE_DEBUG Temp6x6Matrix result = bigIsInvD * stI; PX_ASSERT(result.isEqual(columns)); #endif break; } default: spatialInertia.setZero(); break; } //(I - Is*Inv(sIs)*sI) spatialInertia = articulatedInertia - spatialInertia; return spatialInertia; } void FeatherstoneArticulation::computeArticulatedSpatialInertiaAndZ (const ArticulationLink* links, const PxU32 linkCount, const PxVec3* linkRsW, const ArticulationJointCoreData* jointData, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW, const Cm::SpatialVectorF* linkCoriolisVectors, const PxReal* jointDofForces, Cm::SpatialVectorF* jointDofISW, InvStIs* linkInvStISW, Cm::SpatialVectorF* jointDofISInvStISW, PxReal* jointDofMinusStZExtW, PxReal* jointDofQStZIntIcW, Cm::SpatialVectorF* linkZAExtForcesW, Cm::SpatialVectorF* linkZAIntForcesW, SpatialMatrix* linkSpatialArticulatedInertiaW, SpatialMatrix& baseInvSpatialArticulatedInertiaW) { const PxU32 startIndex = PxU32(linkCount - 1); for (PxU32 linkID = startIndex; linkID > 0; --linkID) { const ArticulationLink& link = links[linkID]; const ArticulationJointCoreData& jointDatum = jointData[linkID]; const PxU32 jointOffset = jointDatum.jointOffset; const PxU8 nbDofs = jointDatum.dof; for (PxU8 ind = 0; ind < nbDofs; ++ind) { const Cm::UnAlignedSpatialVector tmp = linkSpatialArticulatedInertiaW[linkID] * jointDofMotionMatricesW[jointOffset + ind]; jointDofISW[jointOffset + ind].top = tmp.top; jointDofISW[jointOffset + ind].bottom = tmp.bottom; } //Compute the terms to accumulate on the parent's articulated z.a force and articulated spatial inertia. Cm::SpatialVectorF deltaZAExtParent; Cm::SpatialVectorF deltaZAIntParent; SpatialMatrix spatialInertiaW; { //calculate spatial zero acceleration force, this can move out of the loop const Cm::SpatialVectorF linkZW = linkZAExtForcesW[linkID]; const Cm::SpatialVectorF linkIcW = linkSpatialArticulatedInertiaW[linkID] * linkCoriolisVectors[linkID]; const Cm::SpatialVectorF linkZIntIcW = linkZAIntForcesW[linkID] + linkIcW; //(I - Is*Inv(sIs)*sI) //KS - we also bury Articulated ZA force and ZIc force computation in here because that saves //us some round-trips to memory! spatialInertiaW = computePropagateSpatialInertia_ZA_ZIc( PxArticulationJointType::Enum(link.inboundJoint->jointType), jointDatum.dof, &jointDofMotionMatricesW[jointOffset], &jointDofISW[jointOffset], &jointDatum.armature[0], &jointDofForces[jointOffset], linkSpatialArticulatedInertiaW[linkID], linkZW, linkZIntIcW, linkInvStISW[linkID], &jointDofISInvStISW[jointOffset], &jointDofMinusStZExtW[jointOffset], &jointDofQStZIntIcW[jointOffset], deltaZAExtParent, deltaZAIntParent); } //Accumulate the spatial inertia on the parent link. { //transform spatial inertia into parent space FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(linkRsW[linkID]), spatialInertiaW); // Make sure we do not propagate up negative inertias around the principal inertial axes // due to numerical rounding errors const PxReal minPropagatedInertia = 0.f; spatialInertiaW.bottomLeft.column0.x = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column0.x); spatialInertiaW.bottomLeft.column1.y = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column1.y); spatialInertiaW.bottomLeft.column2.z = PxMax(minPropagatedInertia, spatialInertiaW.bottomLeft.column2.z); linkSpatialArticulatedInertiaW[link.parent] += spatialInertiaW; } //Accumulate the articulated z.a force on the parent link. { Cm::SpatialVectorF translatedZA = FeatherstoneArticulation::translateSpatialVector(linkRsW[linkID], deltaZAExtParent); Cm::SpatialVectorF translatedZAInt = FeatherstoneArticulation::translateSpatialVector(linkRsW[linkID], deltaZAIntParent); linkZAExtForcesW[link.parent] += translatedZA; linkZAIntForcesW[link.parent] += translatedZAInt; } } //cache base link inverse spatial inertia linkSpatialArticulatedInertiaW[0].invertInertiaV(baseInvSpatialArticulatedInertiaW); } void FeatherstoneArticulation::computeArticulatedSpatialInertiaAndZ_NonSeparated(ArticulationData& data, ScratchData& scratchData) { const ArticulationLink* links = data.getLinks(); ArticulationJointCoreData* jointData = data.getJointData(); SpatialMatrix* spatialArticulatedInertia = data.getWorldSpatialArticulatedInertia(); const Cm::UnAlignedSpatialVector* motionMatrix = data.getWorldMotionMatrix(); Cm::SpatialVectorF* Is = data.getIsW(); InvStIs* invStIs = data.getInvStIS(); Cm::SpatialVectorF* IsInvDW = data.getISInvStIS(); PxReal* qstZIc = data.getQstZIc(); SpatialMatrix& baseInvSpatialArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW(); const PxU32 linkCount = data.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; Cm::SpatialVectorF* articulatedZA = scratchData.spatialZAVectors; for (PxU32 linkID = startIndex; linkID > 0; --linkID) { const ArticulationLink& link = links[linkID]; ArticulationJointCoreData& jointDatum = jointData[linkID]; const PxU32 jointOffset = jointDatum.jointOffset; const PxU8 nbDofs = jointDatum.dof; for (PxU8 ind = 0; ind < nbDofs; ++ind) { const Cm::UnAlignedSpatialVector tmp = spatialArticulatedInertia[linkID] * motionMatrix[jointOffset + ind]; Is[jointOffset + ind].top = tmp.top; Is[jointOffset + ind].bottom = tmp.bottom; } //calculate spatial zero acceleration force, this can move out of the loop Cm::SpatialVectorF deltaZParent; SpatialMatrix spatialInertiaW; { Cm::SpatialVectorF Ic = spatialArticulatedInertia[linkID] * coriolisVectors[linkID]; Cm::SpatialVectorF Z = articulatedZA[linkID] + Ic; //(I - Is*Inv(sIs)*sI) //KS - we also bury Articulated ZA force and ZIc force computation in here because that saves //us some round-trips to memory! spatialInertiaW = computePropagateSpatialInertia_ZA_ZIc_NonSeparated( PxArticulationJointType::Enum(link.inboundJoint->jointType), jointDatum.dof, &motionMatrix[jointDatum.jointOffset], &Is[jointDatum.jointOffset], &jointDatum.armature[0], &scratchData.jointForces[jointDatum.jointOffset], // AD what's the difference between the scratch and the articulation data? spatialArticulatedInertia[linkID], Z, invStIs[linkID], &IsInvDW[jointDatum.jointOffset], &qstZIc[jointDatum.jointOffset], deltaZParent); } //transform spatial inertia into parent space FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(data.getRw(linkID)), spatialInertiaW); spatialArticulatedInertia[link.parent] += spatialInertiaW; Cm::SpatialVectorF translatedZA = FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), deltaZParent); articulatedZA[link.parent] += translatedZA; } //cache base link inverse spatial inertia spatialArticulatedInertia[0].invertInertiaV(baseInvSpatialArticulatedInertia); } void FeatherstoneArticulation::computeArticulatedSpatialInertia(ArticulationData& data) { const ArticulationLink* links = data.getLinks(); const ArticulationJointCoreData* jointData = data.getJointData(); SpatialMatrix* spatialArticulatedInertia = data.getWorldSpatialArticulatedInertia(); const Cm::UnAlignedSpatialVector* motionMatrix = data.getWorldMotionMatrix(); Cm::SpatialVectorF* Is = data.getIsW(); InvStIs* invStIs = data.getInvStIS(); Cm::SpatialVectorF* IsInvDW = data.getISInvStIS(); SpatialMatrix& baseInvSpatialArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW(); const PxU32 linkCount = data.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); for (PxU32 linkID = startIndex; linkID > 0; --linkID) { const ArticulationLink& link = links[linkID]; const ArticulationJointCoreData& jointDatum = jointData[linkID]; const PxU32 jointOffset = jointDatum.jointOffset; const PxU8 nbDofs = jointDatum.dof; for (PxU8 ind = 0; ind < nbDofs; ++ind) { const Cm::UnAlignedSpatialVector tmp = spatialArticulatedInertia[linkID] * motionMatrix[jointOffset + ind]; Is[jointOffset + ind].top = tmp.top; Is[jointOffset + ind].bottom = tmp.bottom; } //(I - Is*Inv(sIs)*sI) //KS - we also bury Articulated ZA force and ZIc force computation in here because that saves //us some round-trips to memory! SpatialMatrix spatialInertiaW = computePropagateSpatialInertia( PxArticulationJointType::Enum(link.inboundJoint->jointType), jointDatum.dof, spatialArticulatedInertia[linkID], &motionMatrix[jointOffset], &Is[jointOffset], invStIs[linkID], &IsInvDW[jointOffset]); //transform spatial inertia into parent space FeatherstoneArticulation::translateInertia(constructSkewSymmetricMatrix(data.getRw(linkID)), spatialInertiaW); spatialArticulatedInertia[link.parent] += spatialInertiaW; } //cache base link inverse spatial inertia spatialArticulatedInertia[0].invertInertiaV(baseInvSpatialArticulatedInertia); } void FeatherstoneArticulation::computeArticulatedResponseMatrix (const PxArticulationFlags& articulationFlags, const PxU32 linkCount, const ArticulationJointCoreData* jointData, const SpatialMatrix& baseInvArticulatedInertiaW, const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW, const Cm::SpatialVectorF* jointDofISW, const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofIsInvDW, ArticulationLink* links, SpatialImpulseResponseMatrix* linkResponsesW) { //PX_PROFILE_ZONE("ComputeResponseMatrix", 0); //We can work out impulse response vectors by propagating an impulse to the root link, then back down to the child link using existing data. //Alternatively, we can compute an impulse response matrix, which is a vector of 6x6 matrices, which can be multiplied by the impulse vector to //compute the response. This can be stored in world space, saving transforms. It can also be computed incrementally, meaning it should not be //dramatically more expensive than propagating the impulse for a single constraint. Furthermore, this will allow us to rapidly compute the //impulse response with the TGS solver allowing us to improve quality of equality positional constraints by properly reflecting non-linear motion //of the articulation rather than approximating it with linear projections. //The input expected is a local-space impulse and the output is a local-space impulse response vector if (articulationFlags & PxArticulationFlag::eFIX_BASE) { //Fixed base, so response is zero PxMemZero(linkResponsesW, sizeof(SpatialImpulseResponseMatrix)); } else { //Compute impulse response matrix. Compute the impulse response of unit responses on all 6 axes... PxMat33 bottomRight = baseInvArticulatedInertiaW.getBottomRight(); linkResponsesW[0].rows[0] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column0, baseInvArticulatedInertiaW.bottomLeft.column0); linkResponsesW[0].rows[1] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column1, baseInvArticulatedInertiaW.bottomLeft.column1); linkResponsesW[0].rows[2] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topLeft.column2, baseInvArticulatedInertiaW.bottomLeft.column2); linkResponsesW[0].rows[3] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column0, bottomRight.column0); linkResponsesW[0].rows[4] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column1, bottomRight.column1); linkResponsesW[0].rows[5] = Cm::SpatialVectorF(baseInvArticulatedInertiaW.topRight.column2, bottomRight.column2); links[0].cfm *= PxMax(linkResponsesW[0].rows[0].bottom.x, PxMax(linkResponsesW[0].rows[1].bottom.y, linkResponsesW[0].rows[2].bottom.z)); } for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { PxVec3 offset = linkRsW[linkID]; const PxU32 jointOffset = jointData[linkID].jointOffset; const PxU8 dofCount = jointData[linkID].dof; for (PxU32 i = 0; i < 6; ++i) { //Impulse has to be negated! Cm::SpatialVectorF vec = Cm::SpatialVectorF::Zero(); vec[i] = 1.f; Cm::SpatialVectorF temp = -vec; ArticulationLink& tLink = links[linkID]; //(1) Propagate impulse to parent PxReal qstZ[3] = { 0.f, 0.f, 0.f }; Cm::SpatialVectorF Zp = FeatherstoneArticulation::propagateImpulseW( offset, temp, &jointDofIsInvDW[jointOffset], &jointDofMotionMatricesW[jointOffset], dofCount, qstZ); //(2) Get deltaV response for parent Cm::SpatialVectorF zR = -linkResponsesW[tLink.parent].getResponse(Zp); const Cm::SpatialVectorF deltaV = propagateAccelerationW(offset, linkInvStISW[linkID], &jointDofMotionMatricesW[jointOffset], zR, dofCount, &jointDofISW[jointOffset], qstZ); //Store in local space (required for propagation linkResponsesW[linkID].rows[i] = deltaV; } links[linkID].cfm *= PxMax(linkResponsesW[linkID].rows[0].bottom.x, PxMax(linkResponsesW[linkID].rows[1].bottom.y, linkResponsesW[linkID].rows[2].bottom.z)); } } void FeatherstoneArticulation::computeArticulatedSpatialZ(ArticulationData& data, ScratchData& scratchData) { ArticulationLink* links = data.getLinks(); ArticulationJointCoreData* jointData = data.getJointData(); const PxU32 linkCount = data.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; Cm::SpatialVectorF* articulatedZA = scratchData.spatialZAVectors; PxReal* jointForces = scratchData.jointForces; for (PxU32 linkID = startIndex; linkID > 0; --linkID) { ArticulationLink& link = links[linkID]; ArticulationJointCoreData& jointDatum = jointData[linkID]; //calculate spatial zero acceleration force, this can move out of the loop Cm::SpatialVectorF Ic = data.mWorldSpatialArticulatedInertia[linkID] * coriolisVectors[linkID]; Cm::SpatialVectorF ZIc = articulatedZA[linkID] + Ic; const PxReal* jF = &jointForces[jointDatum.jointOffset]; Cm::SpatialVectorF ZA = ZIc; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { const Cm::UnAlignedSpatialVector& sa = data.mWorldMotionMatrix[jointDatum.jointOffset + ind]; const PxReal stZ = sa.innerProduct(ZIc); //link.qstZIc[ind] = jF[ind] - stZ; const PxReal qstZic = jF[ind] - stZ; data.qstZIc[jointDatum.jointOffset + ind] = qstZic; PX_ASSERT(PxIsFinite(qstZic)); ZA += data.mISInvStIS[jointDatum.jointOffset + ind] * qstZic; } //accumulate childen's articulated zero acceleration force to parent's articulated zero acceleration articulatedZA[link.parent] += FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), ZA); } } void FeatherstoneArticulation::computeJointSpaceJacobians(ArticulationData& data) { //PX_PROFILE_ZONE("computeJointSpaceJacobians", 0); const PxU32 linkCount = data.getLinkCount(); const PxU32 dofCount = data.getDofs(); PxTransform* trans = data.getAccumulatedPoses(); Cm::SpatialVectorF* jointSpaceJacobians = data.getJointSpaceJacobians(); Dy::ArticulationLink* links = data.mLinks; Dy::ArticulationJointCoreData* jointData = data.mJointData; Cm::UnAlignedSpatialVector* worldMotionMatrix = data.mWorldMotionMatrix.begin(); for (PxU32 linkID = 1; linkID < linkCount; linkID++) { const PxTransform pose = trans[linkID]; Cm::SpatialVectorF* myJacobian = &jointSpaceJacobians[linkID*dofCount]; const PxU32 lastDof = jointData[linkID].jointOffset + jointData[linkID].dof; PxMemZero(myJacobian, sizeof(Cm::SpatialVectorF)*lastDof); PxU32 link = linkID; while (link != 0) { PxU32 parent = links[link].parent; const Dy::ArticulationJointCoreData& jData = jointData[link]; const PxTransform parentPose = trans[link]; PxVec3 rw = parentPose.p - pose.p; const PxU32 jointOffset = jData.jointOffset; const PxU32 dofs = jData.dof; Cm::UnAlignedSpatialVector* motionMatrix = &worldMotionMatrix[jointOffset]; for (PxU32 i = 0; i < dofs; ++i) { myJacobian[jointOffset + i].top = motionMatrix[i].top; myJacobian[jointOffset + i].bottom = motionMatrix[i].bottom + rw.cross(motionMatrix[i].top); } link = parent; } #if 0 //Verify the jacobian... Cm::SpatialVectorF velocity = FeatherstoneArticulation::translateSpatialVector((trans[0].p - trans[linkID].p), data.mMotionVelocities[0]); PxReal* jointVelocity = data.getJointVelocities(); //KS - a bunch of these dofs can be skipped, we just need to follow path-to-root. However, that may be more expensive than //just doing the full multiplication. Let's see how expensive it is now... for (PxU32 i = 0; i < lastDof; ++i) { velocity += myJacobian[i] * jointVelocity[i]; } int bob = 0; PX_UNUSED(bob); #endif } } void FeatherstoneArticulation::computeJointAccelerationW(const PxU8 nbJointDofs, const Cm::SpatialVectorF& parentMotionAcceleration, const Cm::SpatialVectorF* jointDofISW, const InvStIs& linkInvStISW, const PxReal* jointDofQStZIcW, PxReal* jointAcceleration) { PxReal tJAccel[6]; //Mirtich equivalent: Q_i - (s_i^T * I_i^A * a_i-1) - s_i^T * (Z_i^A + I_i^A * c_i) for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { //stI * pAcceleration const PxReal temp = jointDofISW[ind].innerProduct(parentMotionAcceleration); tJAccel[ind] = (jointDofQStZIcW[ind] - temp); } //calculate jointAcceleration //Mirtich equivalent: [Q_i - (s_i^T * I_i^A * a_i-1) - s_i^T * (Z_i^A + I_i^A * c_i)]/[s_i^T * I_i^A * s_i] for (PxU32 ind = 0; ind < nbJointDofs; ++ind) { jointAcceleration[ind] = 0.f; for (PxU32 ind2 = 0; ind2 < nbJointDofs; ++ind2) { jointAcceleration[ind] += linkInvStISW.invStIs[ind2][ind] * tJAccel[ind2]; } //PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000); } } void FeatherstoneArticulation::computeLinkAcceleration (const bool doIC, const PxReal dt, const bool fixBase, const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointDatas, const Cm::SpatialVectorF* linkSpatialZAForces, const Cm::SpatialVectorF* linkCoriolisForces, const PxVec3* linkRws, const Cm::UnAlignedSpatialVector* jointDofMotionMatrices, const SpatialMatrix& baseInvSpatialArticulatedInertiaW, const InvStIs* linkInvStIs, const Cm::SpatialVectorF* jointDofIsWs, const PxReal* jointDofQstZics, Cm::SpatialVectorF* linkMotionAccelerations, Cm::SpatialVectorF* linkMotionVelocities, PxReal* jointDofAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities) { //we have initialized motionVelocity and motionAcceleration to be zero in the root link if //fix based flag is raised if (!fixBase) { //ArticulationLinkData& baseLinkDatum = data.getLinkData(0); #if FEATHERSTONE_DEBUG SpatialMatrix result = invInertia * baseLinkDatum.spatialArticulatedInertia; bool isIdentity = result.isIdentity(); PX_ASSERT(isIdentity); PX_UNUSED(isIdentity); #endif //ArticulationLink& baseLink = data.getLink(0); //const PxTransform& body2World = baseLink.bodyCore->body2World; Cm::SpatialVectorF accel = -(baseInvSpatialArticulatedInertiaW * linkSpatialZAForces[0]); linkMotionAccelerations[0] = accel; Cm::SpatialVectorF deltaV = accel * dt; linkMotionVelocities[0] += deltaV; } #if FEATHERSTONE_DEBUG else { PX_ASSERT(isSpatialVectorZero(motionAccelerations[0])); PX_ASSERT(isSpatialVectorZero(motionVelocities[0])); } #endif /*PxReal* jointAccelerations = data.getJointAccelerations(); PxReal* jointVelocities = data.getJointVelocities(); PxReal* jointPositions = data.getJointPositions();*/ //printf("===========================\n"); //calculate acceleration for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationJointCore& joint = *link.inboundJoint; PX_UNUSED(joint); Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-linkRws[linkID], linkMotionAccelerations[link.parent]); const ArticulationJointCoreData& jointDatum = jointDatas[linkID]; //calculate jointAcceleration PxReal* jA = &jointDofAccelerations[jointDatum.jointOffset]; const InvStIs& invStIs = linkInvStIs[linkID]; computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &jointDofIsWs[jointDatum.jointOffset], invStIs, &jointDofQstZics[jointDatum.jointOffset], jA); Cm::SpatialVectorF motionAcceleration = pMotionAcceleration; if (doIC) motionAcceleration += linkCoriolisForces[linkID]; PxReal* jointVelocity = &jointDofVelocities[jointDatum.jointOffset]; PxReal* jointNewVelocity = &jointDofNewVelocities[jointDatum.jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { const PxReal accel = jA[ind]; PxReal jVel = jointVelocity[ind] + accel * dt; jointVelocity[ind] = jVel; jointNewVelocity[ind] = jVel; motionAcceleration.top += jointDofMotionMatrices[jointDatum.jointOffset + ind].top * accel; motionAcceleration.bottom += jointDofMotionMatrices[jointDatum.jointOffset + ind].bottom * accel; } //KS - can we just work out velocities by projecting out the joint velocities instead of accumulating all this? linkMotionAccelerations[linkID] = motionAcceleration; PX_ASSERT(linkMotionAccelerations[linkID].isFinite()); linkMotionVelocities[linkID] += motionAcceleration * dt; /*Cm::SpatialVectorF spatialForce = mArticulationData.mWorldSpatialArticulatedInertia[linkID] * motionAcceleration; Cm::SpatialVectorF zaForce = -spatialZAForces[linkID]; int bob = 0; PX_UNUSED(bob);*/ } } void FeatherstoneArticulation::computeLinkInternalAcceleration ( const PxReal dt, const bool fixBase, const PxVec3& com, const PxReal invSumMass, const PxReal maxLinearVelocity, const PxReal maxAngularVelocity, const PxMat33* linkIsolatedSpatialArticulatedInertiasW, const SpatialMatrix& baseInvSpatialArticulatedInertiaW, const ArticulationLink* links, const PxU32 linkCount, const PxReal* linkMasses, const PxVec3* linkRsW, const PxTransform* linkAccumulatedPosesW, const Cm::SpatialVectorF* linkSpatialZAIntForcesW, const Cm::SpatialVectorF* linkCoriolisVectorsW, const ArticulationJointCoreData* jointDatas, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW, const InvStIs* linkInvStISW, const Cm::SpatialVectorF* jointDofISW, const PxReal* jointDofQStZIntIcW, Cm::SpatialVectorF* linkMotionAccelerationsW, Cm::SpatialVectorF* linkMotionIntAccelerationsW, Cm::SpatialVectorF* linkMotionVelocitiesW, PxReal* jointDofAccelerations, PxReal* jointDofInternalAccelerations, PxReal* jointDofVelocities, PxReal* jointDofNewVelocities) { //we have initialized motionVelocity and motionAcceleration to be zero in the root link if //fix based flag is raised Cm::SpatialVectorF momentum0(PxVec3(0,0,0), PxVec3(0,0,0)); PxVec3 rootVel(PxZero); { for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const Cm::SpatialVectorF& vel = linkMotionVelocitiesW[linkID]; const PxReal mass = linkMasses[linkID]; momentum0.top += vel.bottom*mass; } rootVel = momentum0.top * invSumMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxReal mass = linkMasses[linkID]; const Cm::SpatialVectorF& vel = linkMotionVelocitiesW[linkID]; const PxVec3 offsetMass = (linkAccumulatedPosesW[linkID].p - com)*mass; const PxVec3 angMom = linkIsolatedSpatialArticulatedInertiasW[linkID] * vel.top + offsetMass.cross(linkMotionVelocitiesW[linkID].bottom - rootVel); momentum0.bottom += angMom; } } if (!fixBase) { //ArticulationLinkData& baseLinkDatum = data.getLinkData(0); #if FEATHERSTONE_DEBUG SpatialMatrix result = invInertia * baseLinkDatum.spatialArticulatedInertia; bool isIdentity = result.isIdentity(); PX_ASSERT(isIdentity); PX_UNUSED(isIdentity); #endif //ArticulationLink& baseLink = data.getLink(0); //const PxTransform& body2World = baseLink.bodyCore->body2World; const Cm::SpatialVectorF accel = -(baseInvSpatialArticulatedInertiaW * linkSpatialZAIntForcesW[0]); linkMotionIntAccelerationsW[0] = accel; linkMotionAccelerationsW[0] += accel; const Cm::SpatialVectorF deltaV = accel * dt; linkMotionVelocitiesW[0] += deltaV; } else { linkMotionIntAccelerationsW[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); } //printf("===========================\n"); //calculate acceleration for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationJointCore& joint = *link.inboundJoint; PX_UNUSED(joint); const Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-linkRsW[linkID], linkMotionIntAccelerationsW[link.parent]); const ArticulationJointCoreData& jointDatum = jointDatas[linkID]; //calculate jointAcceleration PxReal* jIntAccel = &jointDofInternalAccelerations[jointDatum.jointOffset]; computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &jointDofISW[jointDatum.jointOffset], linkInvStISW[linkID], &jointDofQStZIntIcW[jointDatum.jointOffset], jIntAccel); //printf("jA %f\n", jA[0]); //KS - TODO - separate integration of coriolis vectors! Cm::SpatialVectorF motionAcceleration = pMotionAcceleration + linkCoriolisVectorsW[linkID]; PxReal* jointVelocity = &jointDofVelocities[jointDatum.jointOffset]; PxReal* jointNewVelocity = &jointDofNewVelocities[jointDatum.jointOffset]; PxReal* jA = &jointDofAccelerations[jointDatum.jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { const PxReal accel = jIntAccel[ind]; PxReal jVel = jointVelocity[ind] + accel * dt; jointVelocity[ind] = jVel; jointNewVelocity[ind] = jVel; motionAcceleration.top += jointDofMotionMatricesW[jointDatum.jointOffset + ind].top * accel; motionAcceleration.bottom += jointDofMotionMatricesW[jointDatum.jointOffset + ind].bottom * accel; jA[ind] += accel; } //KS - can we just work out velocities by projecting out the joint velocities instead of accumulating all this? linkMotionIntAccelerationsW[linkID] = motionAcceleration; linkMotionAccelerationsW[linkID] += motionAcceleration; PX_ASSERT(linkMotionAccelerationsW[linkID].isFinite()); Cm::SpatialVectorF velDelta = (motionAcceleration)* dt; linkMotionVelocitiesW[linkID] += velDelta; } if (!fixBase) { PxVec3 angMomentum1(0.f); PxMat33 inertia(PxZero); PxVec3 sumLinMomentum(0.f); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { PxReal mass = linkMasses[linkID]; sumLinMomentum += linkMotionVelocitiesW[linkID].bottom * mass; } rootVel = sumLinMomentum * invSumMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { PxReal mass = linkMasses[linkID]; const PxVec3 offset = linkAccumulatedPosesW[linkID].p - com; inertia += translateInertia(linkIsolatedSpatialArticulatedInertiasW[linkID], mass, offset); angMomentum1 += linkIsolatedSpatialArticulatedInertiasW[linkID] * linkMotionVelocitiesW[linkID].top + offset.cross(linkMotionVelocitiesW[linkID].bottom - rootVel) * mass; } PxMat33 invCompoundInertia = inertia.getInverse(); PxReal denom0 = angMomentum1.magnitude(); PxReal num = momentum0.bottom.magnitude(); PxReal angRatio = denom0 == 0.f ? 1.f : num / denom0; PxVec3 deltaAngMom = angMomentum1 * (angRatio - 1.f); PxVec3 deltaAng = invCompoundInertia * deltaAngMom; if (maxAngularVelocity > 0.0f) { const PxReal maxAng = maxAngularVelocity; const PxReal maxAngSq = maxAng * maxAng; PxVec3 ang = (invCompoundInertia * angMomentum1) + deltaAng; if (ang.magnitudeSquared() > maxAngSq) { PxReal ratio = maxAng / ang.magnitude(); deltaAng += (ratio - 1.f)*ang; } } #if 1 for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxVec3 offset = (linkAccumulatedPosesW[linkID].p - com); Cm::SpatialVectorF velChange(deltaAng, -offset.cross(deltaAng)); linkMotionVelocitiesW[linkID] += velChange; const PxReal mass = linkMasses[linkID]; sumLinMomentum += velChange.bottom * mass; } #else motionVelocities[0].top += deltaAng; motionAccelerations[0] = Cm::SpatialVectorF(deltaAng, PxVec3(0.f)); //sumLinMomentum = motionVelocities[0].bottom * data.mMasses[0]; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { Cm::SpatialVectorF velChange = Dy::FeatherstoneArticulation::translateSpatialVector(-data.getRw(linkID), motionAccelerations[data.getLink(linkID).parent]); motionVelocities[linkID] += velChange; motionAccelerations[linkID] = velChange; PxReal mass = data.mMasses[linkID]; //sumLinMomentum += motionVelocities[linkID].bottom * mass; sumLinMomentum += velChange.bottom * mass; } #endif #if 0 PxReal denom1 = sumLinMomentum.magnitude(); PxReal linRatio = PxMin(10.f, denom1 == 0.f ? 1.f : momentum0.top.magnitude() / denom1); PxVec3 deltaLinMom = sumLinMomentum * (linRatio - 1.f); #else PxVec3 deltaLinMom = momentum0.top - sumLinMomentum; #endif PxVec3 deltaLin = deltaLinMom * invSumMass; if (maxLinearVelocity >= 0.0f) { const PxReal maxLin = maxLinearVelocity; const PxReal maxLinSq = maxLin * maxLin; PxVec3 lin = (sumLinMomentum * invSumMass) + deltaLin; if (lin.magnitudeSquared() > maxLinSq) { PxReal ratio = maxLin / lin.magnitude(); deltaLin += (ratio - 1.f)*lin; } } for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { linkMotionVelocitiesW[linkID].bottom += deltaLin; } #if PX_DEBUG && 0 const bool validateMomentum = false; if (validateMomentum) { Cm::SpatialVectorF momentum2(PxVec3(0.f), PxVec3(0.f)); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxReal mass = data.mMasses[linkID]; momentum2.top += motionVelocities[linkID].bottom * mass; } rootVel = momentum2.top * sumInvMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxReal mass = data.mMasses[linkID]; const PxVec3 angMom = data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top + (data.getAccumulatedPoses()[linkID].p - COM).cross(motionVelocities[linkID].bottom - rootVel) * mass; momentum2.bottom += angMom; } static PxU32 count = 0; count++; printf("LinMom0 = %f, LinMom1 = %f, LinMom2 = %f\n", momentum0.top.magnitude(), sumLinMomentum.magnitude(), momentum2.top.magnitude()); printf("AngMom0 = %f, AngMom1 = %f, AngMom2 = %f\n", momentum0.bottom.magnitude(), angMomentum1.magnitude(), momentum2.bottom.magnitude()); printf("%i: Angular Momentum0 (%f, %f, %f), angularMomentum1 (%f, %f, %f), angularMomFinal (%f, %f, %f)\n", count, momentum0.bottom.x, momentum0.bottom.y, momentum0.bottom.z, angMomentum1.x, angMomentum1.y, angMomentum1.z, momentum2.bottom.x, momentum2.bottom.y, momentum2.bottom.z); } #endif } } void FeatherstoneArticulation::computeLinkIncomingJointForce( const PxU32 linkCount, const Cm::SpatialVectorF* linkZAForcesExtW, const Cm::SpatialVectorF* linkZAForcesIntW, const Cm::SpatialVectorF* linkMotionAccelerationsW, const SpatialMatrix* linkSpatialInertiasW, Cm::SpatialVectorF* linkIncomingJointForces) { linkIncomingJointForces[0] = Cm::SpatialVectorF(PxVec3(0,0,0), PxVec3(0,0,0)); for(PxU32 i = 1; i < linkCount; i++) { linkIncomingJointForces[i] = linkSpatialInertiasW[i]*linkMotionAccelerationsW[i] + (linkZAForcesExtW[i] + linkZAForcesIntW[i]); } } void FeatherstoneArticulation::computeJointTransmittedFrictionForce( ArticulationData& data, ScratchData& scratchData, Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*DeltaV*/) { //const PxU32 linkCount = data.getLinkCount(); const PxU32 startIndex = data.getLinkCount() - 1; //const PxReal frictionCoefficient =30.5f; Cm::SpatialVectorF* transmittedForce = scratchData.spatialZAVectors; for (PxU32 linkID = startIndex; linkID > 1; --linkID) { const ArticulationLink& link = data.getLink(linkID); //joint force transmitted from parent to child //transmittedForce[link.parent] += data.mChildToParent[linkID] * transmittedForce[linkID]; transmittedForce[link.parent] += FeatherstoneArticulation::translateSpatialVector(data.getRw(linkID), transmittedForce[linkID]); } transmittedForce[0] = Cm::SpatialVectorF::Zero(); //const PxReal dt = data.getDt(); //for (PxU32 linkID = 1; linkID < linkCount; ++linkID) //{ // //ArticulationLink& link = data.getLink(linkID); // //ArticulationLinkData& linkDatum = data.getLinkData(linkID); // transmittedForce[linkID] = transmittedForce[linkID] * (frictionCoefficient) * dt; // //transmittedForce[link.parent] -= linkDatum.childToParent * transmittedForce[linkID]; //} // //applyImpulses(transmittedForce, Z, DeltaV); //PxReal* deltaV = data.getJointDeltaVelocities(); //PxReal* jointV = data.getJointVelocities(); //for (PxU32 linkID = 1; linkID < data.getLinkCount(); ++linkID) //{ // ArticulationJointCoreData& tJointDatum = data.getJointData()[linkID]; // for (PxU32 i = 0; i < tJointDatum.dof; ++i) // { // jointV[i + tJointDatum.jointOffset] += deltaV[i + tJointDatum.jointOffset]; // deltaV[i + tJointDatum.jointOffset] = 0.f; // } //} } //void FeatherstoneArticulation::computeJointFriction(ArticulationData& data, // ScratchData& scratchData) //{ // PX_UNUSED(scratchData); // const PxU32 linkCount = data.getLinkCount(); // PxReal* jointForces = scratchData.jointForces; // PxReal* jointFrictionForces = data.getJointFrictionForces(); // PxReal* jointVelocities = data.getJointVelocities(); // const PxReal coefficient = 0.5f; // for (PxU32 linkID = 1; linkID < linkCount; ++linkID) // { // ArticulationJointCoreData& jointDatum = data.getJointData(linkID); // //compute generalized force // PxReal* jFs = &jointForces[jointDatum.jointOffset]; // PxReal* jVs = &jointVelocities[jointDatum.jointOffset]; // PxReal* jFFs = &jointFrictionForces[jointDatum.jointOffset]; // for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) // { // PxReal sign = jVs[ind] > 0 ? -1.f : 1.f; // jFFs[ind] = coefficient * PxAbs(jFs[ind]) *sign; // //jFFs[ind] = coefficient * jVs[ind]; // } // } //} // TODO AD: the following two functions could be just one. PxU32 FeatherstoneArticulation::computeUnconstrainedVelocities( const ArticulationSolverDesc& desc, PxReal dt, PxU32& acCount, const PxVec3& gravity, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV, const PxReal invLengthScale) { FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation); ArticulationData& data = articulation->mArticulationData; data.setDt(dt); // AD: would be nicer to just have a list of all dirty articulations and process that one. // but that means we need to add a task dependency before because we'll get problems with multithreading // if we don't process the same lists. if (articulation->mJcalcDirty) { articulation->mJcalcDirty = false; articulation->jcalc(data); } articulation->computeUnconstrainedVelocitiesInternal(gravity, Z, deltaV, invLengthScale); const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; return articulation->setupSolverConstraints(data.getLinks(), data.getLinkCount(), fixBase, data, Z, acCount); } void FeatherstoneArticulation::computeUnconstrainedVelocitiesTGS( const ArticulationSolverDesc& desc, PxReal dt, const PxVec3& gravity, PxU64 contextID, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV, const PxReal invLengthScale) { PX_UNUSED(contextID); FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation); ArticulationData& data = articulation->mArticulationData; data.setDt(dt); // AD: would be nicer to just have a list of all dirty articulations and process that one. // but that means we need to add a task dependency before because we'll get problems with multithreading // if we don't process the same lists. if (articulation->mJcalcDirty) { articulation->mJcalcDirty = false; articulation->jcalc(data); } articulation->computeUnconstrainedVelocitiesInternal(gravity, Z, DeltaV, invLengthScale); } //void FeatherstoneArticulation::computeCounteractJointForce(const ArticulationSolverDesc& desc, ScratchData& /*scratchData*/, const PxVec3& gravity) //{ // const bool fixBase = mArticulationData.getCore()->flags & PxArticulationFlag::eFIX_BASE; // const PxU32 linkCount = mArticulationData.getLinkCount(); // const PxU32 totalDofs = mArticulationData.getDofs(); // //common data // computeRelativeTransform(mArticulationData); // jcalc(mArticulationData); // computeSpatialInertia(mArticulationData); // DyScratchAllocator allocator(desc.scratchMemory, desc.scratchMemorySize); // ScratchData tempScratchData; // allocateScratchSpatialData(allocator, linkCount, tempScratchData); // //PxReal* gravityJointForce = allocator.alloc<PxReal>(totalDofs); // //{ // // PxMemZero(gravityJointForce, sizeof(PxReal) * totalDofs); // // //compute joint force due to gravity // // tempScratchData.jointVelocities = NULL; // // tempScratchData.jointAccelerations = NULL; // // tempScratchData.jointForces = gravityJointForce; // // tempScratchData.externalAccels = NULL; // // if (fixBase) // // inverseDynamic(mArticulationData, gravity,tempScratchData); // // else // // inverseDynamicFloatingLink(mArticulationData, gravity, tempScratchData); // //} // ////PxReal* jointForce = mArticulationData.getJointForces(); // //PxReal* tempJointForce = mArticulationData.getTempJointForces(); // //{ // // PxMemZero(tempJointForce, sizeof(PxReal) * totalDofs); // // //compute joint force due to coriolis force // // tempScratchData.jointVelocities = mArticulationData.getJointVelocities(); // // tempScratchData.jointAccelerations = NULL; // // tempScratchData.jointForces = tempJointForce; // // tempScratchData.externalAccels = NULL; // // if (fixBase) // // inverseDynamic(mArticulationData, PxVec3(0.f), tempScratchData); // // else // // inverseDynamicFloatingLink(mArticulationData, PxVec3(0.f), tempScratchData); // //} // //PxReal* jointForce = mArticulationData.getJointForces(); // //for (PxU32 i = 0; i < mArticulationData.getDofs(); ++i) // //{ // // jointForce[i] = tempJointForce[i] - gravityJointForce[i]; // //} // //PxReal* jointForce = mArticulationData.getJointForces(); // PxReal* tempJointForce = mArticulationData.getTempJointForces(); // { // PxMemZero(tempJointForce, sizeof(PxReal) * totalDofs); // //compute joint force due to coriolis force // tempScratchData.jointVelocities = mArticulationData.getJointVelocities(); // tempScratchData.jointAccelerations = NULL; // tempScratchData.jointForces = tempJointForce; // tempScratchData.externalAccels = mArticulationData.getExternalAccelerations(); // if (fixBase) // inverseDynamic(mArticulationData, gravity, tempScratchData); // else // inverseDynamicFloatingLink(mArticulationData, gravity, tempScratchData); // } // PxReal* jointForce = mArticulationData.getJointForces(); // for (PxU32 i = 0; i < mArticulationData.getDofs(); ++i) // { // jointForce[i] = tempJointForce[i]; // } //} void FeatherstoneArticulation::updateArticulation(const PxVec3& gravity, const PxReal invLengthScale) { //Copy the link poses into a handy array. //Update the link separation vectors with the latest link poses. //Compute the motion matrices in the world frame uisng the latest link poses. { //constants const ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const ArticulationJointCoreData* jointCoreDatas = mArticulationData.getJointData(); const Cm::UnAlignedSpatialVector* jointDofMotionMatrices = mArticulationData.getMotionMatrix(); //outputs PxTransform* linkAccumulatedPosesW = mArticulationData.getAccumulatedPoses(); PxVec3* linkRsW = mArticulationData.getRw(); Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix(); computeRelativeTransformC2P( links, linkCount, jointCoreDatas, jointDofMotionMatrices, linkAccumulatedPosesW, linkRsW, jointDofMotionMatricesW); } //computeLinkVelocities(mArticulationData, scratchData); { //constants const PxReal dt = mArticulationData.mDt; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; const PxU32 nbLinks = mArticulationData.mLinkCount; const PxU32 nbJointDofs = mArticulationData.mJointVelocity.size(); const PxTransform* linkAccumulatedPosesW = mArticulationData.mAccumulatedPoses.begin(); const Cm::SpatialVector* linkExternalAccelsW = mArticulationData.mExternalAcceleration; const PxVec3* linkRsW = mArticulationData.mRw.begin(); //outputs Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.mWorldMotionMatrix.begin(); const ArticulationJointCoreData* jointCoreData = mArticulationData.mJointData; ArticulationLinkData* linkData = mArticulationData.mLinksData; ArticulationLink* links = mArticulationData.mLinks; Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.mMotionVelocities.begin(); Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin(); Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.mCorioliseVectors.begin(); Cm::SpatialVectorF* linkZAExtForcesW = mArticulationData.mZAForces.begin(); Cm::SpatialVectorF* linkZAIntForcesW = mArticulationData.mZAInternalForces.begin(); Dy::SpatialMatrix* linkSpatialArticulatedInertiasW = mArticulationData.mWorldSpatialArticulatedInertia.begin(); PxMat33* linkIsolatedSpatialArticulatedInertiasW = mArticulationData.mWorldIsolatedSpatialArticulatedInertia.begin(); PxReal* linkMasses = mArticulationData.mMasses.begin(); PxReal* jointDofVelocities = mArticulationData.mJointVelocity.begin(); Cm::SpatialVectorF& rootPreMotionVelocityW = mArticulationData.mRootPreMotionVelocity; PxVec3& comW = mArticulationData.mCOM; PxReal& invMass = mArticulationData.mInvSumMass; computeLinkStates( dt, invLengthScale, gravity, fixBase, nbLinks, linkAccumulatedPosesW, linkExternalAccelsW, linkRsW, jointDofMotionMatricesW, jointCoreData, linkData, links, linkMotionAccelerationsW, linkMotionVelocitiesW, linkZAExtForcesW, linkZAIntForcesW, linkCoriolisVectorsW, linkIsolatedSpatialArticulatedInertiasW, linkMasses, linkSpatialArticulatedInertiasW, nbJointDofs, jointDofVelocities, rootPreMotionVelocityW, comW, invMass); } { const PxU32 linkCount = mArticulationData.getLinkCount(); if (linkCount > 1) { const Cm::SpatialVectorF* ZAForcesExtW = mArticulationData.getSpatialZAVectors(); const Cm::SpatialVectorF* ZAForcesIntW = mArticulationData.mZAInternalForces.begin(); Cm::SpatialVectorF* ZAForcesTransmittedW = mArticulationData.getTransmittedForces(); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ZAForcesTransmittedW[linkID] = ZAForcesExtW[linkID] + ZAForcesIntW[linkID]; } } } { //Constant inputs. const ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const PxVec3* linkRsW = mArticulationData.getRw(); const ArticulationJointCoreData* jointData = mArticulationData.getJointData(); const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix(); const Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.getCorioliseVectors(); const PxReal* jointDofForces = mArticulationData.getJointForces(); //Values that we need now and will cache for later use. Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW(); InvStIs* linkInvStISW = mArticulationData.getInvStIS(); Cm::SpatialVectorF* jointDofISInvStIS = mArticulationData.getISInvStIS(); //[(I * s)/(s^T * I * s) PxReal* jointDofMinusStZExtW = mArticulationData.getMinusStZExt(); //[-s^t * ZExt] PxReal* jointDofQStZIntIcW = mArticulationData.getQStZIntIc(); //[Q - s^T*(ZInt + I*c)] //We need to compute these. Cm::SpatialVectorF* linkZAForcesExtW = mArticulationData.getSpatialZAVectors(); Cm::SpatialVectorF* linkZAForcesIntW = mArticulationData.mZAInternalForces.begin(); SpatialMatrix* linkSpatialInertiasW = mArticulationData.getWorldSpatialArticulatedInertia(); SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW(); computeArticulatedSpatialInertiaAndZ( links, linkCount, linkRsW, //constants jointData, //constants jointDofMotionMatricesW, linkCoriolisVectorsW, jointDofForces, //constants jointDofISW, linkInvStISW, jointDofISInvStIS, //compute and cache for later use jointDofMinusStZExtW, jointDofQStZIntIcW, //compute and cache for later use linkZAForcesExtW, linkZAForcesIntW, //outputs linkSpatialInertiasW, baseInvSpatialArticulatedInertiaW); //outputs } { //Constants const PxArticulationFlags& flags = mArticulationData.getArticulationFlags(); ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const ArticulationJointCoreData* jointData = mArticulationData.getJointData(); const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW(); const PxVec3* linkRsW = mArticulationData.getRw(); const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix(); const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW(); const InvStIs* linkInvStIsW = mArticulationData.getInvStIS(); const Cm::SpatialVectorF* jointDofISInvDW = mArticulationData.getISInvStIS(); //outputs SpatialImpulseResponseMatrix* linkImpulseResponseMatricesW = mArticulationData.getImpulseResponseMatrixWorld(); computeArticulatedResponseMatrix( flags, linkCount, //constants jointData, baseInvSpatialArticulatedInertiaW, //constants linkRsW, jointDofMotionMatricesW, //constants jointDofISW, linkInvStIsW, jointDofISInvDW, //constants links, linkImpulseResponseMatricesW); //outputs } { //Constant terms. const bool doIC = false; const PxReal dt = mArticulationData.getDt(); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; const ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData(); const Cm::SpatialVectorF* linkSpatialZAForcesExtW = mArticulationData.getSpatialZAVectors(); const Cm::SpatialVectorF* linkCoriolisForcesW = mArticulationData.getCorioliseVectors(); const PxVec3* linkRsW = mArticulationData.getRw(); const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix(); const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW(); //Cached constant terms. const InvStIs* linkInvStISW = mArticulationData.getInvStIS(); const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW(); const PxReal* jointDofMinusStZExtW = mArticulationData.getMinusStZExt(); //Output Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.getMotionVelocities(); Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.getMotionAccelerations(); PxReal* jointDofAccelerations = mArticulationData.getJointAccelerations(); PxReal* jointDofVelocities = mArticulationData.getJointVelocities(); PxReal* jointDofNewVelocities = mArticulationData.getJointNewVelocities(); computeLinkAcceleration( doIC, dt, fixBase, links, linkCount, jointDatas, linkSpatialZAForcesExtW, linkCoriolisForcesW, linkRsW, jointDofMotionMatricesW, baseInvSpatialArticulatedInertiaW, linkInvStISW, jointDofISW, jointDofMinusStZExtW, linkMotionAccelerationsW,linkMotionVelocitiesW, jointDofAccelerations, jointDofVelocities, jointDofNewVelocities); } { //constants const PxReal dt = mArticulationData.getDt(); const PxVec3& comW = mArticulationData.mCOM; const PxReal invSumMass = mArticulationData.mInvSumMass; const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.mBaseInvSpatialArticulatedInertiaW; const PxReal linkMaxLinearVelocity = mSolverDesc.core ? mSolverDesc.core->maxLinearVelocity : -1.0f; const PxReal linkMaxAngularVelocity = mSolverDesc.core ? mSolverDesc.core->maxAngularVelocity : -1.0f; const ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData(); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; const Cm::SpatialVectorF* linkSpatialZAIntForcesW = mArticulationData.getSpatialZAInternalVectors(); const Cm::SpatialVectorF* linkCoriolisVectorsW = mArticulationData.getCorioliseVectors(); const PxReal* linkMasses = mArticulationData.mMasses.begin(); const PxVec3* linkRsW = mArticulationData.getRw(); const PxTransform* linkAccumulatedPosesW = mArticulationData.getAccumulatedPoses(); const PxMat33* linkIsolatedSpatialArticulatedInertiasW = mArticulationData.mWorldIsolatedSpatialArticulatedInertia.begin(); const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW = mArticulationData.getWorldMotionMatrix(); //cached data. const InvStIs* linkInvStISW = mArticulationData.getInvStIS(); const Cm::SpatialVectorF* jointDofISW = mArticulationData.getIsW(); const PxReal* jointDofQStZIntIcW = mArticulationData.getQStZIntIc(); //output Cm::SpatialVectorF* linkMotionVelocitiesW = mArticulationData.getMotionVelocities(); Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.getMotionAccelerations(); Cm::SpatialVectorF* linkMotionAccelerationIntW = mArticulationData.mMotionAccelerationsInternal.begin(); PxReal* jointDofAccelerations = mArticulationData.getJointAccelerations(); PxReal* jointDofInternalAccelerations = mArticulationData.mJointInternalAcceleration.begin(); PxReal* jointVelocities = mArticulationData.getJointVelocities(); PxReal* jointNewVelocities = mArticulationData.mJointNewVelocity.begin(); computeLinkInternalAcceleration( dt, fixBase, comW, invSumMass, linkMaxLinearVelocity, linkMaxAngularVelocity, linkIsolatedSpatialArticulatedInertiasW, baseInvSpatialArticulatedInertiaW, links, linkCount, linkMasses, linkRsW, linkAccumulatedPosesW, linkSpatialZAIntForcesW, linkCoriolisVectorsW, jointDatas, jointDofMotionMatricesW, linkInvStISW, jointDofISW, jointDofQStZIntIcW, linkMotionAccelerationsW, linkMotionAccelerationIntW, linkMotionVelocitiesW, jointDofAccelerations, jointDofInternalAccelerations, jointVelocities, jointNewVelocities); } { const PxU32 linkCount = mArticulationData.getLinkCount(); Cm::SpatialVectorF* solverLinkSpatialDeltaVels = mArticulationData.mSolverLinkSpatialDeltaVels.begin(); PxMemZero(solverLinkSpatialDeltaVels, sizeof(Cm::SpatialVectorF) * linkCount); Cm::SpatialVectorF* solverLinkSpatialImpulses = mArticulationData.mSolverLinkSpatialImpulses.begin(); PxMemZero(solverLinkSpatialImpulses, sizeof(Cm::SpatialVectorF) * linkCount); Cm::SpatialVectorF* solverLinkSpatialForcesW = mArticulationData.mSolverLinkSpatialForces.begin(); PxMemZero(solverLinkSpatialForcesW, linkCount * sizeof(Cm::SpatialVectorF)); } } void FeatherstoneArticulation::computeUnconstrainedVelocitiesInternal( const PxVec3& gravity, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV, const PxReal invLengthScale) { //PX_PROFILE_ZONE("Articulations:computeUnconstrainedVelocities", 0); //mStaticConstraints.forceSize_Unsafe(0); mStatic1DConstraints.forceSize_Unsafe(0); mStaticContactConstraints.forceSize_Unsafe(0); PxMemZero(mArticulationData.mNbStatic1DConstraints.begin(), mArticulationData.mNbStatic1DConstraints.size()*sizeof(PxU32)); PxMemZero(mArticulationData.mNbStaticContactConstraints.begin(), mArticulationData.mNbStaticContactConstraints.size() * sizeof(PxU32)); //const PxU32 linkCount = mArticulationData.getLinkCount(); mArticulationData.init(); updateArticulation(gravity, invLengthScale); ScratchData scratchData; scratchData.motionVelocities = mArticulationData.getMotionVelocities(); scratchData.motionAccelerations = mArticulationData.getMotionAccelerations(); scratchData.coriolisVectors = mArticulationData.getCorioliseVectors(); scratchData.spatialZAVectors = mArticulationData.getSpatialZAVectors(); scratchData.jointAccelerations = mArticulationData.getJointAccelerations(); scratchData.jointVelocities = mArticulationData.getJointVelocities(); scratchData.jointPositions = mArticulationData.getJointPositions(); scratchData.jointForces = mArticulationData.getJointForces(); scratchData.externalAccels = mArticulationData.getExternalAccelerations(); if (mArticulationData.mLinkCount > 1) { //use individual zero acceleration force(we copy the initial Z value to the transmitted force buffers in initLink()) scratchData.spatialZAVectors = mArticulationData.getTransmittedForces(); computeZAForceInv(mArticulationData, scratchData); computeJointTransmittedFrictionForce(mArticulationData, scratchData, Z, DeltaV); } //the dirty flag is used in inverse dynamic mArticulationData.setDataDirty(true); //zero zero acceleration vector in the articulation data so that we can use this buffer to accumulated //impulse for the contacts/constraints in the PGS/TGS solvers //PxMemZero(mArticulationData.getSpatialZAVectors(), sizeof(Cm::SpatialVectorF) * linkCount); //Reset deferredQstZ and root deferredZ! PxMemZero(mArticulationData.mDeferredQstZ.begin(), sizeof(PxReal)*mArticulationData.getDofs()); PxMemZero(mArticulationData.mJointConstraintForces.begin(), sizeof(PxReal)*mArticulationData.getDofs()); mArticulationData.mRootDeferredZ = Cm::SpatialVectorF::Zero(); // solver progress counters maxSolverNormalProgress = 0; maxSolverFrictionProgress = 0; solverProgress = 0; numTotalConstraints = 0; for (PxU32 a = 0; a < mArticulationData.getLinkCount(); ++a) { mArticulationData.mAccumulatedPoses[a] = mArticulationData.getLink(a).bodyCore->body2World; mArticulationData.mPreTransform[a] = mArticulationData.getLink(a).bodyCore->body2World; mArticulationData.mDeltaQ[a] = PxQuat(PxIdentity); } } void FeatherstoneArticulation::enforcePrismaticLimits(PxReal& jPosition, ArticulationJointCore* joint) { const PxU32 dofId = joint->dofIds[0]; if (joint->motion[dofId] == PxArticulationMotion::eLIMITED) { if (jPosition < (joint->limits[dofId].low)) jPosition = joint->limits[dofId].low; if (jPosition > (joint->limits[dofId].high)) jPosition = joint->limits[dofId].high; } } PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat, const PxQuat& newRot, const PxQuat& pBody2WorldRot, PxReal* jPositions, const Cm::UnAlignedSpatialVector* motionMatrix, const PxU32 dofs) { PxQuat newParentToChild = (newRot.getConjugate() * pBody2WorldRot).getNormalized(); if(newParentToChild.w < 0.f) newParentToChild = -newParentToChild; //PxQuat newParentToChild = (newRot * pBody2WorldRot.getConjugate()).getNormalized(); PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate(); if(jointRotation.w < 0.0f) jointRotation = -jointRotation; PxReal radians; PxVec3 axis; jointRotation.toRadiansAndUnitAxis(radians, axis); axis *= radians; for (PxU32 d = 0; d < dofs; ++d) { jPositions[d] = -motionMatrix[d].top.dot(axis); } return newParentToChild; } PxQuat computeSphericalJointPositions(const PxQuat& /*relativeQuat*/, const PxQuat& newRot, const PxQuat& pBody2WorldRot) { PxQuat newParentToChild = (newRot.getConjugate() * pBody2WorldRot).getNormalized(); if (newParentToChild.w < 0.f) newParentToChild = -newParentToChild; /*PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate(); PxReal radians; jointRotation.toRadiansAndUnitAxis(radians, axis); axis *= radians;*/ return newParentToChild; } void FeatherstoneArticulation::computeAndEnforceJointPositions(ArticulationData& data) { ArticulationLink* links = data.getLinks(); const PxU32 linkCount = data.getLinkCount(); ArticulationJointCoreData* jointData = data.getJointData(); PxReal* jointPositions = data.getJointPositions(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; ArticulationJointCore* joint = link.inboundJoint; ArticulationJointCoreData& jointDatum = jointData[linkID]; PxReal* jPositions = &jointPositions[jointDatum.jointOffset]; if (joint->jointType == PxArticulationJointType::eSPHERICAL) { ArticulationLink& pLink = links[link.parent]; //const PxTransform pBody2World = pLink.bodyCore->body2World; const PxU32 dof = jointDatum.dof; computeSphericalJointPositions(data.mRelativeQuat[linkID], link.bodyCore->body2World.q, pLink.bodyCore->body2World.q, jPositions, &data.getMotionMatrix(jointDatum.jointOffset), dof); } else if (joint->jointType == PxArticulationJointType::eREVOLUTE) { PxReal jPos = jPositions[0]; if (jPos > PxTwoPi) jPos -= PxTwoPi*2.f; else if (jPos < -PxTwoPi) jPos += PxTwoPi*2.f; jPos = PxClamp(jPos, -PxTwoPi*2.f, PxTwoPi*2.f); jPositions[0] = jPos; } else if(joint->jointType == PxArticulationJointType::ePRISMATIC) { enforcePrismaticLimits(jPositions[0], joint); } } } void FeatherstoneArticulation::updateJointProperties(PxReal* jointNewVelocities, PxReal* jointVelocities, PxReal* jointAccelerations) { using namespace Dy; const PxU32 dofs = mArticulationData.getDofs(); const PxReal invDt = 1.f / mArticulationData.getDt(); for (PxU32 i = 0; i < dofs; ++i) { const PxReal jNewVel = jointNewVelocities[i]; PxReal delta = jNewVel - jointVelocities[i]; jointVelocities[i] = jNewVel; jointAccelerations[i] += delta * invDt; } } void FeatherstoneArticulation::propagateLinksDown(ArticulationData& data, PxReal* jointVelocities, PxReal* jointPositions, Cm::SpatialVectorF* motionVelocities) { ArticulationLink* links = mArticulationData.getLinks(); ArticulationJointCoreData* jointData = mArticulationData.getJointData(); const PxQuat* const PX_RESTRICT relativeQuats = mArticulationData.mRelativeQuat.begin(); const PxU32 linkCount = mArticulationData.getLinkCount(); const PxReal dt = data.getDt(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; ArticulationJointCoreData& jointDatum = jointData[linkID]; //ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID); //const PxTransform oldTransform = preTransforms[linkID]; ArticulationLink& pLink = links[link.parent]; const PxTransform pBody2World = pLink.bodyCore->body2World; ArticulationJointCore* joint = link.inboundJoint; PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; PxQuat newParentToChild; PxQuat newWorldQ; PxVec3 r; const PxVec3 childOffset = -joint->childPose.p; const PxVec3 parentOffset = joint->parentPose.p; PxTransform& body2World = link.bodyCore->body2World; const PxQuat relativeQuat = relativeQuats[linkID]; switch (joint->jointType) { case PxArticulationJointType::ePRISMATIC: { const PxReal delta = (jVelocity[0]) * dt; PxReal jPos = jPosition[0] + delta; enforcePrismaticLimits(jPos, joint); jPosition[0] = jPos; newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].bottom; r = e + d + u * jPos; break; } case PxArticulationJointType::eREVOLUTE: { //use positional iteration JointVelociy to integrate const PxReal delta = (jVelocity[0]) * dt; PxReal jPos = jPosition[0] + delta; if (jPos > PxTwoPi) jPos -= PxTwoPi*2.f; else if (jPos < -PxTwoPi) jPos += PxTwoPi*2.f; jPos = PxClamp(jPos, -PxTwoPi*2.f, PxTwoPi*2.f); jPosition[0] = jPos; const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top; PxQuat jointRotation = PxQuat(-jPos, u); if (jointRotation.w < 0) //shortest angle. jointRotation = -jointRotation; newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const PxReal delta = (jVelocity[0]) * dt; PxReal jPos = jPosition[0] + delta; jPosition[0] = jPos; const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top; PxQuat jointRotation = PxQuat(-jPos, u); if (jointRotation.w < 0) //shortest angle. jointRotation = -jointRotation; newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eSPHERICAL: { if (1) { const PxTransform oldTransform = data.mAccumulatedPoses[linkID]; #if 0 Cm::SpatialVectorF worldVel = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.mRw[linkID], motionVelocities[link.parent]); for (PxU32 i = 0; i < jointDatum.dof; ++i) { const PxReal delta = (jVelocity[i]) * dt; const PxReal jPos = jPosition[i] + delta; jPosition[i] = jPos; worldVel.top += data.mWorldMotionMatrix[jointDatum.jointOffset + i].top * jVelocity[i]; worldVel.bottom += data.mWorldMotionMatrix[jointDatum.jointOffset + i].bottom * jVelocity[i]; } motionVelocities[linkID] = worldVel; #else Cm::SpatialVectorF worldVel = motionVelocities[linkID]; //Cm::SpatialVectorF parentVel = motionVelocities[link.parent]; //PxVec3 relVel = oldTransform.rotateInv(worldVel.top - parentVel.top); //for (PxU32 i = 0; i < jointDatum.dof; ++i) //{ // const PxReal jVel = mArticulationData.mMotionMatrix[jointDatum.jointOffset + i].top.dot(relVel); // jVelocity[i] = jVel; // /*const PxReal delta = jVel * dt; // jPosition[i] += delta;*/ //} #endif //Gp and Gc are centre of mass poses of parent(p) and child(c) in the world frame. //Introduce Q(v, dt) = PxExp(worldAngVel*dt); //Lp and Lc are joint frames of parent(p) and child(c) in the parent and child body frames. //The rotational part of Gc will be updated as follows: //GcNew.q = Q(v, dt) * Gc.q //We could use GcNew for the new child pose but it isn't in quite the right form //to use in a generic way with all the other joint types supported here. //Here's what we do. //Step 1) add Identity to the rhs. //GcNew.q = Gp.q * Gp.q^-1 * Q(v, dt) * Gc.q //Step 2) Remember that (A * B^-1) = (B * A ^-1)^-1. //Gp.q^-1 * Q(v, dt) * Gc.q = (Q(v, dt) * Gc.q)^-1 * Gp.q //GcNew.q = Gp.q * (Q(v, dt) * Gc.q)^-1 * Gp.q //Write this out using the variable names used here. //The final form is: //body2World.q = pBody2World.q * newParent2Child //The translational part of GcNew will be updated as follows: //GcNew.p = Gp.p + Gp.q.rotate(Lp.p) - GcNew.q.rotate(Lc.p) // = Gp.p + GcNew.q * (GcNew.q^-1 * Gp.q).rotate(Lp.p) - GcNew.q.rotate(Lc.p) // = Gp.p + GcNew.q.rotate((GcNew.q^-1 * Gp.q).rotate(Lp.p) - GcNew.q.rotate(Lc.p) // = Gp.p + GcNew.q.rotate((GcNew.q^-1 * Gp.q).rotate(Lp.p) - Lc.p) //Write this out using the variable names used here. //body2World.p = pBody2World.p + body2World.q.rotate(newParent2Child.rotate(parentOffset) + childOffset) //Put r = newParent2Child.rotate(parentOffset) + childOffset //and we have the final form used here: //body2World.p = pBody2World.p + body2World.q.rotate(r) //Now let's think about the rotation angles. //Imagine that the joint frames are aligned in the world frame. //The pose(Gc0) of the child body in the world frame will satisfy: //Gp * Lp = Gc0 * Lc //We can solve for Gc0: //Gc0 = Gp * Lp * Lc^-1 //Gc0 = Gp * (Lc * Lp^-1)^-1 //Now compute the rotation J that rotates from Gc0 to GcNew. //We seek a rotation J in the child body frame (in the aligned state so at Gc0) that satisfies: //Gc0 * J = GcNew //Let's actually solve for J^-1 (because that's what we do here). //J^-1 = GcNew^-1 * Gp * (Lc * Lp^-1)^-1 //From J^-1 we can retrieve three rotation angles in the child body frame. //We actually want the angles for J. We observe that //toAngles(J^-1) = -toAngles(J) //Our rotation angles r_b commensurate with J are then: //r_b = -toAngles(J^-1) //From r_b we can compute the angles r_j in the child joint frame. // r_j = Lc.rotateInv(r_b) //Remember that we began our calculation with aligned frames. //We can equally apply r_j to the parent joint frame and achieve the same outcome. //GcNew = Q(v, dt) * Gc.q PxVec3 worldAngVel = worldVel.top; newWorldQ = PxExp(worldAngVel*dt) * oldTransform.q; //GcNew^-1 * Gp newParentToChild = computeSphericalJointPositions(relativeQuat, newWorldQ, pBody2World.q); //J^-1 = GcNew^-1 * Gp * (Lc * Lp^-1)^-1 PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate(); if(jointRotation.w < 0.0f) jointRotation = -jointRotation; //PxVec3 axis = toRotationVector(jointRotation); /*PxVec3 axis = jointRotation.getImaginaryPart(); for (PxU32 i = 0; i < jointDatum.dof; ++i) { PxVec3 sa = data.getMotionMatrix(jointDatum.jointOffset + i).top; PxReal angle = -compAng(PxVec3(sa.x, sa.y, sa.z).dot(axis), jointRotation.w); jPosition[i] = angle; }*/ //r_j = -Lc.rotateInv(r_b) PxVec3 axis; PxReal angle; jointRotation.toRadiansAndUnitAxis(angle, axis); axis *= angle; for (PxU32 i = 0; i < jointDatum.dof; ++i) { PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top; PxReal ang = -sa.dot(axis); jPosition[i] = ang; } const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; } break; } case PxArticulationJointType::eFIX: { //this is fix joint so joint don't have velocity newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; break; } default: PX_ASSERT(false); break; } body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized(); body2World.p = pBody2World.p + body2World.q.rotate(r); PX_ASSERT(body2World.isSane()); PX_ASSERT(body2World.isValid()); } } void FeatherstoneArticulation::updateBodies(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt) { updateBodies(static_cast<FeatherstoneArticulation*>(desc.articulation), tempDeltaV, dt, true); } void FeatherstoneArticulation::updateBodiesTGS(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt) { updateBodies(static_cast<FeatherstoneArticulation*>(desc.articulation), tempDeltaV, dt, false); } void FeatherstoneArticulation::updateBodies(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* tempDeltaV, PxReal dt, bool integrateJointPositions) { ArticulationData& data = articulation->mArticulationData; ArticulationLink* links = data.getLinks(); const PxU32 linkCount = data.getLinkCount(); Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities(); Cm::SpatialVectorF* posMotionVelocities = data.getPosIterMotionVelocities(); Cm::SpatialVector* externalAccels = data.getExternalAccelerations(); Cm::SpatialVector zero = Cm::SpatialVector::zero(); data.setDt(dt); const PxU32 nbSensors = data.mNbSensors; bool doForces = data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES || nbSensors; //update joint velocities/accelerations due to contacts/constraints. if (data.mJointDirty) { //update delta joint velocity and motion velocity due to velocity iteration changes //update motionVelocities PxcFsFlushVelocity(*articulation, tempDeltaV, doForces); } Cm::SpatialVectorF momentum0 = Cm::SpatialVectorF::Zero(); PxVec3 posMomentum(0.f); const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; //PGS if (!fixBase) { const PxVec3 COM = data.mCOM; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { PxReal mass = data.mMasses[linkID]; momentum0.top += motionVelocities[linkID].bottom * mass; posMomentum += posMotionVelocities[linkID].bottom * mass; } PxVec3 rootVel = momentum0.top * data.mInvSumMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { PxReal mass = data.mMasses[linkID]; PxVec3 offsetMass = (data.mPreTransform[linkID].p - COM)*mass; PxVec3 angMom = (data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top) + offsetMass.cross(motionVelocities[linkID].bottom - rootVel); momentum0.bottom += angMom; } } if (!integrateJointPositions) { //TGS for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { links[linkID].bodyCore->body2World = data.mAccumulatedPoses[linkID].getNormalized(); } articulation->computeAndEnforceJointPositions(data); } else { if (!fixBase) { const PxTransform& preTrans = data.mAccumulatedPoses[0]; const Cm::SpatialVectorF& posVel = data.getPosIterMotionVelocity(0); updateRootBody(posVel, preTrans, data, dt); } //using the original joint velocities and delta velocities changed in the positional iter to update joint position/body transform articulation->propagateLinksDown(data, data.getPosIterJointVelocities(), data.getJointPositions(), data.getPosIterMotionVelocities()); } //Fix up momentum based on changes in pos. Only currently possible with non-fixed base if (!fixBase) { PxVec3 COM = data.mLinks[0].bodyCore->body2World.p * data.mMasses[0]; data.mAccumulatedPoses[0] = data.mLinks[0].bodyCore->body2World; PxVec3 sumLinMom = data.mMotionVelocities[0].bottom * data.mMasses[0]; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { PxU32 parent = data.mLinks[linkID].parent; const PxTransform childPose = data.mLinks[linkID].bodyCore->body2World; data.mAccumulatedPoses[linkID] = childPose; PxVec3 rw = childPose.p - data.mAccumulatedPoses[parent].p; data.mRw[linkID] = rw; ArticulationJointCoreData& jointDatum = data.mJointData[linkID]; const PxReal* jVelocity = &data.mJointNewVelocity[jointDatum.jointOffset]; Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-rw, data.mMotionVelocities[parent]); Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero(); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { PxReal jVel = jVelocity[ind]; //deltaV += data.mWorldMotionMatrix[jointDatum.jointOffset + ind] * jVel; deltaV += data.mMotionMatrix[jointDatum.jointOffset + ind] * jVel; } vel.top += childPose.rotate(deltaV.top); vel.bottom += childPose.rotate(deltaV.bottom); data.mMotionVelocities[linkID] = vel; PxReal mass = data.mMasses[linkID]; COM += childPose.p * mass; sumLinMom += vel.bottom * mass; } COM *= data.mInvSumMass; PxMat33 sumInertia(PxZero); PxVec3 sumAngMom(0.f); PxVec3 rootLinVel = sumLinMom * data.mInvSumMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { PxReal mass = data.mMasses[linkID]; const PxVec3 offset = data.mAccumulatedPoses[linkID].p - COM; PxMat33 inertia; PxMat33 R(data.mAccumulatedPoses[linkID].q); const PxVec3 invInertiaDiag = data.getLink(linkID).bodyCore->inverseInertia; PxVec3 inertiaDiag(1.f / invInertiaDiag.x, 1.f / invInertiaDiag.y, 1.f / invInertiaDiag.z); const PxVec3 offsetMass = offset * mass; Cm::transformInertiaTensor(inertiaDiag, R, inertia); //Only needed for debug validation #if PX_DEBUG data.mWorldIsolatedSpatialArticulatedInertia[linkID] = inertia; #endif sumInertia += translateInertia(inertia, mass, offset); sumAngMom += inertia * motionVelocities[linkID].top; sumAngMom += offsetMass.cross(motionVelocities[linkID].bottom - rootLinVel); } PxMat33 invSumInertia = sumInertia.getInverse(); PxReal aDenom = sumAngMom.magnitude(); PxReal angRatio = aDenom == 0.f ? 0.f : momentum0.bottom.magnitude() / aDenom; PxVec3 angMomDelta = sumAngMom * (angRatio - 1.f); PxVec3 angDelta = invSumInertia * angMomDelta; #if 0 motionVelocities[0].top += angDelta; Cm::SpatialVectorF* motionAccelerations = data.getMotionAccelerations(); motionAccelerations[0] = Cm::SpatialVectorF(angDelta, PxVec3(0.f)); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { Cm::SpatialVectorF deltaV = Dy::FeatherstoneArticulation::translateSpatialVector(-data.getRw(linkID), motionAccelerations[data.getLink(linkID).parent]); motionVelocities[linkID] += deltaV; motionAccelerations[linkID] = deltaV; sumLinMom += deltaV.bottom*data.mMasses[linkID]; } #else for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxVec3 offset = (data.getAccumulatedPoses()[linkID].p - COM); Cm::SpatialVectorF velChange(angDelta, -offset.cross(angDelta)); motionVelocities[linkID] += velChange; PxReal mass = data.mMasses[linkID]; sumLinMom += velChange.bottom * mass; } #endif PxVec3 linDelta = (momentum0.top - sumLinMom)*data.mInvSumMass; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { motionVelocities[linkID].bottom += linDelta; } //if (integrateJointPositions) { PxVec3 predictedCOM = data.mCOM + posMomentum * (data.mInvSumMass * dt); PxVec3 posCorrection = predictedCOM - COM; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; link.bodyCore->body2World.p += posCorrection; } COM += posCorrection; } #if PX_DEBUG && 0 const bool validateMomentum = false; if (validateMomentum) { PxVec3 rootVel = sumLinMom * data.mInvSumMass + linDelta; Cm::SpatialVectorF momentum2(PxVec3(0.f), PxVec3(0.f)); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { const PxReal mass = data.mMasses[linkID]; PxVec3 offsetMass = (data.getLink(linkID).bodyCore->body2World.p - COM) * mass; const PxVec3 angMom = data.mWorldIsolatedSpatialArticulatedInertia[linkID] * motionVelocities[linkID].top + offsetMass.cross(motionVelocities[linkID].bottom - rootVel); momentum2.bottom += angMom; momentum2.top += motionVelocities[linkID].bottom * mass; } printf("COM = (%f, %f, %f)\n", COM.x, COM.y, COM.z); printf("%i: linMom0 %f, linMom1 %f, angMom0 %f, angMom1 %f\n\n\n", count, momentum0.top.magnitude(), momentum2.top.magnitude(), momentum0.bottom.magnitude(), momentum2.bottom.magnitude()); } #endif } { //update joint velocity/accelerations PxReal* jointVelocities = data.getJointVelocities(); PxReal* jointAccelerations = data.getJointAccelerations(); PxReal* jointNewVelocities = data.getJointNewVelocities(); articulation->updateJointProperties(jointNewVelocities, jointVelocities, jointAccelerations); } const PxReal invDt = 1.f/dt; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; PxsBodyCore* bodyCore = link.bodyCore; bodyCore->linearVelocity = motionVelocities[linkID].bottom; bodyCore->angularVelocity = motionVelocities[linkID].top; //zero external accelerations if(!(link.bodyCore->mFlags & PxRigidBodyFlag::eRETAIN_ACCELERATIONS)) externalAccels[linkID] = zero; } if (doForces) { data.mSolverLinkSpatialForces[0] *= invDt; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { data.mSolverLinkSpatialForces[linkID] = (data.mWorldSpatialArticulatedInertia[linkID] * data.mSolverLinkSpatialForces[linkID]) * invDt; } if (data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES) { //const PxU32 dofCount = data.getDofs(); PxReal* constraintForces = data.getJointConstraintForces(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const Cm::SpatialVectorF spatialForce = data.mSolverLinkSpatialForces[linkID] - (data.mZAForces[linkID] + data.mZAInternalForces[linkID]); ArticulationJointCoreData& jointDatum = data.mJointData[linkID]; const PxU32 offset = jointDatum.jointOffset; const PxU32 dofCount = jointDatum.dof; for (PxU32 i = 0; i < dofCount; ++i) { const PxReal jointForce = data.mWorldMotionMatrix[offset + i].innerProduct(spatialForce); constraintForces[offset + i] = jointForce; } } } for (PxU32 s = 0; s < nbSensors; ++s) { ArticulationSensor* sensor = data.mSensors[s]; const PxU32 linkID = sensor->mLinkID; const PxTransform& transform = data.mPreTransform[linkID]; const PxTransform& relTrans = sensor->mRelativePose; //Offset to translate the impulse by const PxVec3 offset = transform.rotate(relTrans.p); Cm::SpatialVectorF spatialForce(PxVec3(0.f), PxVec3(0.f)); if (sensor->mFlags & PxArticulationSensorFlag::eCONSTRAINT_SOLVER_FORCES) spatialForce += data.mSolverLinkSpatialForces[linkID]; if (sensor->mFlags & PxArticulationSensorFlag::eFORWARD_DYNAMICS_FORCES) spatialForce -= (data.mZAForces[linkID] + data.mZAInternalForces[linkID]); // translate from body to sensor frame (offset is body->sensor) spatialForce = translateSpatialVector(-offset, spatialForce); if (sensor->mFlags & PxArticulationSensorFlag::eWORLD_FRAME) { data.mSensorForces[s].force = spatialForce.top; data.mSensorForces[s].torque = spatialForce.bottom; } else { //Now we need to rotate into the sensor's frame. Forces are currently reported in world frame const PxQuat rotate = transform.q * relTrans.q; data.mSensorForces[s].force = rotate.rotateInv(spatialForce.top); data.mSensorForces[s].torque = rotate.rotateInv(spatialForce.bottom); } } } } void FeatherstoneArticulation::updateRootBody(const Cm::SpatialVectorF& motionVelocity, const PxTransform& preTransform, ArticulationData& data, const PxReal dt) { ArticulationLink* links = data.getLinks(); //body2World store new body transform integrated from solver linear/angular velocity PX_ASSERT(motionVelocity.top.isFinite()); PX_ASSERT(motionVelocity.bottom.isFinite()); ArticulationLink& baseLink = links[0]; PxsBodyCore* baseBodyCore = baseLink.bodyCore; //(1) project the current body's velocity (based on its pre-pose) to the geometric COM that we're integrating around... PxVec3 comLinVel = motionVelocity.bottom; //using the position iteration motion velocity to compute the body2World PxVec3 newP = (preTransform.p) + comLinVel * dt; PxQuat deltaQ = PxExp(motionVelocity.top*dt); baseBodyCore->body2World = PxTransform(newP, (deltaQ* preTransform.q).getNormalized()); PX_ASSERT(baseBodyCore->body2World.isFinite() && baseBodyCore->body2World.isValid()); } void FeatherstoneArticulation::getJointAcceleration(const PxVec3& gravity, PxArticulationCache& cache) { PX_SIMD_GUARD if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getJointAcceleration() commonInit need to be called first to initialize data!"); return; } const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = cache.jointVelocity; scratchData.jointForces = cache.jointForce; //compute individual link's spatial inertia tensor //[0, M] //[I, 0] computeSpatialInertia(mArticulationData); computeLinkVelocities(mArticulationData, scratchData); //compute individual zero acceleration force computeZ(mArticulationData, gravity, scratchData); //compute corolis and centrifugal force computeC(mArticulationData, scratchData); computeArticulatedSpatialInertiaAndZ_NonSeparated(mArticulationData, scratchData); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; //we have initialized motionVelocity and motionAcceleration to be zero in the root link if //fix based flag is raised //ArticulationLinkData& baseLinkDatum = mArticulationData.getLinkData(0); Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors; Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; if (!fixBase) { SpatialMatrix inverseArticulatedInertia = mArticulationData.mWorldSpatialArticulatedInertia[0].getInverse(); motionAccelerations[0] = -(inverseArticulatedInertia * spatialZAForces[0]); } #if FEATHERSTONE_DEBUG else { PX_ASSERT(isSpatialVectorZero(motionAccelerations[0])); } #endif PxReal* jointAccelerations = cache.jointAcceleration; //calculate acceleration for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = mArticulationData.getLink(linkID); //SpatialTransform p2C = linkDatum.childToParent.getTranspose(); //Cm::SpatialVectorF pMotionAcceleration = mArticulationData.mChildToParent[linkID].transposeTransform(motionAccelerations[link.parent]); Cm::SpatialVectorF pMotionAcceleration = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.getRw(linkID), motionAccelerations[link.parent]); ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); //calculate jointAcceleration PxReal* jA = &jointAccelerations[jointDatum.jointOffset]; const InvStIs& invStIs = mArticulationData.mInvStIs[linkID]; computeJointAccelerationW(jointDatum.dof, pMotionAcceleration, &mArticulationData.mIsW[jointDatum.jointOffset], invStIs, &mArticulationData.qstZIc[jointDatum.jointOffset], jA); Cm::SpatialVectorF motionAcceleration(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { motionAcceleration.top += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jA[ind]; motionAcceleration.bottom += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jA[ind]; } motionAccelerations[linkID] = pMotionAcceleration + coriolisVectors[linkID] + motionAcceleration; PX_ASSERT(motionAccelerations[linkID].isFinite()); } allocator->free(tempMemory); } }//namespace Dy }
105,900
C++
37.135038
167
0.723985
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPartition.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. #include "DyConstraintPartition.h" #include "DyArticulationUtils.h" #include "DySoftBody.h" #include "foundation/PxHashMap.h" #include "DyFeatherstoneArticulation.h" #define INTERLEAVE_SELF_CONSTRAINTS 1 namespace physx { namespace Dy { namespace { class RigidBodyClassification : public RigidBodyClassificationBase { public: RigidBodyClassification(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) : RigidBodyClassificationBase(bodies, bodyCount, bodyStride) { } /* PX_FORCE_INLINE void getProgress(const PxSolverConstraintDesc& desc, PxU32& bodyAProgress, PxU32& bodyBProgress) const { bodyAProgress = desc.bodyA->solverProgress; bodyBProgress = desc.bodyB->solverProgress; }*/ PX_FORCE_INLINE void getProgressRequirements(const PxSolverConstraintDesc& desc, PxU32& progressA, PxU32& progressB) const { const uintptr_t indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mBodyStride; const uintptr_t indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mBodyStride; const bool activeA = indexA < mBodyCount; const bool activeB = indexB < mBodyCount; if (activeA) progressA = desc.bodyA->maxSolverFrictionProgress++; else progressA = 0; if (activeB) progressB = desc.bodyB->maxSolverFrictionProgress++; else progressB = 0; } PX_FORCE_INLINE void clearState() { for(PxU32 a = 0; a < mBodySize; a+= mBodyStride) reinterpret_cast<PxSolverBody*>(mBodies+a)->solverProgress = 0; } PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxArray<PxU32>& numConstraintsPerPartition) { for(PxU32 a = 0; a < mBodySize; a += mBodyStride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies+a); body.solverProgress = 0; PxU32 requiredSize = PxU32(body.maxSolverNormalProgress + body.maxSolverFrictionProgress); if(requiredSize > numConstraintsPerPartition.size()) { numConstraintsPerPartition.resize(requiredSize); } for(PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b) { numConstraintsPerPartition[body.maxSolverNormalProgress + b]++; } } } }; class ExtendedRigidBodyClassification : public ExtendedRigidBodyClassificationBase { const bool mForceStaticCollisionsToSolver; // PT: why is this one not present in the immediate mode version? public: ExtendedRigidBodyClassification(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations, bool forceStaticCollisionsToSolver) : ExtendedRigidBodyClassificationBase (bodies, numBodies, stride, articulations, numArticulations), mForceStaticCollisionsToSolver (forceStaticCollisionsToSolver) { // PT: why is this loop not present in the immediate mode version? for (PxU32 i = 0; i < mNumArticulations; ++i) mArticulations[i]->mArticulationIndex = PxTo16(i); } // PT: this version is slightly different from the immediate mode version, see 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(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { 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 { FeatherstoneArticulation* articulationA = getArticulationA(desc); indexA=mBodyCount+ articulationA->mArticulationIndex; //bodyAProgress = articulationA->getFsDataPtr()->solverProgress; bodyAProgress = articulationA->solverProgress; activeA = true; } if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { indexB=uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies)/mStride; activeB = indexB < mBodyCount; hasStatic = hasStatic || !activeB; bodyBProgress = activeB ? desc.bodyB->solverProgress : 0; } else { FeatherstoneArticulation* articulationB = getArticulationB(desc); indexB=mBodyCount+ articulationB->mArticulationIndex; activeB = true; bodyBProgress = articulationB->solverProgress; } return !hasStatic; } /* PX_FORCE_INLINE void getProgress(const PxSolverConstraintDesc& desc, PxU32& bodyAProgress, PxU32& bodyBProgress) const { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { bodyAProgress = desc.bodyA->solverProgress; } else { FeatherstoneArticulation* articulationA = getArticulationA(desc); bodyAProgress = articulationA->solverProgress; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { bodyBProgress = desc.bodyB->solverProgress; } else { FeatherstoneArticulation* articulationB = getArticulationB(desc); bodyBProgress = articulationB->solverProgress; } }*/ PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { desc.bodyA->solverProgress = bodyAProgress; desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition); } else { FeatherstoneArticulation* articulationA = getArticulationA(desc); articulationA->solverProgress = bodyAProgress; articulationA->maxSolverNormalProgress = PxMax(articulationA->maxSolverNormalProgress, availablePartition); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { desc.bodyB->solverProgress = bodyBProgress; desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition); } else { FeatherstoneArticulation* articulationB = getArticulationB(desc); articulationB->solverProgress = bodyBProgress; articulationB->maxSolverNormalProgress = PxMax(articulationB->maxSolverNormalProgress, availablePartition); } } PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { desc.bodyA->solverProgress = bodyAProgress; } else { FeatherstoneArticulation* articulationA = getArticulationA(desc); articulationA->solverProgress = bodyAProgress; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { desc.bodyB->solverProgress = bodyBProgress; } else { FeatherstoneArticulation* articulationB = getArticulationB(desc); articulationB->solverProgress = bodyBProgress; } } PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool& activeA, bool& activeB) { if (activeA) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) desc.bodyA->maxSolverFrictionProgress++; else { FeatherstoneArticulation* articulationA = getArticulationA(desc); if(!articulationA->willStoreStaticConstraint() || mForceStaticCollisionsToSolver) articulationA->maxSolverFrictionProgress++; } } if (activeB) { if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) desc.bodyB->maxSolverFrictionProgress++; else { FeatherstoneArticulation* articulationB = getArticulationB(desc); if (!articulationB->willStoreStaticConstraint() || mForceStaticCollisionsToSolver) articulationB->maxSolverFrictionProgress++; } } } PX_FORCE_INLINE void getProgressRequirements(const PxSolverConstraintDesc& desc, PxU32& progressA, PxU32& progressB) const { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { uintptr_t indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mStride; if(indexA < mBodyCount) progressA = desc.bodyA->maxSolverFrictionProgress++; else progressA = 0; } else { FeatherstoneArticulation* articulationA = getArticulationA(desc); progressA = articulationA->maxSolverFrictionProgress++; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { uintptr_t indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mStride; if(indexB < mBodyCount) progressB = desc.bodyB->maxSolverFrictionProgress++; else progressB = 0; } else { if (desc.articulationA != desc.articulationB) { FeatherstoneArticulation* articulationB = getArticulationB(desc); progressB = articulationB->maxSolverFrictionProgress++; } else progressB = progressA; } } PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const { if (activeA) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++); } else { FeatherstoneArticulation* articulationA = getArticulationA(desc); //Attempt to store static constraints on the articulation (only supported with the reduced coordinate articulations). //This acts as an optimization if(!mForceStaticCollisionsToSolver && articulationA->storeStaticConstraint(desc)) return 0xffffffff; return PxU32(articulationA->maxSolverNormalProgress + articulationA->maxSolverFrictionProgress++); } } else if (activeB) { if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++); } else { FeatherstoneArticulation* articulationB = getArticulationB(desc); //Attempt to store static constraints on the articulation (only supported with the reduced coordinate articulations). //This acts as an optimization if (!mForceStaticCollisionsToSolver && articulationB->storeStaticConstraint(desc)) return 0xffffffff; return PxU32(articulationB->maxSolverNormalProgress + articulationB->maxSolverFrictionProgress++); } } return 0xffffffff; } PX_FORCE_INLINE void clearState() { for(PxU32 a = 0; a < mBodySize; a+= mStride) reinterpret_cast<PxSolverBody*>(mBodies+a)->solverProgress = 0; for(PxU32 a = 0; a < mNumArticulations; ++a) (reinterpret_cast<FeatherstoneArticulation*>(mArticulations[a]))->solverProgress = 0; } PX_FORCE_INLINE void reserveSpaceForStaticConstraints(PxArray<PxU32>& numConstraintsPerPartition) { for(PxU32 a = 0; a < mBodySize; a+= mStride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(mBodies+a); body.solverProgress = 0; PxU32 requiredSize = PxU32(body.maxSolverNormalProgress + body.maxSolverFrictionProgress); if(requiredSize > numConstraintsPerPartition.size()) { numConstraintsPerPartition.resize(requiredSize); } for(PxU32 b = 0; b < body.maxSolverFrictionProgress; ++b) { numConstraintsPerPartition[body.maxSolverNormalProgress + b]++; } } for(PxU32 a = 0; a < mNumArticulations; ++a) { FeatherstoneArticulation* articulation = reinterpret_cast<FeatherstoneArticulation*>(mArticulations[a]); articulation->solverProgress = 0; PxU32 requiredSize = PxU32(articulation->maxSolverNormalProgress + articulation->maxSolverFrictionProgress); if(requiredSize > numConstraintsPerPartition.size()) { numConstraintsPerPartition.resize(requiredSize); } for(PxU32 b = 0; b < articulation->maxSolverFrictionProgress; ++b) { numConstraintsPerPartition[articulation->maxSolverNormalProgress + b]++; } } } }; template <typename Classification> static PxU32 classifyConstraintDesc(const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification, PxArray<PxU32>& numConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaTempConstraintDescriptors, PxU32 maxPartitions) { const PxSolverConstraintDesc* _desc = descs; const PxU32 numConstraintsMin1 = numConstraints - 1; PxU32 numUnpartitionedConstraints = 0; numConstraintsPerPartition.forceSize_Unsafe(32); PxMemZero(numConstraintsPerPartition.begin(), sizeof(PxU32) * 32); 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) { eaTempConstraintDescriptors[numUnpartitionedConstraints++] = *_desc; continue; } const PxU32 partitionBit = (1u << availablePartition); if (activeA) partitionsA |= partitionBit; if(activeB) partitionsB |= partitionBit; } numConstraintsPerPartition[availablePartition]++; availablePartition++; classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition)); } else { classification.recordStaticConstraint(*_desc, activeA, activeB); } } PxU32 partitionStartIndex = 0; while (numUnpartitionedConstraints > 0) { classification.clearState(); partitionStartIndex += 32; if(maxPartitions <= partitionStartIndex) break; //Keep partitioning the un-partitioned constraints and blat the whole thing to 0! numConstraintsPerPartition.resize(32 + numConstraintsPerPartition.size()); PxMemZero(numConstraintsPerPartition.begin() + partitionStartIndex, sizeof(PxU32) * 32); PxU32 newNumUnpartitionedConstraints = 0; PxU32 partitionsA, partitionsB; bool activeA, activeB; uintptr_t indexA, indexB; for (PxU32 i = 0; i < numUnpartitionedConstraints; ++i) { const PxSolverConstraintDesc& desc = eaTempConstraintDescriptors[i]; classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB); PxU32 availablePartition; { const PxU32 combinedMask = (~partitionsA & ~partitionsB); availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask); if (availablePartition == MAX_NUM_PARTITIONS) { //Need to shuffle around unpartitioned constraints... eaTempConstraintDescriptors[newNumUnpartitionedConstraints++] = desc; continue; } const PxU32 partitionBit = (1u << availablePartition); if (activeA) partitionsA |= partitionBit; if (activeB) partitionsB |= partitionBit; } /*desc.bodyA->solverProgress = partitionsA; desc.bodyB->solverProgress = partitionsB;*/ availablePartition += partitionStartIndex; numConstraintsPerPartition[availablePartition]++; availablePartition++; classification.storeProgress(desc, partitionsA, partitionsB, PxU16(availablePartition)); /* desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, PxU16(availablePartition)); desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, PxU16(availablePartition));*/ } numUnpartitionedConstraints = newNumUnpartitionedConstraints; } classification.reserveSpaceForStaticConstraints(numConstraintsPerPartition); return numUnpartitionedConstraints; } template <typename Classification> static PxU32 writeConstraintDesc( const PxSolverConstraintDesc* PX_RESTRICT descs, PxU32 numConstraints, Classification& classification, PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* eaTempConstraintDescriptors, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc, PxU32 maxPartitions, PxU32 numOverflows) { PX_UNUSED(eaTempConstraintDescriptors); const PxSolverConstraintDesc* _desc = descs; const PxU32 numConstraintsMin1 = numConstraints - 1; PxU32 numUnpartitionedConstraints = 0; PxU32 numStaticConstraints = 0; 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) { eaTempConstraintDescriptors[numUnpartitionedConstraints++] = *_desc; continue; } const PxU32 partitionBit = (1u << availablePartition); if(activeA) partitionsA |= partitionBit; if(activeB) partitionsB |= partitionBit; } classification.storeProgress(*_desc, partitionsA, partitionsB, PxU16(availablePartition + 1)); eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[availablePartition]++] = *_desc; } else { //Just count the number of static constraints and store in maxSolverFrictionProgress... PxU32 index = classification.getStaticContactWriteIndex(*_desc, activeA, activeB); if (index != 0xffffffff) { eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[index]++] = *_desc; } else numStaticConstraints++; } } PxU32 partitionStartIndex = 0; while (numUnpartitionedConstraints > 0) { classification.clearState(); partitionStartIndex += 32; if(partitionStartIndex >= maxPartitions) break; PxU32 newNumUnpartitionedConstraints = 0; PxU32 partitionsA, partitionsB; bool activeA, activeB; uintptr_t indexA, indexB; for (PxU32 i = 0; i < numUnpartitionedConstraints; ++i) { const PxSolverConstraintDesc& desc = eaTempConstraintDescriptors[i]; /* PxU32 partitionsA=desc.bodyA->solverProgress; PxU32 partitionsB=desc.bodyB->solverProgress;*/ classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB); PxU32 availablePartition; { const PxU32 combinedMask = (~partitionsA & ~partitionsB); availablePartition = combinedMask == 0 ? MAX_NUM_PARTITIONS : PxLowestSetBit(combinedMask); if (availablePartition == MAX_NUM_PARTITIONS) { //Need to shuffle around unpartitioned constraints... eaTempConstraintDescriptors[newNumUnpartitionedConstraints++] = desc; continue; } const PxU32 partitionBit = (1u << availablePartition); if (activeA) partitionsA |= partitionBit; if (activeB) partitionsB |= partitionBit; } /*desc.bodyA->solverProgress = partitionsA; desc.bodyB->solverProgress = partitionsB; */ classification.storeProgress(desc, partitionsA, partitionsB); availablePartition += partitionStartIndex; eaOrderedConstraintDesc[numOverflows + accumulatedConstraintsPerPartition[availablePartition]++] = desc; } numUnpartitionedConstraints = newNumUnpartitionedConstraints; } return numStaticConstraints; } static void outputOverflowConstraints( PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* overflowConstraints, PxU32 nbOverflowConstraints, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDesc) { //Firstly, we resize and shuffle accumulatedConstraintsPerPartition accumulatedConstraintsPerPartition.resize(accumulatedConstraintsPerPartition.size()+1); PxU32 partitionCount = accumulatedConstraintsPerPartition.size(); while(partitionCount-- > 1) { accumulatedConstraintsPerPartition[partitionCount] = accumulatedConstraintsPerPartition[partitionCount -1] + nbOverflowConstraints; } accumulatedConstraintsPerPartition[0] = nbOverflowConstraints; //Now fill in the constraints and work out the iter for (PxU32 i = 0; i < nbOverflowConstraints; ++i) { eaOrderedConstraintDesc[i] = overflowConstraints[i]; } } } #define PX_NORMALIZE_PARTITIONS 1 #if PX_NORMALIZE_PARTITIONS #ifdef REMOVED_UNUSED template<typename Classification> PxU32 normalizePartitions(PxArray<PxU32>& accumulatedConstraintsPerPartition, PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDescriptors, PxU32 numConstraintDescriptors, PxArray<PxU32>& bitField, const Classification& classification, PxU32 numBodies, PxU32 numArticulations) { PxU32 numPartitions = 0; PxU32 prevAccumulation = 0; for(; numPartitions < accumulatedConstraintsPerPartition.size() && accumulatedConstraintsPerPartition[numPartitions] > prevAccumulation; prevAccumulation = accumulatedConstraintsPerPartition[numPartitions++]); PxU32 targetSize = (numPartitions == 0 ? 0 : (numConstraintDescriptors)/numPartitions); bitField.reserve((numBodies + numArticulations + 31)/32); bitField.forceSize_Unsafe((numBodies + numArticulations + 31)/32); for(PxU32 i = numPartitions; i > 0; i--) { PxU32 partitionIndex = i-1; //Build the partition mask... PxU32 startIndex = partitionIndex == 0 ? 0 : accumulatedConstraintsPerPartition[partitionIndex-1]; PxU32 endIndex = accumulatedConstraintsPerPartition[partitionIndex]; //If its greater than target size, there's nothing that will be pulled into it from earlier partitions if((endIndex - startIndex) >= targetSize) continue; PxMemZero(bitField.begin(), sizeof(PxU32)*bitField.size()); for(PxU32 a = startIndex; a < endIndex; ++a) { PxSolverConstraintDesc& desc = eaOrderedConstraintDescriptors[a]; uintptr_t indexA, indexB; bool activeA, activeB; PxU32 partitionsA, partitionsB; classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB); if (activeA) bitField[PxU32(indexA) / 32] |= (1u << (indexA & 31)); if(activeB) bitField[PxU32(indexB)/32] |= (1u << (indexB & 31)); } bool bTerm = false; for(PxU32 a = partitionIndex; a > 0 && !bTerm; --a) { PxU32 pInd = a-1; PxU32 si = pInd == 0 ? 0 : accumulatedConstraintsPerPartition[pInd-1]; PxU32 ei = accumulatedConstraintsPerPartition[pInd]; for(PxU32 b = ei; b > si && !bTerm; --b) { PxU32 ind = b-1; PxSolverConstraintDesc& desc = eaOrderedConstraintDescriptors[ind]; uintptr_t indexA, indexB; bool activeA, activeB; PxU32 partitionsA, partitionsB; classification.classifyConstraint(desc, indexA, indexB, activeA, activeB, partitionsA, partitionsB); bool canAdd = true; if(activeA && (bitField[PxU32(indexA)/32] & (1u << (indexA & 31)))) canAdd = false; if(activeB && (bitField[PxU32(indexB)/32] & (1u << (indexB & 31)))) canAdd = false; if(canAdd) { PxSolverConstraintDesc tmp = eaOrderedConstraintDescriptors[ind]; if(activeA) bitField[PxU32(indexA)/32] |= (1u << (indexA & 31)); if(activeB) bitField[PxU32(indexB)/32] |= (1u << (indexB & 31)); PxU32 index = ind; for(PxU32 c = pInd; c < partitionIndex; ++c) { PxU32 newIndex = --accumulatedConstraintsPerPartition[c]; if(index != newIndex) eaOrderedConstraintDescriptors[index] = eaOrderedConstraintDescriptors[newIndex]; index = newIndex; } if(index != ind) eaOrderedConstraintDescriptors[index] = tmp; if((accumulatedConstraintsPerPartition[partitionIndex] - accumulatedConstraintsPerPartition[partitionIndex-1]) >= targetSize) { bTerm = true; break; } } } } } PxU32 partitionCount = 0; PxU32 lastPartitionCount = 0; for (PxU32 a = 0; a < numPartitions; ++a) { const PxU32 constraintCount = accumulatedConstraintsPerPartition[a]; accumulatedConstraintsPerPartition[partitionCount] = constraintCount; if (constraintCount != lastPartitionCount) { lastPartitionCount = constraintCount; partitionCount++; } } accumulatedConstraintsPerPartition.forceSize_Unsafe(partitionCount); return partitionCount; } #endif #endif PxU32 partitionContactConstraints(ConstraintPartitionArgs& args) { PxU32 maxPartition = 0; //Unpack the input data. const PxU32 numBodies = args.mNumBodies; const PxU32 numArticulations = args.mNumArticulationPtrs; const PxU32 numConstraintDescriptors = args.mNumContactConstraintDescriptors; const PxSolverConstraintDesc* PX_RESTRICT eaConstraintDescriptors = args.mContactConstraintDescriptors; PxSolverConstraintDesc* PX_RESTRICT eaOrderedConstraintDescriptors = args.mOrderedContactConstraintDescriptors; PxSolverConstraintDesc* PX_RESTRICT eaOverflowConstraintDescriptors = args.mOverflowConstraintDescriptors; PxArray<PxU32>& constraintsPerPartition = *args.mConstraintsPerPartition; constraintsPerPartition.forceSize_Unsafe(0); const PxU32 stride = args.mStride; for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies + offset); body.solverProgress = 0; //We re-use maxSolverFrictionProgress and maxSolverNormalProgress to record the //maximum partition used by dynamic constraints and the number of static constraints affecting //a body. We use this to make partitioning much cheaper and be able to support an arbitrary number of dynamic partitions. body.maxSolverFrictionProgress = 0; body.maxSolverNormalProgress = 0; } PxU32 numOrderedConstraints=0; PxU32 numStaticConstraints = 0; PxU32 numOverflows = 0; if(numArticulations == 0) { RigidBodyClassification classification(args.mBodies, numBodies, stride); numOverflows = classifyConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition, eaOverflowConstraintDescriptors, args.mMaxPartitions); PxU32 accumulation = 0; for(PxU32 a = 0; a < constraintsPerPartition.size(); ++a) { PxU32 count = constraintsPerPartition[a]; constraintsPerPartition[a] = accumulation; accumulation += count; } for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies + offset); PxPrefetchLine(&args.mBodies[a], 256); 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; } writeConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition, eaOverflowConstraintDescriptors, eaOrderedConstraintDescriptors, args.mMaxPartitions, numOverflows); numOrderedConstraints = numConstraintDescriptors; //Next step, let's slot the overflow partitions into the first slot and work out targets for them... if (numOverflows) { outputOverflowConstraints(constraintsPerPartition, eaOverflowConstraintDescriptors, numOverflows, eaOrderedConstraintDescriptors); } } else { const ArticulationSolverDesc* articulationDescs=args.mArticulationPtrs; PX_ALLOCA(_eaArticulations, Dy::FeatherstoneArticulation*, numArticulations); Dy::FeatherstoneArticulation** eaArticulations = _eaArticulations; for(PxU32 i=0;i<numArticulations;i++) { FeatherstoneArticulation* articulation = articulationDescs[i].articulation; eaArticulations[i]= articulation; articulation->solverProgress = 0; articulation->maxSolverFrictionProgress = 0; articulation->maxSolverNormalProgress = 0; } ExtendedRigidBodyClassification classification(args.mBodies, numBodies, stride, eaArticulations, numArticulations, args.mForceStaticConstraintsToSolver); numOverflows = classifyConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition, eaOverflowConstraintDescriptors, args.mMaxPartitions); PxU32 accumulation = 0; for(PxU32 a = 0; a < constraintsPerPartition.size(); ++a) { PxU32 count = constraintsPerPartition[a]; constraintsPerPartition[a] = accumulation; accumulation += count; } for(PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += stride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(args.mBodies+offset); 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 < numArticulations; ++a) { FeatherstoneArticulation* articulation = eaArticulations[a]; articulation->solverProgress = 0; articulation->maxSolverFrictionProgress = 0; } numStaticConstraints = writeConstraintDesc(eaConstraintDescriptors, numConstraintDescriptors, classification, constraintsPerPartition, eaOverflowConstraintDescriptors, eaOrderedConstraintDescriptors, args.mMaxPartitions, numOverflows); numOrderedConstraints = numConstraintDescriptors - numStaticConstraints; if (numOverflows) { outputOverflowConstraints(constraintsPerPartition, eaOverflowConstraintDescriptors, numOverflows, eaOrderedConstraintDescriptors); } } const PxU32 numConstraintsDifferentBodies=numOrderedConstraints; //PX_ASSERT(numConstraintsDifferentBodies == numConstraintDescriptors); //Now handle the articulated self-constraints. PxU32 totalConstraintCount = numConstraintsDifferentBodies; args.mNumDifferentBodyConstraints=numConstraintsDifferentBodies; args.mNumSelfConstraints=totalConstraintCount-numConstraintsDifferentBodies; args.mNumStaticConstraints = numStaticConstraints; args.mNumOverflowConstraints = numOverflows; //if (args.enhancedDeterminism) { PxU32 prevPartitionSize = 0; maxPartition = 0; for (PxU32 a = 0; a < constraintsPerPartition.size(); ++a, maxPartition++) { if (constraintsPerPartition[a] == prevPartitionSize) break; prevPartitionSize = constraintsPerPartition[a]; } } return maxPartition; } void processOverflowConstraints(PxU8* bodies, PxU32 bodyStride, PxU32 numBodies, Dy::ArticulationSolverDesc* articulationDescs, PxU32 numArticulations, PxSolverConstraintDesc* constraints, PxU32 numConstraints) { for (PxU32 a = 0, offset = 0; a < numBodies; ++a, offset += bodyStride) { PxSolverBody& body = *reinterpret_cast<PxSolverBody*>(bodies + offset); 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; } if (numConstraints == 0) return; if (numArticulations == 0) { RigidBodyClassification classification(bodies, numBodies, bodyStride); for (PxU32 i = 0; i < numConstraints; ++i) { PxU32 progressA, progressB; classification.getProgressRequirements(constraints[i], progressA, progressB); constraints[i].progressA = PxTo16(progressA); constraints[i].progressB = PxTo16(progressB); } } else { PX_ALLOCA(_eaArticulations, Dy::FeatherstoneArticulation*, numArticulations); Dy::FeatherstoneArticulation** eaArticulations = _eaArticulations; for (PxU32 i = 0; i<numArticulations; i++) { FeatherstoneArticulation* articulation = articulationDescs[i].articulation; eaArticulations[i] = articulation; articulation->solverProgress = 0; articulation->maxSolverFrictionProgress = 0; //articulation->maxSolverNormalProgress = 0; } ExtendedRigidBodyClassification classification(bodies, numBodies, bodyStride, eaArticulations, numArticulations, false); for (PxU32 i = 0; i < numConstraints; ++i) { PxU32 progressA, progressB; classification.getProgressRequirements(constraints[i], progressA, progressB); constraints[i].progressA = PxTo16(progressA); constraints[i].progressB = PxTo16(progressB); } } } } }
33,895
C++
33.482197
185
0.753356
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DyCorrelationBuffer.h" #include "DySolverConstraintExtShared.h" #include "DyArticulationCpuGpu.h" #include "DyFeatherstoneArticulation.h" using namespace physx::Gu; namespace physx { namespace Dy { // constraint-gen only, since these use getVelocity methods // which aren't valid during the solver phase //PX_INLINE void computeFrictionTangents(const aos::Vec3V& vrel,const aos::Vec3V& unitNormal, aos::Vec3V& t0, aos::Vec3V& t1) //{ // using namespace aos; // //PX_ASSERT(PxAbs(unitNormal.magnitude()-1)<1e-3f); // // t0 = V3Sub(vrel, V3Scale(unitNormal, V3Dot(unitNormal, vrel))); // const FloatV ll = V3Dot(t0, t0); // // if (FAllGrtr(ll, FLoad(1e10f))) //can set as low as 0. // { // t0 = V3Scale(t0, FRsqrt(ll)); // t1 = V3Cross(unitNormal, t0); // } // else // PxNormalToTangents(unitNormal, t0, t1); //fallback //} PxReal SolverExtBody::projectVelocity(const PxVec3& linear, const PxVec3& angular) const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { return mBodyData->projectVelocity(linear, angular); } else { const Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex); const FloatV fv = velocity.dot(Cm::SpatialVector(linear, angular)); PxF32 f; FStore(fv, &f); return f; /*PxF32 f; FStore(getVelocity(*mFsData)[mLinkIndex].dot(Cm::SpatialVector(linear, angular)), &f); return f;*/ } } PxReal SolverExtBody::getCFM() const { return (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) ? 0.f : mArticulation->getCfm(mLinkIndex); } aos::FloatV SolverExtBody::projectVelocity(const aos::Vec3V& linear, const aos::Vec3V& angular) const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { return V3SumElems(V3Add(V3Mul(V3LoadA(mBodyData->linearVelocity), linear), V3Mul(V3LoadA(mBodyData->angularVelocity), angular))); } else { const Cm::SpatialVectorV velocity = mArticulation->getLinkVelocity(mLinkIndex); return velocity.dot(Cm::SpatialVectorV(linear, angular)); } } PxVec3 SolverExtBody::getLinVel() const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return mBodyData->linearVelocity; else { const Vec3V linear = mArticulation->getLinkVelocity(mLinkIndex).linear; PxVec3 result; V3StoreU(linear, result); /*PxVec3 result; V3StoreU(getVelocity(*mFsData)[mLinkIndex].linear, result);*/ return result; } } PxVec3 SolverExtBody::getAngVel() const { if(mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return mBodyData->angularVelocity; else { const Vec3V angular = mArticulation->getLinkVelocity(mLinkIndex).angular; PxVec3 result; V3StoreU(angular, result); /*PxVec3 result; V3StoreU(getVelocity(*mFsData)[mLinkIndex].angular, result);*/ return result; } } aos::Vec3V SolverExtBody::getLinVelV() const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return V3LoadA(mBodyData->linearVelocity); else { return mArticulation->getLinkVelocity(mLinkIndex).linear; } } Vec3V SolverExtBody::getAngVelV() const { if (mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return V3LoadA(mBodyData->angularVelocity); else { return mArticulation->getLinkVelocity(mLinkIndex).angular; } } Cm::SpatialVectorV SolverExtBody::getVelocity() const { if(mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) return Cm::SpatialVectorV(V3LoadA(mBodyData->linearVelocity), V3LoadA(mBodyData->angularVelocity)); else return mArticulation->getLinkVelocity(mLinkIndex); } Cm::SpatialVector createImpulseResponseVector(const PxVec3& linear, const PxVec3& angular, const SolverExtBody& body) { if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { return Cm::SpatialVector(linear, body.mBodyData->sqrtInvInertia * angular); } return Cm::SpatialVector(linear, angular); } Cm::SpatialVectorV createImpulseResponseVector(const aos::Vec3V& linear, const aos::Vec3V& angular, const SolverExtBody& body) { if (body.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { return Cm::SpatialVectorV(linear, M33MulV3(M33Load(body.mBodyData->sqrtInvInertia), angular)); } return Cm::SpatialVectorV(linear, angular); } 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) { PxReal response; allowSelfCollision = false; // right now self-collision with contacts crashes the solver //KS - knocked this out to save some space on SPU if(allowSelfCollision && b0.mLinkIndex!=PxSolverConstraintDesc::RIGID_BODY && b0.mArticulation == b1.mArticulation && 0) { /*ArticulationHelper::getImpulseSelfResponse(*b0.mFsData,b0.mLinkIndex, impulse0, deltaV0, b1.mLinkIndex, impulse1, deltaV1);*/ b0.mArticulation->getImpulseSelfResponse(b0.mLinkIndex, b1.mLinkIndex, Z, impulse0.scale(dom0, angDom0), impulse1.scale(dom1, angDom1), deltaV0, deltaV1); response = impulse0.dot(deltaV0) + impulse1.dot(deltaV1); } else { if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV0.linear = impulse0.linear * b0.mBodyData->invMass * dom0; deltaV0.angular = impulse0.angular * angDom0; } else { b0.mArticulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0); } response = impulse0.dot(deltaV0); if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV1.linear = impulse1.linear * b1.mBodyData->invMass * dom1; deltaV1.angular = impulse1.angular * angDom1; } else { b1.mArticulation->getImpulseResponse( b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1); } response += impulse1.dot(deltaV1); } return response; } FloatV getImpulseResponse(const SolverExtBody& b0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, const FloatV& dom0, const FloatV& angDom0, const SolverExtBody& b1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1, const FloatV& dom1, const FloatV& angDom1, Cm::SpatialVectorV* Z, bool /*allowSelfCollision*/) { Vec3V response; { if (b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV0.linear = V3Scale(impulse0.linear, FMul(FLoad(b0.mBodyData->invMass), dom0)); deltaV0.angular = V3Scale(impulse0.angular, angDom0); } else { b0.mArticulation->getImpulseResponse(b0.mLinkIndex, Z, impulse0.scale(dom0, angDom0), deltaV0); } response = V3Add(V3Mul(impulse0.linear, deltaV0.linear), V3Mul(impulse0.angular, deltaV0.angular)); if (b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) { deltaV1.linear = V3Scale(impulse1.linear, FMul(FLoad(b1.mBodyData->invMass), dom1)); deltaV1.angular = V3Scale(impulse1.angular, angDom1); } else { b1.mArticulation->getImpulseResponse(b1.mLinkIndex, Z, impulse1.scale(dom1, angDom1), deltaV1); } response = V3Add(response, V3Add(V3Mul(impulse1.linear, deltaV1.linear), V3Mul(impulse1.angular, deltaV1.angular))); } return V3SumElems(response); } 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, const PxReal restDist, PxU8* frictionDataPtr, PxReal ccdMaxContactDist, Cm::SpatialVectorF* Z, const PxReal offsetSlop) { // 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 bool haveFriction = PX_IR(n.staticFriction) > 0 || PX_IR(n.dynamicFriction) > 0;*/ const FloatV ccdMaxSeparation = FLoad(ccdMaxContactDist); const Vec3VArg solverOffsetSlop = V3Load(offsetSlop); PxU8* PX_RESTRICT ptr = workspace; const FloatV zero = FZero(); //KS - TODO - this should all be done in SIMD to avoid LHS //const PxF32 maxPenBias0 = b0.mLinkIndex == PxSolverConstraintDesc::NO_LINK ? b0.mBodyData->penBiasClamp : getMaxPenBias(*b0.mFsData)[b0.mLinkIndex]; //const PxF32 maxPenBias1 = b1.mLinkIndex == PxSolverConstraintDesc::NO_LINK ? b1.mBodyData->penBiasClamp : getMaxPenBias(*b1.mFsData)[b1.mLinkIndex]; PxF32 maxPenBias0; PxF32 maxPenBias1; if (b0.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY) { maxPenBias0 = b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex); } else maxPenBias0 = b0.mBodyData->penBiasClamp; if (b1.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY) { maxPenBias1 = b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex); } else maxPenBias1 = b1.mBodyData->penBiasClamp; const FloatV maxPenBias = FLoad(PxMax(maxPenBias0, maxPenBias1)); const Vec3V frame0p = V3LoadU(bodyFrame0.p); const Vec3V frame1p = V3LoadU(bodyFrame1.p); const Cm::SpatialVectorV vel0 = b0.getVelocity(); const Cm::SpatialVectorV vel1 = b1.getVelocity(); const FloatV quarter = FLoad(0.25f); const FloatV d0 = FLoad(invMassScale0); const FloatV d1 = FLoad(invMassScale1); const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM())); const FloatV angD0 = FLoad(invInertiaScale0); const FloatV angD1 = FLoad(invInertiaScale1); Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = V4Zero(); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d0); staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W=V4SetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W, d1); const FloatV restDistance = FLoad(restDist); PxU32 frictionPatchWritebackAddrIndex = 0; PxPrefetchLine(c.contactID); PxPrefetchLine(c.contactID, 128); 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); PxU8 flags = 0; 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); //0==anchorCount is allowed if all the contacts in the manifold have a large offset. const PxContactPoint* contactBase0 = buffer + c.contactPatches[c.correlationListHeads[i]].start; const PxReal coefficient = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && frictionPatch.anchorCount == 2) ? 0.5f : 1.f; const PxReal staticFriction = contactBase0->staticFriction * coefficient; const PxReal dynamicFriction = contactBase0->dynamicFriction * coefficient; 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)); SolverContactHeader* PX_RESTRICT header = reinterpret_cast<SolverContactHeader*>(ptr); ptr += sizeof(SolverContactHeader); PxPrefetchLine(ptr + 128); PxPrefetchLine(ptr + 256); PxPrefetchLine(ptr + 384); const bool haveFriction = (disableStrongFriction == 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 = PxTo8(DY_SC_TYPE_EXT_CONTACT); header->flags = flags; const FloatV restitution = FLoad(contactBase0->restitution); const FloatV damping = FLoad(contactBase0->damping); header->staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W = staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W; header->angDom0 = invInertiaScale0; header->angDom1 = invInertiaScale1; const PxU32 pointStride = sizeof(SolverContactPointExt); const PxU32 frictionStride = sizeof(SolverContactFrictionExt); const Vec3V normal = V3LoadU(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal); FloatV accumImpulse = FZero(); const FloatV norVel0 = V3Dot(normal, vel0.linear); const FloatV norVel1 = V3Dot(normal, vel1.linear); 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++) { const PxContactPoint& contact = contactBase[j]; SolverContactPointExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointExt*>(p); p += pointStride; accumImpulse = FAdd(accumImpulse, setupExtSolverContact(b0, b1, d0, d1, angD0, angD1, frame0p, frame1p, normal, invDt, invDtp8, dt, restDistance, maxPenBias, restitution, bounceThreshold, contact, *solverContact, ccdMaxSeparation, Z, vel0, vel1, cfm, solverOffsetSlop, norVel0, norVel1, damping)); } ptr = p; } accumImpulse = FMul(FDiv(accumImpulse, FLoad(PxF32(contactCount))), quarter); header->normal_minAppliedImpulseForFrictionW = V4SetW(Vec4V_From_Vec3V(normal), accumImpulse); PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr); PxMemZero(forceBuffer, sizeof(PxF32) * contactCount); ptr += sizeof(PxF32) * ((contactCount + 3) & (~3)); header->broken = 0; if(haveFriction) { //const Vec3V normal = Vec3V_From_PxVec3(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal); //Vec3V normalS = V3LoadA(buffer[c.contactPatches[c.correlationListHeads[i]].start].normal); const Vec3V linVrel = V3Sub(vel0.linear, vel1.linear); //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(normal, t0Cross); const VecCrossV t1Cross = V3PrepareCross(t1); //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++) { SolverContactFrictionExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionExt*>(ptr); ptr += frictionStride; SolverContactFrictionExt* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionExt*>(ptr); ptr += frictionStride; Vec3V ra = V3LoadU(bodyFrame0.q.rotate(frictionPatch.body0Anchors[j])); Vec3V rb = V3LoadU(bodyFrame1.q.rotate(frictionPatch.body1Anchors[j])); Vec3V error = V3Sub(V3Add(ra, frame0p), V3Add(rb, frame1p)); { 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); Cm::SpatialVectorV deltaV0, deltaV1; const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1); FloatV resp = FAdd(cfm, getImpulseResponse(b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z))); const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FDiv(p8, resp), zero); const PxU32 index = c.contactPatches[c.correlationListHeads[i]].start; FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t0); if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) targetVel = FSub(targetVel, b0.projectVelocity(t0, raXn)); else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) targetVel = FAdd(targetVel, b1.projectVelocity(t0, rbXn)); f0->normalXYZ_appliedForceW = V4SetW(t0, zero); f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier); f0->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FMul(V3Dot(t0, error), invDt)); f0->linDeltaVA = deltaV0.linear; f0->angDeltaVA = deltaV0.angular; f0->linDeltaVB = deltaV1.linear; f0->angDeltaVB = deltaV1.angular; 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); Cm::SpatialVectorV deltaV0, deltaV1; const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t1, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t1), V3Neg(rbXn), b1); FloatV resp = FAdd(cfm, getImpulseResponse(b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z))); //const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FMul(p8, FRecip(resp)), zero); const FloatV velMultiplier = FSel(FIsGrtr(resp, FLoad(DY_ARTICULATION_MIN_RESPONSE)), FDiv(p8, resp), zero); const PxU32 index = c.contactPatches[c.correlationListHeads[i]].start; FloatV targetVel = V3Dot(V3LoadA(buffer[index].targetVel), t1); if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) targetVel = FSub(targetVel, b0.projectVelocity(t1, raXn)); else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) targetVel = FAdd(targetVel, b1.projectVelocity(t1, rbXn)); f1->normalXYZ_appliedForceW = V4SetW(t1, zero); f1->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), velMultiplier); f1->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FMul(V3Dot(t1, error), invDt)); f1->linDeltaVA = deltaV0.linear; f1->angDeltaVA = deltaV0.angular; f1->linDeltaVB = deltaV1.linear; f1->angDeltaVB = deltaV1.angular; FStore(targetVel, &f1->targetVel); } } } frictionPatchWritebackAddrIndex++; } } } }
21,350
C++
36.067708
174
0.739813
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSContactPrepBlock.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "PxcNpContactPrepShared.h" #include "DyTGSDynamics.h" using namespace physx; using namespace Gu; #include "PxsMaterialManager.h" #include "DyContactPrepShared.h" #include "DyConstraintPrep.h" #include "DyTGS.h" namespace physx { namespace Dy { inline bool ValidateVec4(const Vec4V v) { PX_ALIGN(16, PxVec4 vF); aos::V4StoreA(v, &vF.x); return vF.isFinite(); } PX_FORCE_INLINE void QuatRotate4(const Vec4VArg qx, const Vec4VArg qy, const Vec4VArg qz, const Vec4VArg qw, const Vec4VArg vx, const Vec4VArg vy, const Vec4VArg vz, Vec4V& rX, Vec4V& rY, Vec4V& rZ) { /* const PxVec3 qv(x,y,z); return (v*(w*w-0.5f) + (qv.cross(v))*w + qv*(qv.dot(v)))*2; */ const Vec4V two = V4Splat(FLoad(2.f)); const Vec4V nhalf = V4Splat(FLoad(-0.5f)); const Vec4V w2 = V4MulAdd(qw, qw, nhalf); const Vec4V ax = V4Mul(vx, w2); const Vec4V ay = V4Mul(vy, w2); const Vec4V az = V4Mul(vz, w2); const Vec4V crX = V4NegMulSub(qz, vy, V4Mul(qy, vz)); const Vec4V crY = V4NegMulSub(qx, vz, V4Mul(qz, vx)); const Vec4V crZ = V4NegMulSub(qy, vx, V4Mul(qx, vy)); const Vec4V tempX = V4MulAdd(crX, qw, ax); const Vec4V tempY = V4MulAdd(crY, qw, ay); const Vec4V tempZ = V4MulAdd(crZ, qw, az); Vec4V dotuv = V4Mul(qx, vx); dotuv = V4MulAdd(qy, vy, dotuv); dotuv = V4MulAdd(qz, vz, dotuv); rX = V4Mul(V4MulAdd(qx, dotuv, tempX), two); rY = V4Mul(V4MulAdd(qy, dotuv, tempY), two); rZ = V4Mul(V4MulAdd(qz, dotuv, tempZ), two); } struct SolverContactHeaderStepBlock { enum { eHAS_MAX_IMPULSE = 1 << 0, eHAS_TARGET_VELOCITY = 1 << 1 }; PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU8 numFrictionConstr; PxU8 flag; PxU8 flags[4]; //KS - used for write-back only PxU8 numNormalConstrs[4]; PxU8 numFrictionConstrs[4]; //Vec4V restitution; Vec4V staticFriction; Vec4V dynamicFriction; //Technically, these mass properties could be pulled out into a new structure and shared. For multi-manifold contacts, //this would save 64 bytes per-manifold after the cost of the first manifold Vec4V invMass0D0; Vec4V invMass1D1; Vec4V angDom0; Vec4V angDom1; //Normal is shared between all contacts in the batch. This will save some memory! Vec4V normalX; Vec4V normalY; Vec4V normalZ; Vec4V maxPenBias; Sc::ShapeInteraction* shapeInteraction[4]; //192 or 208 BoolV broken; PxU8* frictionBrokenWritebackByte[4]; }; struct SolverContactPointStepBlock { Vec4V raXnI[3]; Vec4V rbXnI[3]; Vec4V separation; Vec4V velMultiplier; Vec4V targetVelocity; Vec4V biasCoefficient; Vec4V recipResponse; }; //KS - technically, this friction constraint has identical data to the above contact constraint. //We make them separate structs for clarity struct SolverContactFrictionStepBlock { Vec4V normal[3]; Vec4V raXnI[3]; Vec4V rbXnI[3]; Vec4V error; Vec4V velMultiplier; Vec4V targetVel; Vec4V biasCoefficient; }; struct SolverConstraint1DHeaderStep4 { PxU8 type; // enum SolverConstraintType - must be first byte PxU8 pad0[3]; //These counts are the max of the 4 sets of data. //When certain pairs have fewer constraints than others, they are padded with 0s so that no work is performed but //calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD) PxU32 count; PxU8 counts[4]; PxU8 breakable[4]; Vec4V linBreakImpulse; Vec4V angBreakImpulse; Vec4V invMass0D0; Vec4V invMass1D1; Vec4V angD0; Vec4V angD1; Vec4V body0WorkOffset[3]; Vec4V rAWorld[3]; Vec4V rBWorld[3]; Vec4V angOrthoAxis0X[3]; Vec4V angOrthoAxis0Y[3]; Vec4V angOrthoAxis0Z[3]; Vec4V angOrthoAxis1X[3]; Vec4V angOrthoAxis1Y[3]; Vec4V angOrthoAxis1Z[3]; Vec4V angOrthoRecipResponse[3]; Vec4V angOrthoError[3]; }; PX_ALIGN_PREFIX(16) struct SolverConstraint1DStep4 { public: Vec4V lin0[3]; //!< linear velocity projection (body 0) Vec4V error; //!< constraint error term - must be scaled by biasScale. Can be adjusted at run-time Vec4V lin1[3]; //!< linear velocity projection (body 1) Vec4V biasScale; //!< constraint constant bias scale. Constant Vec4V ang0[3]; //!< angular velocity projection (body 0) Vec4V velMultiplier; //!< constraint velocity multiplier Vec4V ang1[3]; //!< angular velocity projection (body 1) Vec4V velTarget; //!< Scaled target velocity of the constraint drive Vec4V minImpulse; //!< Lower bound on impulse magnitude Vec4V maxImpulse; //!< Upper bound on impulse magnitude Vec4V appliedForce; //!< applied force to correct velocity+bias Vec4V maxBias; Vec4V angularErrorScale; //Constant PxU32 flags[4]; } PX_ALIGN_SUFFIX(16); static void setupFinalizeSolverConstraints4Step(PxTGSSolverContactDesc* PX_RESTRICT descs, CorrelationBuffer& c, PxU8* PX_RESTRICT workspace, PxReal invDtF32, PxReal totalDtF32, PxReal invTotalDtF32, PxReal dtF32, PxReal bounceThresholdF32, PxReal biasCoefficient, 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(); 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) }; const 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; PxReal kinematicScale0F32[4]; PxReal kinematicScale1F32[4]; for (PxU32 a = 0; a < 4; ++a) { isDynamic = isDynamic || (descs[a].bodyState1 == PxSolverContactDesc::eDYNAMIC_BODY); hasKinematic = hasKinematic || descs[a].bodyState1 == PxSolverContactDesc::eKINEMATIC_BODY; kinematicScale0F32[a] = descs[a].body0->isKinematic ? 1.f : 0.f; kinematicScale1F32[a] = descs[a].body1->isKinematic ? 1.f : 0.f; } /*BoolV kinematic0 = BLoad(isKinematic0); BoolV kinematic1 = BLoad(isKinematic1);*/ const Vec4V kinematicScale0 = V4LoadU(kinematicScale0F32); const Vec4V kinematicScale1 = V4LoadU(kinematicScale1F32); const PxU32 constraintSize = sizeof(SolverContactPointStepBlock); const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock); 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].bodyData0->penBiasClamp, descs[1].bodyData0->penBiasClamp, descs[2].bodyData0->penBiasClamp, descs[3].bodyData0->penBiasClamp), V4LoadXYZW(descs[0].bodyData1->penBiasClamp, descs[1].bodyData1->penBiasClamp, descs[2].bodyData1->penBiasClamp, descs[3].bodyData1->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].bodyData0->originalLinearVelocity.x); Vec4V linVel10 = V4LoadA(&descs[1].bodyData0->originalLinearVelocity.x); Vec4V linVel20 = V4LoadA(&descs[2].bodyData0->originalLinearVelocity.x); Vec4V linVel30 = V4LoadA(&descs[3].bodyData0->originalLinearVelocity.x); Vec4V linVel01 = V4LoadA(&descs[0].bodyData1->originalLinearVelocity.x); Vec4V linVel11 = V4LoadA(&descs[1].bodyData1->originalLinearVelocity.x); Vec4V linVel21 = V4LoadA(&descs[2].bodyData1->originalLinearVelocity.x); Vec4V linVel31 = V4LoadA(&descs[3].bodyData1->originalLinearVelocity.x); Vec4V angVel00 = V4LoadA(&descs[0].bodyData0->originalAngularVelocity.x); Vec4V angVel10 = V4LoadA(&descs[1].bodyData0->originalAngularVelocity.x); Vec4V angVel20 = V4LoadA(&descs[2].bodyData0->originalAngularVelocity.x); Vec4V angVel30 = V4LoadA(&descs[3].bodyData0->originalAngularVelocity.x); Vec4V angVel01 = V4LoadA(&descs[0].bodyData1->originalAngularVelocity.x); Vec4V angVel11 = V4LoadA(&descs[1].bodyData1->originalAngularVelocity.x); Vec4V angVel21 = V4LoadA(&descs[2].bodyData1->originalAngularVelocity.x); Vec4V angVel31 = V4LoadA(&descs[3].bodyData1->originalAngularVelocity.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 invMass0 = V4LoadXYZW(descs[0].bodyData0->invMass, descs[1].bodyData0->invMass, descs[2].bodyData0->invMass, descs[3].bodyData0->invMass); const Vec4V invMass1 = V4LoadXYZW(descs[0].bodyData1->invMass, descs[1].bodyData1->invMass, descs[2].bodyData1->invMass, descs[3].bodyData1->invMass); const Vec4V invMass0D0 = V4Mul(dom0, invMass0); const Vec4V invMass1D1 = V4Mul(dom1, invMass1); Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].body0TxI->sqrtInvInertia.column2)); Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].body0TxI->sqrtInvInertia.column2)); Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].body0TxI->sqrtInvInertia.column2)); Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body0TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body0TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].body0TxI->sqrtInvInertia.column2)); Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[0].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].body1TxI->sqrtInvInertia.column2)); Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[1].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].body1TxI->sqrtInvInertia.column2)); Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[2].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].body1TxI->sqrtInvInertia.column2)); Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body1TxI->sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(descs[3].body1TxI->sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(descs[3].body1TxI->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 PxReal scale = PxMin(0.8f, biasCoefficient); const FloatV p8 = FLoad(scale); const FloatV frictionBiasScale = FMul(invDt, p8); const Vec4V totalDt = V4Load(totalDtF32); const FloatV invTotalDt = FLoad(invTotalDtF32); const Vec4V p84 = V4Splat(p8); const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32)); const Vec4V invDtp8 = V4Splat(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); const FloatV dt = FLoad(dtF32); 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; PxU32 clampedContacts0 = hasFinished[0] ? 0 : c.frictionPatchContactCounts[frictionIndex0]; PxU32 clampedContacts1 = hasFinished[1] ? 0 : c.frictionPatchContactCounts[frictionIndex1]; PxU32 clampedContacts2 = hasFinished[2] ? 0 : c.frictionPatchContactCounts[frictionIndex2]; PxU32 clampedContacts3 = hasFinished[3] ? 0 : c.frictionPatchContactCounts[frictionIndex3]; PxU32 firstPatch0 = c.correlationListHeads[frictionIndex0]; PxU32 firstPatch1 = c.correlationListHeads[frictionIndex1]; PxU32 firstPatch2 = c.correlationListHeads[frictionIndex2]; 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); SolverContactHeaderStepBlock* PX_RESTRICT header = reinterpret_cast<SolverContactHeaderStepBlock*>(ptr); ptr += sizeof(SolverContactHeaderStepBlock); 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->numNormalConstrs[0] = PxTo8(clampedContacts0); header->numNormalConstrs[1] = PxTo8(clampedContacts1); header->numNormalConstrs[2] = PxTo8(clampedContacts2); header->numNormalConstrs[3] = 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; header->maxPenBias = maxPenBias; 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); BoolV bFinished = BLoad(hasFinished); while (finished != 0xf) { finished = newFinished; ++contactCount; PxPrefetchLine(p, 384); PxPrefetchLine(p, 512); PxPrefetchLine(p, 640); SolverContactPointStepBlock* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointStepBlock*>(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); 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)); const Vec4V relAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00))); const Vec4V relAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01))); const Vec4V relAng = V4Sub(relAngVel0, relAngVel1); 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); 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 vrel0 = V4Add(norVel0, relAngVel0); Vec4V vrel1 = V4Add(norVel1, relAngVel1); Vec4V delAngVel1X = zero; Vec4V delAngVel1Y = zero; Vec4V delAngVel1Z = zero; //The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much if (isDynamic) { rbXnX = V4Sel(V4IsGrtr(slop, V4Abs(rbXnX)), zero, rbXnX); rbXnY = V4Sel(V4IsGrtr(slop, V4Abs(rbXnY)), zero, rbXnY); rbXnZ = V4Sel(V4IsGrtr(slop, V4Abs(rbXnZ)), zero, rbXnZ); delAngVel1X = V4Mul(invInertia1X0, rbXnX); delAngVel1Y = V4Mul(invInertia1X1, rbXnX); 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); } Vec4V vrel = V4Sub(vrel0, vrel1); solverContact->rbXnI[0] = delAngVel1X; solverContact->rbXnI[1] = delAngVel1Y; solverContact->rbXnI[2] = delAngVel1Z; Vec4V penetration = V4Sub(separation, restDistance); const Vec4V penetrationInvDt = V4Scale(penetration, invTotalDt); const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(zero, restitution), V4IsGrtr(bounceThreshold, vrel)), V4IsGrtr(V4Neg(vrel), penetrationInvDt)); const Vec4V ratio = V4Sel(isGreater2, V4Add(totalDt, V4Div(penetration, vrel)), zero); const Vec4V recipResponse = V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero); //Restitution is negated in the block setup code const BoolV isCompliant = V4IsGrtr(restitution, zero); const Vec4V rdt = V4Scale(restitution, dt); const Vec4V a = V4Scale(V4Add(damping, rdt), dt); const Vec4V x = V4Recip(V4MulAdd(a, unitResponse, V4One())); const Vec4V velMultiplier = V4Sel(isCompliant, V4Mul(x, a), recipResponse); const Vec4V scaledBias = V4Neg(V4Sel(isCompliant, V4Mul(rdt, V4Mul(x, unitResponse)), V4Sel(V4IsGrtr(penetration, zero), V4Splat(invDt), invDtp8))); Vec4V targetVelocity = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4Sel(isGreater2, V4Mul(vrel, restitution), zero))); penetration = V4MulAdd(targetVelocity, ratio, penetration); //Vec4V biasedErr = V4Sel(isGreater2, targetVelocity, scaledBias); //Vec4V biasedErr = V4Add(targetVelocity, scaledBias); //biasedErr = V4NegMulSub(V4Sub(vrel, cTargetNorVel), velMultiplier, biasedErr); //These values are present for static and dynamic contacts solverContact->raXnI[0] = delAngVel0X; solverContact->raXnI[1] = delAngVel0Y; solverContact->raXnI[2] = delAngVel0Z; solverContact->velMultiplier = V4Sel(bFinished, zero, velMultiplier); solverContact->targetVelocity = V4Add(cTargetNorVel, targetVelocity); solverContact->separation = penetration; solverContact->biasCoefficient = V4Sel(bFinished, zero, scaledBias); solverContact->recipResponse = V4Sel(bFinished, zero, recipResponse); if (hasMaxImpulse) { maxImpulse[contactCount - 1] = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse), FLoad(con3.maxImpulse)); } } 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]; PxU32 anchorCount0 = frictionPatch0.anchorCount; PxU32 anchorCount1 = frictionPatch1.anchorCount; PxU32 anchorCount2 = frictionPatch2.anchorCount; PxU32 anchorCount3 = frictionPatch3.anchorCount; PxU32 clampedAnchorCount0 = hasFinished[0] || (contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount0; PxU32 clampedAnchorCount1 = hasFinished[1] || (contactBase1->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount1; PxU32 clampedAnchorCount2 = hasFinished[2] || (contactBase2->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount2; PxU32 clampedAnchorCount3 = hasFinished[3] || (contactBase3->materialFlags & PxMaterialFlag::eDISABLE_FRICTION) ? 0 : anchorCount3; const PxU32 maxAnchorCount = PxMax(clampedAnchorCount0, PxMax(clampedAnchorCount1, PxMax(clampedAnchorCount2, clampedAnchorCount3))); PX_ALIGN(16, PxReal staticFriction[4]); PX_ALIGN(16, PxReal dynamicFriction[4]); //for (PxU32 f = 0; f < 4; ++f) { PxReal coeff0 = (contactBase0->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount0 == 2) ? 0.5f : 1.f; PxReal coeff1 = (contactBase1->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount1 == 2) ? 0.5f : 1.f; PxReal coeff2 = (contactBase2->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount2 == 2) ? 0.5f : 1.f; PxReal coeff3 = (contactBase3->materialFlags & PxMaterialFlag::eIMPROVED_PATCH_FRICTION && clampedAnchorCount3 == 2) ? 0.5f : 1.f; staticFriction[0] = contactBase0->staticFriction * coeff0; dynamicFriction[0] = contactBase0->dynamicFriction * coeff0; staticFriction[1] = contactBase1->staticFriction * coeff1; dynamicFriction[1] = contactBase1->dynamicFriction * coeff1; staticFriction[2] = contactBase2->staticFriction * coeff2; dynamicFriction[2] = contactBase2->dynamicFriction * coeff2; staticFriction[3] = contactBase3->staticFriction * coeff3; dynamicFriction[3] = contactBase3->dynamicFriction * coeff3; } PX_ASSERT(totalContacts == contactCount); header->numFrictionConstr = PxTo8(maxAnchorCount * 2); header->numFrictionConstrs[0] = PxTo8(clampedAnchorCount0 * 2); header->numFrictionConstrs[1] = PxTo8(clampedAnchorCount1 * 2); header->numFrictionConstrs[2] = PxTo8(clampedAnchorCount2 * 2); header->numFrictionConstrs[3] = PxTo8(clampedAnchorCount3 * 2); //KS - TODO - extend this if needed header->type = PxTo8(DY_SC_TYPE_BLOCK_RB_CONTACT); if (maxAnchorCount) { 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; header->broken = bFalse; header->frictionBrokenWritebackByte[0] = writeback0; header->frictionBrokenWritebackByte[1] = writeback1; header->frictionBrokenWritebackByte[2] = writeback2; header->frictionBrokenWritebackByte[3] = writeback3; /*header->frictionNormal[0][0] = t0X; header->frictionNormal[0][1] = t0Y; header->frictionNormal[0][2] = t0Z; header->frictionNormal[1][0] = t1X; header->frictionNormal[1][1] = t1Y; header->frictionNormal[1][2] = 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); SolverContactFrictionStepBlock* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionStepBlock*>(ptr); ptr += frictionSize; SolverContactFrictionStepBlock* PX_RESTRICT f1 = reinterpret_cast<SolverContactFrictionStepBlock*>(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); Vec3V body0Anchor0 = V3LoadU(frictionPatch0.body0Anchors[index0]); Vec3V body0Anchor1 = V3LoadU(frictionPatch1.body0Anchors[index1]); Vec3V body0Anchor2 = V3LoadU(frictionPatch2.body0Anchors[index2]); 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); Vec3V body1Anchor0 = V3LoadU(frictionPatch0.body1Anchors[index0]); Vec3V body1Anchor1 = V3LoadU(frictionPatch1.body1Anchors[index1]); Vec3V body1Anchor2 = V3LoadU(frictionPatch2.body1Anchors[index2]); 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); Vec4V errorX = V4Sub(raWorldX, rbWorldX); Vec4V errorY = V4Sub(raWorldY, rbWorldY); 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 PxU32 contactIndex0 = c.contactID[frictionIndex0][index0]; PxU32 contactIndex1 = c.contactID[frictionIndex1][index1]; PxU32 contactIndex2 = c.contactID[frictionIndex2][index2]; 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 ? &contactBase0->targetVel.x : &descs[1].contacts[contactIndex1].targetVel.x); Vec4V targetVel2 = V4LoadA(contactIndex2 == 0xFFFF ? &contactBase0->targetVel.x : &descs[2].contacts[contactIndex2].targetVel.x); Vec4V targetVel3 = V4LoadA(contactIndex3 == 0xFFFF ? &contactBase0->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 vrel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0))); Vec4V delAngVel1X = zero; Vec4V delAngVel1Y = zero; Vec4V delAngVel1Z = zero; Vec4V vrel1 = zero; if (isDynamic) { 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); delAngVel1X = V4Mul(invInertia1X0, rbXnX); delAngVel1Y = V4Mul(invInertia1X1, rbXnX); 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); const Vec4V tVel1 = V4MulAdd(t0Z, linVelT21, V4MulAdd(t0Y, linVelT11, V4Mul(t0X, linVelT01))); vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); } 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))); vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); } f0->rbXnI[0] = delAngVel1X; f0->rbXnI[1] = delAngVel1Y; f0->rbXnI[2] = delAngVel1Z; const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero)); Vec4V error = V4MulAdd(t0Z, errorZ, V4MulAdd(t0Y, errorY, V4Mul(t0X, errorX))); Vec4V targetVel = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4MulAdd(t0Z, targetVelZ, V4MulAdd(t0Y, targetVelY, V4Mul(t0X, targetVelX))))); f0->normal[0] = t0X; f0->normal[1] = t0Y; f0->normal[2] = t0Z; f0->raXnI[0] = delAngVel0X; f0->raXnI[1] = delAngVel0Y; f0->raXnI[2] = delAngVel0Z; f0->error = error; f0->velMultiplier = velMultiplier; f0->biasCoefficient = V4Splat(frictionBiasScale); f0->targetVel = targetVel; } { 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 vrel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4MulAdd(raXnX, angVelT00, tVel0))); Vec4V delAngVel1X = zero; Vec4V delAngVel1Y = zero; Vec4V delAngVel1Z = zero; Vec4V vrel1 = zero; if (isDynamic) { 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); delAngVel1X = V4Mul(invInertia1X0, rbXnX); delAngVel1Y = V4Mul(invInertia1X1, rbXnX); 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); const Vec4V tVel1 = V4MulAdd(t1Z, linVelT21, V4MulAdd(t1Y, linVelT11, V4Mul(t1X, linVelT01))); vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); } 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))); vrel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4MulAdd(rbXnX, angVelT01, tVel1))); } f1->rbXnI[0] = delAngVel1X; f1->rbXnI[1] = delAngVel1Y; f1->rbXnI[2] = delAngVel1Z; const Vec4V velMultiplier = V4Mul(maxImpulseScale, V4Sel(V4IsGrtr(resp, zero), V4Div(p84, resp), zero)); Vec4V error = V4MulAdd(t1Z, errorZ, V4MulAdd(t1Y, errorY, V4Mul(t1X, errorX))); Vec4V targetVel = V4NegMulSub(vrel0, kinematicScale0, V4MulAdd(vrel1, kinematicScale1, V4MulAdd(t1Z, targetVelZ, V4MulAdd(t1Y, targetVelY, V4Mul(t1X, targetVelX))))); f1->normal[0] = t1X; f1->normal[1] = t1Y; f1->normal[2] = t1Z; f1->raXnI[0] = delAngVel0X; f1->raXnI[1] = delAngVel0Y; f1->raXnI[2] = delAngVel0Z; f1->error = error; f1->velMultiplier = velMultiplier; f1->targetVel = targetVel; f1->biasCoefficient = V4Splat(frictionBiasScale); } } header->dynamicFriction = V4LoadA(dynamicFriction); header->staticFriction = V4LoadA(staticFriction); frictionPatchWritebackAddrIndex0++; frictionPatchWritebackAddrIndex1++; frictionPatchWritebackAddrIndex2++; frictionPatchWritebackAddrIndex3++; } } } } static 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. static void computeBlockStreamByteSizes4(PxTGSSolverContactDesc* 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(SolverContactHeaderStepBlock) * maxPatches; //PxU32 constraintSize = isStatic ? (sizeof(SolverContactBatchPointBase4) * totalContacts) + (sizeof(SolverContactFrictionBase4) * totalFriction) : // (sizeof(SolverContactBatchPointDynamic4) * totalContacts) + (sizeof(SolverContactFrictionDynamic4) * totalFriction); PxU32 constraintSize = (sizeof(SolverContactPointStepBlock) * totalContacts) + (sizeof(SolverContactFrictionStepBlock) * 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(PxTGSSolverContactDesc* 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 createFinalizeSolverContacts4Step( Dy::CorrelationBuffer& c, 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) { 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) { PxTGSSolverContactDesc& 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)) { const 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); const 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) { PxTGSSolverContactDesc& 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]; PxTGSSolverContactDesc& 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); setupFinalizeSolverConstraints4Step(blockDescs, c, solverConstraint, invDtF32, totalDtF32, invTotalDtF32, dt, bounceThresholdF32, biasCoefficient, 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; } SolverConstraintPrepState::Enum createFinalizeSolverContacts4Step( PxsContactManagerOutput** cmOutputs, ThreadContext& threadContext, PxTGSSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal totalDtF32, const PxReal invTotalDtF32, const PxReal dtF32, const PxReal bounceThresholdF32, const PxReal frictionOffsetThreshold, const PxReal correlationDistance, const PxReal biasCoefficient, 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) { PxTGSSolverContactDesc& blockDesc = blockDescs[a]; PxSolverConstraintDesc& desc = *blockDesc.desc; //blockDesc.startContactIndex = buffer.count; blockDesc.contacts = buffer.contacts + buffer.count; PxPrefetchLine(desc.bodyA); PxPrefetchLine(desc.bodyB); //Unbatchable if we have (a) too many contacts or (b) torsional friction enabled - it just seems easier to handle this on an individual contact basis because it is expected to //be used relatively rarely if ((buffer.count + cmOutputs[a]->nbContacts) > 64 || (blockDesc.torsionalPatchRadius != 0.f || blockDesc.minTorsionalPatchRadius != 0.f) ) { 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.bodyData0->maxContactImpulse, blockDesc.bodyData1->maxContactImpulse); PxU32 contactCount = extractContacts(buffer, *cmOutputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1, defaultMaxImpulse); if (contactCount == 0 || hasTargetVelocity) 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 *= blockDesc.body0->isKinematic ? 0.f : invInertiaScale0; blockDesc.invMassScales.angular1 *= blockDesc.body1->isKinematic ? 0.f : invInertiaScale1; } return createFinalizeSolverContacts4Step(c, blockDescs, invDtF32, totalDtF32, invTotalDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, biasCoefficient, constraintAllocator); } void setSolverConstantsStep(PxReal& error, PxReal& biasScale, PxReal& targetVel, PxReal& maxBias, PxReal& velMultiplier, PxReal& rcpResponse, const Px1DConstraint& c, PxReal normalVel, PxReal unitResponse, PxReal minRowResponse, PxReal erp, PxReal dt, PxReal totalDt, PxReal biasClamp, PxReal recipdt, PxReal recipTotalDt, PxReal velTarget); static void setConstants(PxReal& error, PxReal& biasScale, PxReal& targetVel, PxReal& maxBias, PxReal& velMultiplier, PxReal& rcpResponse, const Px1DConstraint& c, PxReal unitResponse, PxReal minRowResponse, PxReal dt, PxReal totalDt, PxReal recipdt, PxReal recipTotalDt, bool finished, PxReal lengthScale, PxReal nv, PxReal nv0, PxReal nv1, bool isKinematic0, bool isKinematic1, PxReal erp) { if (finished) { error = 0.f; biasScale = 0.f; maxBias = 0.f; velMultiplier = 0.f; rcpResponse = 0.f; targetVel = 0.f; return; } //PxReal biasClamp = c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? 50.f : 200.f*lengthScale; PxReal biasClamp = c.flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT ? 100.f : 1000.f*lengthScale; PxReal vt = 0.f; if (isKinematic0) vt -= nv0; if (isKinematic1) vt += nv1; setSolverConstantsStep(error, biasScale, targetVel, maxBias, velMultiplier, rcpResponse, c, nv, unitResponse, minRowResponse, erp, dt, totalDt, biasClamp, recipdt, recipTotalDt, vt); } static void setOrthoData(const PxReal& ang0X, const PxReal& ang0Y, const PxReal& ang0Z, const PxReal& ang1X, const PxReal& ang1Y, const PxReal& ang1Z, const PxReal& recipResponse, const PxReal& error, PxReal& orthoAng0X, PxReal& orthoAng0Y, PxReal& orthoAng0Z, PxReal& orthoAng1X, PxReal& orthoAng1Y, PxReal& orthoAng1Z, PxReal& orthoRecipResponse, PxReal& orthoError, bool disableProcessing, PxU32 solveHint, PxU32& flags, PxU32& orthoCount, bool finished) { if (!finished && !disableProcessing) { if (solveHint == PxConstraintSolveHint::eROTATIONAL_EQUALITY) { flags |= DY_SC_FLAG_ROT_EQ; orthoAng0X = ang0X; orthoAng0Y = ang0Y; orthoAng0Z = ang0Z; orthoAng1X = ang1X; orthoAng1Y = ang1Y; orthoAng1Z = ang1Z; orthoRecipResponse = recipResponse; orthoError = error; orthoCount++; } else if (solveHint & PxConstraintSolveHint::eEQUALITY) flags |= DY_SC_FLAG_ORTHO_TARGET; } } 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); 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) { //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]; PxTGSSolverConstraintPrepDesc& 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); //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, desc.cA2w, desc.cB2w); nbToPrep = constraintCount; maxRows = PxMax(constraintCount, maxRows); if (constraintCount == 0) return SolverConstraintPrepState::eUNBATCHABLE; desc.rows = rows; desc.numRows = constraintCount; rows += constraintCount; if (desc.body0->isKinematic) desc.invMassScales.angular0 = 0.0f; if (desc.body1->isKinematic) desc.invMassScales.angular1 = 0.0f; } return setupSolverConstraintStep4(constraintDescs, dt, totalDt, recipdt, recipTotalDt, totalRows, allocator, maxRows, lengthScale, biasCoefficient); } 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) { 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; PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a]; Px1DConstraint** sorted = allSorted + numRows; for (PxU32 i = 0; i < desc.numRows; ++i) { if (desc.rows[i].flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT) { if (desc.rows[i].solveHint == PxConstraintSolveHint::eEQUALITY) desc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_EQUALITY; else if (desc.rows[i].solveHint == PxConstraintSolveHint::eINEQUALITY) desc.rows[i].solveHint = PxConstraintSolveHint::eROTATIONAL_INEQUALITY; } } preprocessRows(sorted, desc.rows, angSqrtInvInertia0 + numRows, angSqrtInvInertia1 + numRows, desc.numRows, desc.body0TxI->sqrtInvInertia, desc.body1TxI->sqrtInvInertia, desc.bodyData0->invMass, desc.bodyData1->invMass, desc.invMassScales, desc.disablePreprocessing, desc.improvedSlerp); numRows += desc.numRows; } const PxU32 stride = sizeof(SolverConstraint1DStep4); const PxU32 constraintLength = sizeof(SolverConstraint1DHeaderStep4) + 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) { PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a]; desc.desc->constraint = NULL; desc.desc->constraintLengthOver16 = 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; const PxReal erp = 0.5f * biasCoefficient; const bool isKinematic00 = constraintDescs[0].body0->isKinematic; const bool isKinematic01 = constraintDescs[0].body1->isKinematic; const bool isKinematic10 = constraintDescs[1].body0->isKinematic; const bool isKinematic11 = constraintDescs[1].body1->isKinematic; const bool isKinematic20 = constraintDescs[2].body0->isKinematic; const bool isKinematic21 = constraintDescs[2].body1->isKinematic; const bool isKinematic30 = constraintDescs[3].body0->isKinematic; const bool isKinematic31 = constraintDescs[3].body1->isKinematic; for (PxU32 a = 0; a < 4; ++a) { PxTGSSolverConstraintPrepDesc& desc = constraintDescs[a]; desc.desc->constraint = ptr; desc.desc->constraintLengthOver16 = PxU16(constraintLength/16); desc.desc->writeBack = desc.writeback; } { PxU8* currPtr = ptr; SolverConstraint1DHeaderStep4* header = reinterpret_cast<SolverConstraint1DHeaderStep4*>(currPtr); currPtr += sizeof(SolverConstraint1DHeaderStep4); const PxTGSSolverBodyData& bd00 = *constraintDescs[0].bodyData0; const PxTGSSolverBodyData& bd01 = *constraintDescs[1].bodyData0; const PxTGSSolverBodyData& bd02 = *constraintDescs[2].bodyData0; const PxTGSSolverBodyData& bd03 = *constraintDescs[3].bodyData0; const PxTGSSolverBodyData& bd10 = *constraintDescs[0].bodyData1; const PxTGSSolverBodyData& bd11 = *constraintDescs[1].bodyData1; const PxTGSSolverBodyData& bd12 = *constraintDescs[2].bodyData1; const PxTGSSolverBodyData& bd13 = *constraintDescs[3].bodyData1; //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); //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(totalDt); Vec4V linBreakForce = V4LoadXYZW(constraintDescs[0].linBreakForce, constraintDescs[1].linBreakForce, constraintDescs[2].linBreakForce, constraintDescs[3].linBreakForce); Vec4V angBreakForce = V4LoadXYZW(constraintDescs[0].angBreakForce, constraintDescs[1].angBreakForce, constraintDescs[2].angBreakForce, constraintDescs[3].angBreakForce); header->breakable[0] = PxU8((constraintDescs[0].linBreakForce != PX_MAX_F32) || (constraintDescs[0].angBreakForce != PX_MAX_F32)); header->breakable[1] = PxU8((constraintDescs[1].linBreakForce != PX_MAX_F32) || (constraintDescs[1].angBreakForce != PX_MAX_F32)); header->breakable[2] = PxU8((constraintDescs[2].linBreakForce != PX_MAX_F32) || (constraintDescs[2].angBreakForce != PX_MAX_F32)); header->breakable[3] = 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->body0WorkOffset[0] = workOffsetX; header->body0WorkOffset[1] = workOffsetY; header->body0WorkOffset[2] = workOffsetZ; header->count = maxRows; header->type = DY_SC_TYPE_BLOCK_1D; header->linBreakImpulse = V4Scale(linBreakForce, dtV); header->angBreakImpulse = V4Scale(angBreakForce, dtV); header->counts[0] = PxTo8(constraintDescs[0].numRows); header->counts[1] = PxTo8(constraintDescs[1].numRows); header->counts[2] = PxTo8(constraintDescs[2].numRows); header->counts[3] = PxTo8(constraintDescs[3].numRows); Vec4V ca2WX, ca2WY, ca2WZ; Vec4V cb2WX, cb2WY, cb2WZ; Vec4V ca2W0 = V4LoadU(&constraintDescs[0].cA2w.x); Vec4V ca2W1 = V4LoadU(&constraintDescs[1].cA2w.x); Vec4V ca2W2 = V4LoadU(&constraintDescs[2].cA2w.x); Vec4V ca2W3 = V4LoadU(&constraintDescs[3].cA2w.x); Vec4V cb2W0 = V4LoadU(&constraintDescs[0].cB2w.x); Vec4V cb2W1 = V4LoadU(&constraintDescs[1].cB2w.x); Vec4V cb2W2 = V4LoadU(&constraintDescs[2].cB2w.x); Vec4V cb2W3 = V4LoadU(&constraintDescs[3].cB2w.x); PX_TRANSPOSE_44_34(ca2W0, ca2W1, ca2W2, ca2W3, ca2WX, ca2WY, ca2WZ); PX_TRANSPOSE_44_34(cb2W0, cb2W1, cb2W2, cb2W3, cb2WX, cb2WY, cb2WZ); Vec4V pos00 = V4LoadA(&constraintDescs[0].body0TxI->deltaBody2World.p.x); Vec4V pos01 = V4LoadA(&constraintDescs[0].body1TxI->deltaBody2World.p.x); Vec4V pos10 = V4LoadA(&constraintDescs[1].body0TxI->deltaBody2World.p.x); Vec4V pos11 = V4LoadA(&constraintDescs[1].body1TxI->deltaBody2World.p.x); Vec4V pos20 = V4LoadA(&constraintDescs[2].body0TxI->deltaBody2World.p.x); Vec4V pos21 = V4LoadA(&constraintDescs[2].body1TxI->deltaBody2World.p.x); Vec4V pos30 = V4LoadA(&constraintDescs[3].body0TxI->deltaBody2World.p.x); Vec4V pos31 = V4LoadA(&constraintDescs[3].body1TxI->deltaBody2World.p.x); Vec4V pos0X, pos0Y, pos0Z; Vec4V pos1X, pos1Y, pos1Z; PX_TRANSPOSE_44_34(pos00, pos10, pos20, pos30, pos0X, pos0Y, pos0Z); PX_TRANSPOSE_44_34(pos01, pos11, pos21, pos31, pos1X, pos1Y, pos1Z); Vec4V linVel00 = V4LoadA(&constraintDescs[0].bodyData0->originalLinearVelocity.x); Vec4V linVel01 = V4LoadA(&constraintDescs[0].bodyData1->originalLinearVelocity.x); Vec4V angState00 = V4LoadA(&constraintDescs[0].bodyData0->originalAngularVelocity.x); Vec4V angState01 = V4LoadA(&constraintDescs[0].bodyData1->originalAngularVelocity.x); Vec4V linVel10 = V4LoadA(&constraintDescs[1].bodyData0->originalLinearVelocity.x); Vec4V linVel11 = V4LoadA(&constraintDescs[1].bodyData1->originalLinearVelocity.x); Vec4V angState10 = V4LoadA(&constraintDescs[1].bodyData0->originalAngularVelocity.x); Vec4V angState11 = V4LoadA(&constraintDescs[1].bodyData1->originalAngularVelocity.x); Vec4V linVel20 = V4LoadA(&constraintDescs[2].bodyData0->originalLinearVelocity.x); Vec4V linVel21 = V4LoadA(&constraintDescs[2].bodyData1->originalLinearVelocity.x); Vec4V angState20 = V4LoadA(&constraintDescs[2].bodyData0->originalAngularVelocity.x); Vec4V angState21 = V4LoadA(&constraintDescs[2].bodyData1->originalAngularVelocity.x); Vec4V linVel30 = V4LoadA(&constraintDescs[3].bodyData0->originalLinearVelocity.x); Vec4V linVel31 = V4LoadA(&constraintDescs[3].bodyData1->originalLinearVelocity.x); Vec4V angState30 = V4LoadA(&constraintDescs[3].bodyData0->originalAngularVelocity.x); Vec4V angState31 = V4LoadA(&constraintDescs[3].bodyData1->originalAngularVelocity.x); Vec4V linVel0T0, linVel0T1, linVel0T2; Vec4V linVel1T0, linVel1T1, linVel1T2; Vec4V angState0T0, angState0T1, angState0T2; Vec4V angState1T0, angState1T1, angState1T2; 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(angState00, angState10, angState20, angState30, angState0T0, angState0T1, angState0T2); PX_TRANSPOSE_44_34(angState01, angState11, angState21, angState31, angState1T0, angState1T1, angState1T2); const Vec4V raWorldX = V4Sub(ca2WX, pos0X); const Vec4V raWorldY = V4Sub(ca2WY, pos0Y); const Vec4V raWorldZ = V4Sub(ca2WZ, pos0Z); const Vec4V rbWorldX = V4Sub(cb2WX, pos1X); const Vec4V rbWorldY = V4Sub(cb2WY, pos1Y); const Vec4V rbWorldZ = V4Sub(cb2WZ, pos1Z); header->rAWorld[0] = raWorldX; header->rAWorld[1] = raWorldY; header->rAWorld[2] = raWorldZ; header->rBWorld[0] = rbWorldX; header->rBWorld[1] = rbWorldY; header->rBWorld[2] = rbWorldZ; //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 Vec4V one = V4One(); const FloatV fOne = FOne(); PxU32 orthoCount0 = 0, orthoCount1 = 0, orthoCount2 = 0, orthoCount3 = 0; for (PxU32 a = 0; a < 3; ++a) { header->angOrthoAxis0X[a] = V4Zero(); header->angOrthoAxis0Y[a] = V4Zero(); header->angOrthoAxis0Z[a] = V4Zero(); header->angOrthoAxis1X[a] = V4Zero(); header->angOrthoAxis1Y[a] = V4Zero(); header->angOrthoAxis1Z[a] = V4Zero(); header->angOrthoRecipResponse[a] = V4Zero(); header->angOrthoError[a] = V4Zero(); } for (PxU32 a = 0; a < maxRows; ++a) { const bool finished[] = { a >= constraintDescs[0].numRows, a >= constraintDescs[1].numRows, a >= constraintDescs[2].numRows, a >= constraintDescs[3].numRows }; BoolV bFinished = BLoad(finished); SolverConstraint1DStep4* c = reinterpret_cast<SolverConstraint1DStep4*>(currPtr); currPtr += stride; Px1DConstraint* con0 = allSorted[index0]; Px1DConstraint* con1 = allSorted[index1]; Px1DConstraint* con2 = allSorted[index2]; Px1DConstraint* con3 = allSorted[index3]; const bool angularConstraint[4] = { !!(con0->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT), !!(con1->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT), !!(con2->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT), !!(con3->flags & Px1DConstraintFlag::eANGULAR_CONSTRAINT), }; BoolV bAngularConstraint = BLoad(angularConstraint); 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 = one; if (con0->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[0].driveLimitsAreForces) driveScale = V4SetX(driveScale, FMin(fOne, dtV)); if (con1->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[1].driveLimitsAreForces) driveScale = V4SetY(driveScale, FMin(fOne, dtV)); if (con2->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[2].driveLimitsAreForces) driveScale = V4SetZ(driveScale, FMin(fOne, dtV)); if (con3->flags&Px1DConstraintFlag::eHAS_DRIVE_LIMIT && constraintDescs[3].driveLimitsAreForces) driveScale = V4SetW(driveScale, FMin(fOne, 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 clin0X, clin0Y, clin0Z; PX_TRANSPOSE_44_34(clin00, clin01, clin02, clin03, clin0X, clin0Y, clin0Z); 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 cang0X, cang0Y, cang0Z; PX_TRANSPOSE_44_34(cang00, cang01, cang02, cang03, cang0X, cang0Y, cang0Z); 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 cang1X, cang1Y, cang1Z; PX_TRANSPOSE_44_34(cang10, cang11, cang12, cang13, cang1X, cang1Y, cang1Z); 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->lin0[0] = V4Sel(bFinished, zero, clin0X); c->lin0[1] = V4Sel(bFinished, zero, clin0Y); c->lin0[2] = V4Sel(bFinished, zero, clin0Z); c->ang0[0] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0X, zero); c->ang0[1] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0Y, zero); c->ang0[2] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang0Z, zero); c->angularErrorScale = V4Sel(bAngularConstraint, one, zero); 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))); 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 clin1X, clin1Y, clin1Z; PX_TRANSPOSE_44_34(clin10, clin11, clin12, clin13, clin1X, clin1Y, clin1Z); 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->lin1[0] = V4Sel(bFinished, zero, clin1X); c->lin1[1] = V4Sel(bFinished, zero, clin1Y); c->lin1[2] = V4Sel(bFinished, zero, clin1Z); c->ang1[0] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1X, zero); c->ang1[1] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1Y, zero); c->ang1[2] = V4Sel(BAndNot(bAngularConstraint, bFinished), cang1Z, zero); unitResponse = V4Add(unitResponse, V4MulAdd(lin1MagSq, invMass1, V4Mul(cang1DotAngDelta, invInertiaScale1))); const Vec4V lnormalVel0 = V4MulAdd(clin0X, linVel0T0, V4MulAdd(clin0Y, linVel0T1, V4Mul(clin0Z, linVel0T2))); const Vec4V lnormalVel1 = V4MulAdd(clin1X, linVel1T0, V4MulAdd(clin1Y, linVel1T1, V4Mul(clin1Z, linVel1T2))); const Vec4V angVel0 = V4MulAdd(cang0X, angState0T0, V4MulAdd(cang0Y, angState0T1, V4Mul(cang0Z, angState0T2))); const Vec4V angVel1 = V4MulAdd(angDelta1X, angState1T0, V4MulAdd(angDelta1Y, angState1T1, V4Mul(angDelta1Z, angState1T2))); const Vec4V normalVel0 = V4Add(lnormalVel0, angVel0); const Vec4V normalVel1 = V4Add(lnormalVel1, angVel1); const Vec4V normalVel = V4Sub(normalVel0, normalVel1); angDelta0X = V4Mul(angDelta0X, invInertiaScale0); angDelta0Y = V4Mul(angDelta0Y, invInertiaScale0); angDelta0Z = V4Mul(angDelta0Z, invInertiaScale0); angDelta1X = V4Mul(angDelta1X, invInertiaScale1); angDelta1Y = V4Mul(angDelta1Y, invInertiaScale1); angDelta1Z = V4Mul(angDelta1Z, invInertiaScale1); { PxReal recipResponse[4]; const PxVec4& ur = reinterpret_cast<const PxVec4&>(unitResponse); PxVec4& cBiasScale = reinterpret_cast<PxVec4&>(c->biasScale); PxVec4& cError = reinterpret_cast<PxVec4&>(c->error); PxVec4& cMaxBias = reinterpret_cast<PxVec4&>(c->maxBias); PxVec4& cTargetVel = reinterpret_cast<PxVec4&>(c->velTarget); PxVec4& cVelMultiplier = reinterpret_cast<PxVec4&>(c->velMultiplier); const PxVec4& nVel = reinterpret_cast<const PxVec4&>(normalVel); const PxVec4& nVel0 = reinterpret_cast<const PxVec4&>(normalVel0); const PxVec4& nVel1 = reinterpret_cast<const PxVec4&>(normalVel1); setConstants(cError.x, cBiasScale.x, cTargetVel.x, cMaxBias.x, cVelMultiplier.x, recipResponse[0], *con0, ur.x, constraintDescs[0].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt, a >= constraintDescs[0].numRows, lengthScale, nVel.x, nVel0.x, nVel1.x, isKinematic00, isKinematic01, erp); setConstants(cError.y, cBiasScale.y, cTargetVel.y, cMaxBias.y, cVelMultiplier.y, recipResponse[1], *con1, ur.y, constraintDescs[1].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt, a >= constraintDescs[1].numRows, lengthScale, nVel.y, nVel0.y, nVel1.y, isKinematic10, isKinematic11, erp); setConstants(cError.z, cBiasScale.z, cTargetVel.z, cMaxBias.z, cVelMultiplier.z, recipResponse[2], *con2, ur.z, constraintDescs[2].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt, a >= constraintDescs[2].numRows, lengthScale, nVel.z, nVel0.z, nVel1.z, isKinematic20, isKinematic21, erp); setConstants(cError.w, cBiasScale.w, cTargetVel.w, cMaxBias.w, cVelMultiplier.w, recipResponse[3], *con3, ur.w, constraintDescs[3].minResponseThreshold, dt, totalDt, recipdt, recipTotalDt, a >= constraintDescs[3].numRows, lengthScale, nVel.w, nVel0.w, nVel1.w, isKinematic30, isKinematic31, erp); PxVec4* angOrthoAxes0X = reinterpret_cast<PxVec4*>(header->angOrthoAxis0X); PxVec4* angOrthoAxes0Y = reinterpret_cast<PxVec4*>(header->angOrthoAxis0Y); PxVec4* angOrthoAxes0Z = reinterpret_cast<PxVec4*>(header->angOrthoAxis0Z); PxVec4* angOrthoAxes1X = reinterpret_cast<PxVec4*>(header->angOrthoAxis1X); PxVec4* angOrthoAxes1Y = reinterpret_cast<PxVec4*>(header->angOrthoAxis1Y); PxVec4* angOrthoAxes1Z = reinterpret_cast<PxVec4*>(header->angOrthoAxis1Z); PxVec4* orthoRecipResponse = reinterpret_cast<PxVec4*>(header->angOrthoRecipResponse); PxVec4* orthoError = reinterpret_cast<PxVec4*>(header->angOrthoError); const PxVec4& ang0X = reinterpret_cast<const PxVec4&>(angDelta0X); const PxVec4& ang0Y = reinterpret_cast<const PxVec4&>(angDelta0Y); const PxVec4& ang0Z = reinterpret_cast<const PxVec4&>(angDelta0Z); const PxVec4& ang1X = reinterpret_cast<const PxVec4&>(angDelta1X); const PxVec4& ang1Y = reinterpret_cast<const PxVec4&>(angDelta1Y); const PxVec4& ang1Z = reinterpret_cast<const PxVec4&>(angDelta1Z); setOrthoData(ang0X.x, ang0Y.x, ang0Z.x, ang1X.x, ang1Y.x, ang1Z.x, recipResponse[0], cError.x, angOrthoAxes0X[orthoCount0].x, angOrthoAxes0Y[orthoCount0].x, angOrthoAxes0Z[orthoCount0].x, angOrthoAxes1X[orthoCount0].x, angOrthoAxes1Y[orthoCount0].x, angOrthoAxes1Z[orthoCount0].x, orthoRecipResponse[orthoCount0].x, orthoError[orthoCount0].x, constraintDescs[0].disablePreprocessing, con0->solveHint, c->flags[0], orthoCount0, a >= constraintDescs[0].numRows); setOrthoData(ang0X.y, ang0Y.y, ang0Z.y, ang1X.y, ang1Y.y, ang1Z.y, recipResponse[1], cError.y, angOrthoAxes0X[orthoCount1].y, angOrthoAxes0Y[orthoCount1].y, angOrthoAxes0Z[orthoCount1].y, angOrthoAxes1X[orthoCount1].y, angOrthoAxes1Y[orthoCount1].y, angOrthoAxes1Z[orthoCount1].y, orthoRecipResponse[orthoCount1].y, orthoError[orthoCount1].y, constraintDescs[1].disablePreprocessing, con1->solveHint, c->flags[1], orthoCount1, a >= constraintDescs[1].numRows); setOrthoData(ang0X.z, ang0Y.z, ang0Z.z, ang1X.z, ang1Y.z, ang1Z.z, recipResponse[2], cError.z, angOrthoAxes0X[orthoCount2].z, angOrthoAxes0Y[orthoCount2].z, angOrthoAxes0Z[orthoCount2].z, angOrthoAxes1X[orthoCount2].z, angOrthoAxes1Y[orthoCount2].z, angOrthoAxes1Z[orthoCount2].z, orthoRecipResponse[orthoCount2].z, orthoError[orthoCount2].z, constraintDescs[2].disablePreprocessing, con2->solveHint, c->flags[2], orthoCount2, a >= constraintDescs[2].numRows); setOrthoData(ang0X.w, ang0Y.w, ang0Z.w, ang1X.w, ang1Y.w, ang1Z.w, recipResponse[3], cError.w, angOrthoAxes0X[orthoCount3].w, angOrthoAxes0Y[orthoCount3].w, angOrthoAxes0Z[orthoCount3].w, angOrthoAxes1X[orthoCount3].w, angOrthoAxes1Y[orthoCount3].w, angOrthoAxes1Z[orthoCount3].w, orthoRecipResponse[orthoCount3].w, orthoError[orthoCount3].w, constraintDescs[3].disablePreprocessing, con3->solveHint, c->flags[3], orthoCount3, a >= constraintDescs[3].numRows); } 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; if ((con0->flags & Px1DConstraintFlag::eKEEPBIAS)) c->flags[0] |= DY_SC_FLAG_KEEP_BIAS; if ((con1->flags & Px1DConstraintFlag::eKEEPBIAS)) c->flags[1] |= DY_SC_FLAG_KEEP_BIAS; if ((con2->flags & Px1DConstraintFlag::eKEEPBIAS)) c->flags[2] |= DY_SC_FLAG_KEEP_BIAS; if ((con3->flags & Px1DConstraintFlag::eKEEPBIAS)) c->flags[3] |= DY_SC_FLAG_KEEP_BIAS; //Flag inequality constraints... if (con0->solveHint & 1) c->flags[0] |= DY_SC_FLAG_INEQUALITY; if (con1->solveHint & 1) c->flags[1] |= DY_SC_FLAG_INEQUALITY; if (con2->solveHint & 1) c->flags[2] |= DY_SC_FLAG_INEQUALITY; if (con3->solveHint & 1) c->flags[3] |= DY_SC_FLAG_INEQUALITY; } *(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; } static void solveContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, const bool doFriction, const PxReal minPenetration, const PxReal elapsedTimeF32) { PxTGSSolverBodyVel& b00 = *desc[0].tgsBodyA; PxTGSSolverBodyVel& b01 = *desc[0].tgsBodyB; PxTGSSolverBodyVel& b10 = *desc[1].tgsBodyA; PxTGSSolverBodyVel& b11 = *desc[1].tgsBodyB; PxTGSSolverBodyVel& b20 = *desc[2].tgsBodyA; PxTGSSolverBodyVel& b21 = *desc[2].tgsBodyB; PxTGSSolverBodyVel& b30 = *desc[3].tgsBodyA; PxTGSSolverBodyVel& b31 = *desc[3].tgsBodyB; const Vec4V minPen = V4Load(minPenetration); const Vec4V elapsedTime = V4Load(elapsedTimeF32); //We'll need this. const Vec4V vZero = V4Zero(); Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x); Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x); Vec4V angState00 = V4LoadA(&b00.angularVelocity.x); Vec4V angState01 = V4LoadA(&b01.angularVelocity.x); Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x); Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x); Vec4V angState10 = V4LoadA(&b10.angularVelocity.x); Vec4V angState11 = V4LoadA(&b11.angularVelocity.x); Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x); Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x); Vec4V angState20 = V4LoadA(&b20.angularVelocity.x); Vec4V angState21 = V4LoadA(&b21.angularVelocity.x); Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x); Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x); Vec4V angState30 = V4LoadA(&b30.angularVelocity.x); Vec4V angState31 = V4LoadA(&b31.angularVelocity.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); Vec4V linDelta00_ = V4LoadA(&b00.deltaLinDt.x); Vec4V linDelta01_ = V4LoadA(&b01.deltaLinDt.x); Vec4V angDelta00_ = V4LoadA(&b00.deltaAngDt.x); Vec4V angDelta01_ = V4LoadA(&b01.deltaAngDt.x); Vec4V linDelta10_ = V4LoadA(&b10.deltaLinDt.x); Vec4V linDelta11_ = V4LoadA(&b11.deltaLinDt.x); Vec4V angDelta10_ = V4LoadA(&b10.deltaAngDt.x); Vec4V angDelta11_ = V4LoadA(&b11.deltaAngDt.x); Vec4V linDelta20_ = V4LoadA(&b20.deltaLinDt.x); Vec4V linDelta21_ = V4LoadA(&b21.deltaLinDt.x); Vec4V angDelta20_ = V4LoadA(&b20.deltaAngDt.x); Vec4V angDelta21_ = V4LoadA(&b21.deltaAngDt.x); Vec4V linDelta30_ = V4LoadA(&b30.deltaLinDt.x); Vec4V linDelta31_ = V4LoadA(&b31.deltaLinDt.x); Vec4V angDelta30_ = V4LoadA(&b30.deltaAngDt.x); Vec4V angDelta31_ = V4LoadA(&b31.deltaAngDt.x); Vec4V linDelta0T0, linDelta0T1, linDelta0T2; Vec4V linDelta1T0, linDelta1T1, linDelta1T2; Vec4V angDelta0T0, angDelta0T1, angDelta0T2; Vec4V angDelta1T0, angDelta1T1, angDelta1T2; PX_TRANSPOSE_44_34(linDelta00_, linDelta10_, linDelta20_, linDelta30_, linDelta0T0, linDelta0T1, linDelta0T2); PX_TRANSPOSE_44_34(linDelta01_, linDelta11_, linDelta21_, linDelta31_, linDelta1T0, linDelta1T1, linDelta1T2); PX_TRANSPOSE_44_34(angDelta00_, angDelta10_, angDelta20_, angDelta30_, angDelta0T0, angDelta0T1, angDelta0T2); PX_TRANSPOSE_44_34(angDelta01_, angDelta11_, angDelta21_, angDelta31_, angDelta1T0, angDelta1T1, angDelta1T2); 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()); SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr); const Vec4V invMassA = hdr->invMass0D0; const Vec4V invMassB = hdr->invMass1D1; const Vec4V sumInvMass = V4Add(invMassA, invMassB); Vec4V linDeltaX = V4Sub(linDelta0T0, linDelta1T0); Vec4V linDeltaY = V4Sub(linDelta0T1, linDelta1T1); Vec4V linDeltaZ = V4Sub(linDelta0T2, linDelta1T2); while (currPtr < last) { hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr); PX_ASSERT(hdr->type == DY_SC_TYPE_BLOCK_RB_CONTACT); currPtr = reinterpret_cast<PxU8*>(const_cast<SolverContactHeaderStepBlock*>(hdr) + 1); const PxU32 numNormalConstr = hdr->numNormalConstr; const PxU32 numFrictionConstr = hdr->numFrictionConstr; const bool hasMaxImpulse = (hdr->flag & SolverContactHeaderStepBlock::eHAS_MAX_IMPULSE) != 0; Vec4V* appliedForces = reinterpret_cast<Vec4V*>(currPtr); currPtr += sizeof(Vec4V)*numNormalConstr; SolverContactPointStepBlock* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepBlock*>(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 SolverContactFrictionStepBlock* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepBlock*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFrictionStepBlock); 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); const Vec4V maxPenBias = hdr->maxPenBias; Vec4V relVel1 = V4Sub(contactNormalVel1, contactNormalVel3); Vec4V deltaNormalV = V4Mul(linDeltaX, _normalT0); deltaNormalV = V4MulAdd(linDeltaY, _normalT1, deltaNormalV); deltaNormalV = V4MulAdd(linDeltaZ, _normalT2, deltaNormalV); Vec4V accumDeltaF = vZero; for (PxU32 i = 0; i<numNormalConstr; i++) { const SolverContactPointStepBlock& 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.raXnI[0], angState0T0); Vec4V contactNormalVel4 = V4Mul(c.rbXnI[0], angState1T0); contactNormalVel2 = V4MulAdd(c.raXnI[1], angState0T1, contactNormalVel2); contactNormalVel4 = V4MulAdd(c.rbXnI[1], angState1T1, contactNormalVel4); contactNormalVel2 = V4MulAdd(c.raXnI[2], angState0T2, contactNormalVel2); contactNormalVel4 = V4MulAdd(c.rbXnI[2], angState1T2, contactNormalVel4); const Vec4V normalVel = V4Add(relVel1, V4Sub(contactNormalVel2, contactNormalVel4)); Vec4V angDelta0 = V4Mul(angDelta0T0, c.raXnI[0]); Vec4V angDelta1 = V4Mul(angDelta1T0, c.rbXnI[0]); angDelta0 = V4MulAdd(angDelta0T1, c.raXnI[1], angDelta0); angDelta1 = V4MulAdd(angDelta1T1, c.rbXnI[1], angDelta1); angDelta0 = V4MulAdd(angDelta0T2, c.raXnI[2], angDelta0); angDelta1 = V4MulAdd(angDelta1T2, c.rbXnI[2], angDelta1); const Vec4V deltaAng = V4Sub(angDelta0, angDelta1); const Vec4V targetVel = c.targetVelocity; const Vec4V deltaBias = V4Sub(V4Add(deltaNormalV, deltaAng), V4Mul(targetVel, elapsedTime)); //const Vec4V deltaBias = V4Add(deltaNormalV, deltaAng); const Vec4V biasCoefficient = c.biasCoefficient; const Vec4V sep = V4Max(minPen, V4Add(c.separation, deltaBias)); const Vec4V bias = V4Min(V4Neg(maxPenBias), V4Mul(biasCoefficient, sep)); const Vec4V velMultiplier = c.velMultiplier; const Vec4V tVelBias = V4Mul(bias, c.recipResponse); const Vec4V _deltaF = V4Max(V4Sub(tVelBias, V4Mul(V4Sub(normalVel, targetVel), velMultiplier)), V4Neg(appliedForce)); //Vec4V deltaF = V4NegMulSub(normalVel, c.velMultiplier, c.biasedErr); const Vec4V newAppliedForce = V4Min(V4Add(appliedForce, _deltaF), maxImpulse); const Vec4V 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.raXnI[0], angDetaF0, angState0T0); angState1T0 = V4NegMulSub(c.rbXnI[0], angDetaF1, angState1T0); angState0T1 = V4MulAdd(c.raXnI[1], angDetaF0, angState0T1); angState1T1 = V4NegMulSub(c.rbXnI[1], angDetaF1, angState1T1); angState0T2 = V4MulAdd(c.raXnI[2], angDetaF0, angState0T2); angState1T2 = V4NegMulSub(c.rbXnI[2], 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 (doFriction && numFrictionConstr) { const Vec4V staticFric = hdr->staticFriction; const Vec4V dynamicFric = hdr->dynamicFriction; const Vec4V maxFrictionImpulse = V4Add(V4Mul(staticFric, accumulatedNormalImpulse), V4Load(1e-5f)); const Vec4V maxDynFrictionImpulse = V4Mul(dynamicFric, accumulatedNormalImpulse); BoolV broken = BFFFF(); for (PxU32 i = 0; i<numFrictionConstr; i+=2) { const SolverContactFrictionStepBlock& f0 = frictions[i]; const SolverContactFrictionStepBlock& f1 = frictions[i+1]; /*PxU32 offset = 0; PxPrefetchLine(prefetchAddress, offset += 64); PxPrefetchLine(prefetchAddress, offset += 64); PxPrefetchLine(prefetchAddress, offset += 64); PxPrefetchLine(prefetchAddress, offset += 64); prefetchAddress += offset;*/ const Vec4V appliedForce0 = frictionAppliedForce[i]; const Vec4V appliedForce1 = frictionAppliedForce[i+1]; const Vec4V normalT00 = f0.normal[0]; const Vec4V normalT10 = f0.normal[1]; const Vec4V normalT20 = f0.normal[2]; const Vec4V normalT01 = f1.normal[0]; const Vec4V normalT11 = f1.normal[1]; const Vec4V normalT21 = f1.normal[2]; Vec4V normalVel10 = V4Mul(linVel0T0, normalT00); Vec4V normalVel20 = V4Mul(f0.raXnI[0], angState0T0); Vec4V normalVel30 = V4Mul(linVel1T0, normalT00); Vec4V normalVel40 = V4Mul(f0.rbXnI[0], angState1T0); Vec4V normalVel11 = V4Mul(linVel0T0, normalT01); Vec4V normalVel21 = V4Mul(f1.raXnI[0], angState0T0); Vec4V normalVel31 = V4Mul(linVel1T0, normalT01); Vec4V normalVel41 = V4Mul(f1.rbXnI[0], angState1T0); normalVel10 = V4MulAdd(linVel0T1, normalT10, normalVel10); normalVel20 = V4MulAdd(f0.raXnI[1], angState0T1, normalVel20); normalVel30 = V4MulAdd(linVel1T1, normalT10, normalVel30); normalVel40 = V4MulAdd(f0.rbXnI[1], angState1T1, normalVel40); normalVel11 = V4MulAdd(linVel0T1, normalT11, normalVel11); normalVel21 = V4MulAdd(f1.raXnI[1], angState0T1, normalVel21); normalVel31 = V4MulAdd(linVel1T1, normalT11, normalVel31); normalVel41 = V4MulAdd(f1.rbXnI[1], angState1T1, normalVel41); normalVel10 = V4MulAdd(linVel0T2, normalT20, normalVel10); normalVel20 = V4MulAdd(f0.raXnI[2], angState0T2, normalVel20); normalVel30 = V4MulAdd(linVel1T2, normalT20, normalVel30); normalVel40 = V4MulAdd(f0.rbXnI[2], angState1T2, normalVel40); normalVel11 = V4MulAdd(linVel0T2, normalT21, normalVel11); normalVel21 = V4MulAdd(f1.raXnI[2], angState0T2, normalVel21); normalVel31 = V4MulAdd(linVel1T2, normalT21, normalVel31); normalVel41 = V4MulAdd(f1.rbXnI[2], angState1T2, normalVel41); const Vec4V normalVel0_tmp1 = V4Add(normalVel10, normalVel20); const Vec4V normalVel0_tmp2 = V4Add(normalVel30, normalVel40); const Vec4V normalVel0 = V4Sub(normalVel0_tmp1, normalVel0_tmp2); const Vec4V normalVel1_tmp1 = V4Add(normalVel11, normalVel21); const Vec4V normalVel1_tmp2 = V4Add(normalVel31, normalVel41); const Vec4V normalVel1 = V4Sub(normalVel1_tmp1, normalVel1_tmp2); Vec4V deltaV0 = V4Mul(linDeltaX, normalT00); deltaV0 = V4MulAdd(linDeltaY, normalT10, deltaV0); deltaV0 = V4MulAdd(linDeltaZ, normalT20, deltaV0); Vec4V deltaV1 = V4Mul(linDeltaX, normalT01); deltaV1 = V4MulAdd(linDeltaY, normalT11, deltaV1); deltaV1 = V4MulAdd(linDeltaZ, normalT21, deltaV1); Vec4V angDelta00 = V4Mul(angDelta0T0, f0.raXnI[0]); Vec4V angDelta10 = V4Mul(angDelta1T0, f0.rbXnI[0]); angDelta00 = V4MulAdd(angDelta0T1, f0.raXnI[1], angDelta00); angDelta10 = V4MulAdd(angDelta1T1, f0.rbXnI[1], angDelta10); angDelta00 = V4MulAdd(angDelta0T2, f0.raXnI[2], angDelta00); angDelta10 = V4MulAdd(angDelta1T2, f0.rbXnI[2], angDelta10); Vec4V angDelta01 = V4Mul(angDelta0T0, f1.raXnI[0]); Vec4V angDelta11 = V4Mul(angDelta1T0, f1.rbXnI[0]); angDelta01 = V4MulAdd(angDelta0T1, f1.raXnI[1], angDelta01); angDelta11 = V4MulAdd(angDelta1T1, f1.rbXnI[1], angDelta11); angDelta01 = V4MulAdd(angDelta0T2, f1.raXnI[2], angDelta01); angDelta11 = V4MulAdd(angDelta1T2, f1.rbXnI[2], angDelta11); const Vec4V deltaAng0 = V4Sub(angDelta00, angDelta10); const Vec4V deltaAng1 = V4Sub(angDelta01, angDelta11); const Vec4V deltaBias0 = V4Sub(V4Add(deltaV0, deltaAng0), V4Mul(f0.targetVel, elapsedTime)); const Vec4V deltaBias1 = V4Sub(V4Add(deltaV1, deltaAng1), V4Mul(f1.targetVel, elapsedTime)); const Vec4V error0 = V4Add(f0.error, deltaBias0); const Vec4V error1 = V4Add(f1.error, deltaBias1); const Vec4V bias0 = V4Mul(error0, f0.biasCoefficient); const Vec4V bias1 = V4Mul(error1, f1.biasCoefficient); const Vec4V tmp10 = V4NegMulSub(V4Sub(bias0, f0.targetVel), f0.velMultiplier, appliedForce0); const Vec4V tmp11 = V4NegMulSub(V4Sub(bias1, f1.targetVel), f1.velMultiplier, appliedForce1); const Vec4V totalImpulse0 = V4NegMulSub(normalVel0, f0.velMultiplier, tmp10); const Vec4V totalImpulse1 = V4NegMulSub(normalVel1, f1.velMultiplier, tmp11); const Vec4V totalImpulse = V4Sqrt(V4MulAdd(totalImpulse0, totalImpulse0, V4Mul(totalImpulse1, totalImpulse1))); const BoolV clamped = V4IsGrtr(totalImpulse, maxFrictionImpulse); broken = BOr(broken, clamped); const Vec4V totalClamped = V4Sel(broken, V4Min(totalImpulse, maxDynFrictionImpulse), totalImpulse); const Vec4V ratio = V4Sel(V4IsGrtr(totalImpulse, vZero), V4Div(totalClamped, totalImpulse), vZero); const Vec4V newAppliedForce0 = V4Mul(totalImpulse0, ratio); const Vec4V newAppliedForce1 = V4Mul(totalImpulse1, ratio); const Vec4V deltaF0 = V4Sub(newAppliedForce0, appliedForce0); const Vec4V deltaF1 = V4Sub(newAppliedForce1, appliedForce1); frictionAppliedForce[i] = newAppliedForce0; frictionAppliedForce[i+1] = newAppliedForce1; const Vec4V deltaFIM00 = V4Mul(deltaF0, invMassA); const Vec4V deltaFIM10 = V4Mul(deltaF0, invMassB); const Vec4V angDetaF00 = V4Mul(deltaF0, angD0); const Vec4V angDetaF10 = V4Mul(deltaF0, angD1); const Vec4V deltaFIM01 = V4Mul(deltaF1, invMassA); const Vec4V deltaFIM11 = V4Mul(deltaF1, invMassB); const Vec4V angDetaF01 = V4Mul(deltaF1, angD0); const Vec4V angDetaF11 = V4Mul(deltaF1, angD1); linVel0T0 = V4MulAdd(normalT00, deltaFIM00, V4MulAdd(normalT01, deltaFIM01, linVel0T0)); linVel1T0 = V4NegMulSub(normalT00, deltaFIM10, V4NegMulSub(normalT01, deltaFIM11, linVel1T0)); angState0T0 = V4MulAdd(f0.raXnI[0], angDetaF00, V4MulAdd(f1.raXnI[0], angDetaF01, angState0T0)); angState1T0 = V4NegMulSub(f0.rbXnI[0], angDetaF10, V4NegMulSub(f1.rbXnI[0], angDetaF11, angState1T0)); linVel0T1 = V4MulAdd(normalT10, deltaFIM00, V4MulAdd(normalT11, deltaFIM01, linVel0T1)); linVel1T1 = V4NegMulSub(normalT10, deltaFIM10, V4NegMulSub(normalT11, deltaFIM11, linVel1T1)); angState0T1 = V4MulAdd(f0.raXnI[1], angDetaF00, V4MulAdd(f1.raXnI[1], angDetaF01, angState0T1)); angState1T1 = V4NegMulSub(f0.rbXnI[1], angDetaF10, V4NegMulSub(f1.rbXnI[1], angDetaF11, angState1T1)); linVel0T2 = V4MulAdd(normalT20, deltaFIM00, V4MulAdd(normalT21, deltaFIM01, linVel0T2)); linVel1T2 = V4NegMulSub(normalT20, deltaFIM10, V4NegMulSub(normalT21, deltaFIM11, linVel1T2)); angState0T2 = V4MulAdd(f0.raXnI[2], angDetaF00, V4MulAdd(f1.raXnI[2], angDetaF01, angState0T2)); angState1T2 = V4NegMulSub(f0.rbXnI[2], angDetaF10, V4NegMulSub(f1.rbXnI[2], angDetaF11, angState1T2)); } hdr->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.angularVelocity.isFinite()); PX_ASSERT(b10.linearVelocity.isFinite()); PX_ASSERT(b10.angularVelocity.isFinite()); PX_ASSERT(b20.linearVelocity.isFinite()); PX_ASSERT(b20.angularVelocity.isFinite()); PX_ASSERT(b30.linearVelocity.isFinite()); PX_ASSERT(b30.angularVelocity.isFinite()); PX_ASSERT(b01.linearVelocity.isFinite()); PX_ASSERT(b01.angularVelocity.isFinite()); PX_ASSERT(b11.linearVelocity.isFinite()); PX_ASSERT(b11.angularVelocity.isFinite()); PX_ASSERT(b21.linearVelocity.isFinite()); PX_ASSERT(b21.angularVelocity.isFinite()); PX_ASSERT(b31.linearVelocity.isFinite()); PX_ASSERT(b31.angularVelocity.isFinite()); // Write back V4StoreA(linVel00, &b00.linearVelocity.x); V4StoreA(angState00, &b00.angularVelocity.x); V4StoreA(linVel10, &b10.linearVelocity.x); V4StoreA(angState10, &b10.angularVelocity.x); V4StoreA(linVel20, &b20.linearVelocity.x); V4StoreA(angState20, &b20.angularVelocity.x); V4StoreA(linVel30, &b30.linearVelocity.x); V4StoreA(angState30, &b30.angularVelocity.x); if (desc[0].bodyBDataIndex != 0) { V4StoreA(linVel01, &b01.linearVelocity.x); V4StoreA(angState01, &b01.angularVelocity.x); } if (desc[1].bodyBDataIndex != 0) { V4StoreA(linVel11, &b11.linearVelocity.x); V4StoreA(angState11, &b11.angularVelocity.x); } if (desc[2].bodyBDataIndex != 0) { V4StoreA(linVel21, &b21.linearVelocity.x); V4StoreA(angState21, &b21.angularVelocity.x); } if (desc[3].bodyBDataIndex != 0) { V4StoreA(linVel31, &b31.linearVelocity.x); V4StoreA(angState31, &b31.angularVelocity.x); } PX_ASSERT(b00.linearVelocity.isFinite()); PX_ASSERT(b00.angularVelocity.isFinite()); PX_ASSERT(b10.linearVelocity.isFinite()); PX_ASSERT(b10.angularVelocity.isFinite()); PX_ASSERT(b20.linearVelocity.isFinite()); PX_ASSERT(b20.angularVelocity.isFinite()); PX_ASSERT(b30.linearVelocity.isFinite()); PX_ASSERT(b30.angularVelocity.isFinite()); PX_ASSERT(b01.linearVelocity.isFinite()); PX_ASSERT(b01.angularVelocity.isFinite()); PX_ASSERT(b11.linearVelocity.isFinite()); PX_ASSERT(b11.angularVelocity.isFinite()); PX_ASSERT(b21.linearVelocity.isFinite()); PX_ASSERT(b21.angularVelocity.isFinite()); PX_ASSERT(b31.linearVelocity.isFinite()); PX_ASSERT(b31.angularVelocity.isFinite()); } static void writeBackContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc, SolverContext* /*cache*/) { 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 = sizeof(SolverContactPointStepBlock); const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock); Vec4V normalForce = V4Zero(); //We'll need this. //const Vec4V vZero = V4Zero(); bool writeBackThresholds[4] = { false, false, false, false }; while ((currPtr < last)) { SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(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); const bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0; if (hasMaxImpulse) currPtr += sizeof(Vec4V) * numNormalConstr; 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->numNormalConstrs[0]) FStore(appliedForce0, vForceWriteback0++); if (vForceWriteback1 && i < hdr->numNormalConstrs[1]) FStore(appliedForce1, vForceWriteback1++); if (vForceWriteback2 && i < hdr->numNormalConstrs[2]) FStore(appliedForce2, vForceWriteback2++); if (vForceWriteback3 && i < hdr->numNormalConstrs[3]) FStore(appliedForce3, vForceWriteback3++); } if (numFrictionConstr) { PX_ALIGN(16, PxU32 broken[4]); BStoreA(hdr->broken, broken); PxU8* frictionCounts = hdr->numNormalConstrs; for (PxU32 a = 0; a < 4; ++a) { if (frictionCounts[a] && broken[a]) *hdr->frictionBrokenWritebackByte[a] = 1; // PT: bad L2 miss here } } } PX_UNUSED(writeBackThresholds); #if 0 if (cache) { 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::NO_LINK && desc[a].linkIndexB == PxSolverConstraintDesc::NO_LINK && 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 = bd0[a]->nodeIndex; elt.nodeIndexB = 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; } } } #endif } void solveContact4(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(txInertias); PX_UNUSED(cache); solveContact4_Block(desc + hdr.startIndex, true, minPenetration, elapsedTime); } void writeBackContact4(DY_TGS_WRITEBACK_METHOD_PARAMS) { writeBackContact4_Block(desc + hdr.startIndex, cache); } static PX_FORCE_INLINE Vec4V V4Dot3(const Vec4V& x0, const Vec4V& y0, const Vec4V& z0, const Vec4V& x1, const Vec4V& y1, const Vec4V& z1) { return V4MulAdd(x0, x1, V4MulAdd(y0, y1, V4Mul(z0, z1))); } static void solve1DStep4(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxTGSSolverBodyTxInertia* const txInertias, PxReal elapsedTimeF32) { PxU8* PX_RESTRICT bPtr = desc->constraint; if (bPtr == NULL) return; const FloatV elapsedTime = FLoad(elapsedTimeF32); PxTGSSolverBodyVel& b00 = *desc[0].tgsBodyA; PxTGSSolverBodyVel& b01 = *desc[0].tgsBodyB; PxTGSSolverBodyVel& b10 = *desc[1].tgsBodyA; PxTGSSolverBodyVel& b11 = *desc[1].tgsBodyB; PxTGSSolverBodyVel& b20 = *desc[2].tgsBodyA; PxTGSSolverBodyVel& b21 = *desc[2].tgsBodyB; PxTGSSolverBodyVel& b30 = *desc[3].tgsBodyA; PxTGSSolverBodyVel& b31 = *desc[3].tgsBodyB; const PxTGSSolverBodyTxInertia& txI00 = txInertias[desc[0].bodyADataIndex]; const PxTGSSolverBodyTxInertia& txI01 = txInertias[desc[0].bodyBDataIndex]; const PxTGSSolverBodyTxInertia& txI10 = txInertias[desc[1].bodyADataIndex]; const PxTGSSolverBodyTxInertia& txI11 = txInertias[desc[1].bodyBDataIndex]; const PxTGSSolverBodyTxInertia& txI20 = txInertias[desc[2].bodyADataIndex]; const PxTGSSolverBodyTxInertia& txI21 = txInertias[desc[2].bodyBDataIndex]; const PxTGSSolverBodyTxInertia& txI30 = txInertias[desc[3].bodyADataIndex]; const PxTGSSolverBodyTxInertia& txI31 = txInertias[desc[3].bodyBDataIndex]; Vec4V linVel00 = V4LoadA(&b00.linearVelocity.x); Vec4V linVel01 = V4LoadA(&b01.linearVelocity.x); Vec4V angState00 = V4LoadA(&b00.angularVelocity.x); Vec4V angState01 = V4LoadA(&b01.angularVelocity.x); Vec4V linVel10 = V4LoadA(&b10.linearVelocity.x); Vec4V linVel11 = V4LoadA(&b11.linearVelocity.x); Vec4V angState10 = V4LoadA(&b10.angularVelocity.x); Vec4V angState11 = V4LoadA(&b11.angularVelocity.x); Vec4V linVel20 = V4LoadA(&b20.linearVelocity.x); Vec4V linVel21 = V4LoadA(&b21.linearVelocity.x); Vec4V angState20 = V4LoadA(&b20.angularVelocity.x); Vec4V angState21 = V4LoadA(&b21.angularVelocity.x); Vec4V linVel30 = V4LoadA(&b30.linearVelocity.x); Vec4V linVel31 = V4LoadA(&b31.linearVelocity.x); Vec4V angState30 = V4LoadA(&b30.angularVelocity.x); Vec4V angState31 = V4LoadA(&b31.angularVelocity.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); Vec4V linDelta00 = V4LoadA(&b00.deltaLinDt.x); Vec4V linDelta01 = V4LoadA(&b01.deltaLinDt.x); Vec4V angDelta00 = V4LoadA(&b00.deltaAngDt.x); Vec4V angDelta01 = V4LoadA(&b01.deltaAngDt.x); Vec4V linDelta10 = V4LoadA(&b10.deltaLinDt.x); Vec4V linDelta11 = V4LoadA(&b11.deltaLinDt.x); Vec4V angDelta10 = V4LoadA(&b10.deltaAngDt.x); Vec4V angDelta11 = V4LoadA(&b11.deltaAngDt.x); Vec4V linDelta20 = V4LoadA(&b20.deltaLinDt.x); Vec4V linDelta21 = V4LoadA(&b21.deltaLinDt.x); Vec4V angDelta20 = V4LoadA(&b20.deltaAngDt.x); Vec4V angDelta21 = V4LoadA(&b21.deltaAngDt.x); Vec4V linDelta30 = V4LoadA(&b30.deltaLinDt.x); Vec4V linDelta31 = V4LoadA(&b31.deltaLinDt.x); Vec4V angDelta30 = V4LoadA(&b30.deltaAngDt.x); Vec4V angDelta31 = V4LoadA(&b31.deltaAngDt.x); Vec4V linDelta0T0, linDelta0T1, linDelta0T2; Vec4V linDelta1T0, linDelta1T1, linDelta1T2; Vec4V angDelta0T0, angDelta0T1, angDelta0T2; Vec4V angDelta1T0, angDelta1T1, angDelta1T2; PX_TRANSPOSE_44_34(linDelta00, linDelta10, linDelta20, linDelta30, linDelta0T0, linDelta0T1, linDelta0T2); PX_TRANSPOSE_44_34(linDelta01, linDelta11, linDelta21, linDelta31, linDelta1T0, linDelta1T1, linDelta1T2); PX_TRANSPOSE_44_34(angDelta00, angDelta10, angDelta20, angDelta30, angDelta0T0, angDelta0T1, angDelta0T2); PX_TRANSPOSE_44_34(angDelta01, angDelta11, angDelta21, angDelta31, angDelta1T0, angDelta1T1, angDelta1T2); const SolverConstraint1DHeaderStep4* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep4*>(bPtr); SolverConstraint1DStep4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep4*>(bPtr + sizeof(SolverConstraint1DHeaderStep4)); Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI00.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI00.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(txI00.sqrtInvInertia.column2)); Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI10.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI10.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(txI10.sqrtInvInertia.column2)); Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI20.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI20.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(txI20.sqrtInvInertia.column2)); Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI30.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI30.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(txI30.sqrtInvInertia.column2)); Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI01.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI01.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(txI01.sqrtInvInertia.column2)); Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI11.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI11.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(txI11.sqrtInvInertia.column2)); Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI21.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI21.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(txI21.sqrtInvInertia.column2)); Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI31.sqrtInvInertia.column0)); // PT: safe because 'column1' follows 'column0' in PxMat33 Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU_SafeReadW(txI31.sqrtInvInertia.column1)); // PT: safe because 'column2' follows 'column1' in PxMat33 Vec4V invInertia31Z = Vec4V_From_Vec3V(V3LoadU(txI31.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 Vec4V invInertiaScale0 = header->angD0; const Vec4V invInertiaScale1 = header->angD1; //KS - todo - load this a bit quicker... Vec4V rot00 = V4LoadA(&txI00.deltaBody2World.q.x); Vec4V rot01 = V4LoadA(&txI01.deltaBody2World.q.x); Vec4V rot10 = V4LoadA(&txI10.deltaBody2World.q.x); Vec4V rot11 = V4LoadA(&txI11.deltaBody2World.q.x); Vec4V rot20 = V4LoadA(&txI20.deltaBody2World.q.x); Vec4V rot21 = V4LoadA(&txI21.deltaBody2World.q.x); Vec4V rot30 = V4LoadA(&txI30.deltaBody2World.q.x); Vec4V rot31 = V4LoadA(&txI31.deltaBody2World.q.x); Vec4V rot0X, rot0Y, rot0Z, rot0W; Vec4V rot1X, rot1Y, rot1Z, rot1W; PX_TRANSPOSE_44(rot00, rot10, rot20, rot30, rot0X, rot0Y, rot0Z, rot0W); PX_TRANSPOSE_44(rot01, rot11, rot21, rot31, rot1X, rot1Y, rot1Z, rot1W); Vec4V raX, raY, raZ; Vec4V rbX, rbY, rbZ; QuatRotate4(rot0X, rot0Y, rot0Z, rot0W, header->rAWorld[0], header->rAWorld[1], header->rAWorld[2], raX, raY, raZ); QuatRotate4(rot1X, rot1Y, rot1Z, rot1W, header->rBWorld[0], header->rBWorld[1], header->rBWorld[2], rbX, rbY, rbZ); const Vec4V raMotionX = V4Sub(V4Add(raX, linDelta0T0), header->rAWorld[0]); const Vec4V raMotionY = V4Sub(V4Add(raY, linDelta0T1), header->rAWorld[1]); const Vec4V raMotionZ = V4Sub(V4Add(raZ, linDelta0T2), header->rAWorld[2]); const Vec4V rbMotionX = V4Sub(V4Add(rbX, linDelta1T0), header->rBWorld[0]); const Vec4V rbMotionY = V4Sub(V4Add(rbY, linDelta1T1), header->rBWorld[1]); const Vec4V rbMotionZ = V4Sub(V4Add(rbZ, linDelta1T2), header->rBWorld[2]); const Vec4V mass0 = header->invMass0D0; const Vec4V mass1 = header->invMass1D1; const VecI32V orthoMask = I4Load(DY_SC_FLAG_ORTHO_TARGET); const VecI32V limitMask = I4Load(DY_SC_FLAG_INEQUALITY); const Vec4V zero = V4Zero(); const Vec4V one = V4One(); Vec4V error0 = V4Add(header->angOrthoError[0], V4Sub(V4Dot3(header->angOrthoAxis0X[0], header->angOrthoAxis0Y[0], header->angOrthoAxis0Z[0], angDelta0T0, angDelta0T1, angDelta0T2), V4Dot3(header->angOrthoAxis1X[0], header->angOrthoAxis1Y[0], header->angOrthoAxis1Z[0], angDelta1T0, angDelta1T1, angDelta1T2))); Vec4V error1 = V4Add(header->angOrthoError[1], V4Sub(V4Dot3(header->angOrthoAxis0X[1], header->angOrthoAxis0Y[1], header->angOrthoAxis0Z[1], angDelta0T0, angDelta0T1, angDelta0T2), V4Dot3(header->angOrthoAxis1X[1], header->angOrthoAxis1Y[1], header->angOrthoAxis1Z[1], angDelta1T0, angDelta1T1, angDelta1T2))); Vec4V error2 = V4Add(header->angOrthoError[2], V4Sub(V4Dot3(header->angOrthoAxis0X[2], header->angOrthoAxis0Y[2], header->angOrthoAxis0Z[2], angDelta0T0, angDelta0T1, angDelta0T2), V4Dot3(header->angOrthoAxis1X[2], header->angOrthoAxis1Y[2], header->angOrthoAxis1Z[2], angDelta1T0, angDelta1T1, angDelta1T2))); const PxU32 count = header->count; for (PxU32 i = 0; i<count; ++i, base++) { PxPrefetchLine(base + 1); SolverConstraint1DStep4& c = *base; const Vec4V cangVel0X = V4Add(c.ang0[0], V4NegMulSub(raZ, c.lin0[1], V4Mul(raY, c.lin0[2]))); const Vec4V cangVel0Y = V4Add(c.ang0[1], V4NegMulSub(raX, c.lin0[2], V4Mul(raZ, c.lin0[0]))); const Vec4V cangVel0Z = V4Add(c.ang0[2], V4NegMulSub(raY, c.lin0[0], V4Mul(raX, c.lin0[1]))); const Vec4V cangVel1X = V4Add(c.ang1[0], V4NegMulSub(rbZ, c.lin1[1], V4Mul(rbY, c.lin1[2]))); const Vec4V cangVel1Y = V4Add(c.ang1[1], V4NegMulSub(rbX, c.lin1[2], V4Mul(rbZ, c.lin1[0]))); const Vec4V cangVel1Z = V4Add(c.ang1[2], V4NegMulSub(rbY, c.lin1[0], V4Mul(rbX, c.lin1[1]))); const VecI32V flags = I4LoadA(reinterpret_cast<PxI32*>(c.flags)); const BoolV useOrtho = VecI32V_IsEq(VecI32V_And(flags, orthoMask), orthoMask); const Vec4V angOrthoCoefficient = V4Sel(useOrtho, one, zero); Vec4V delAngVel0X = V4Mul(invInertia0X0, cangVel0X); Vec4V delAngVel0Y = V4Mul(invInertia0X1, cangVel0X); Vec4V delAngVel0Z = V4Mul(invInertia0X2, cangVel0X); delAngVel0X = V4MulAdd(invInertia0Y0, cangVel0Y, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Y1, cangVel0Y, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Y2, cangVel0Y, delAngVel0Z); delAngVel0X = V4MulAdd(invInertia0Z0, cangVel0Z, delAngVel0X); delAngVel0Y = V4MulAdd(invInertia0Z1, cangVel0Z, delAngVel0Y); delAngVel0Z = V4MulAdd(invInertia0Z2, cangVel0Z, delAngVel0Z); Vec4V delAngVel1X = V4Mul(invInertia1X0, cangVel1X); Vec4V delAngVel1Y = V4Mul(invInertia1X1, cangVel1X); Vec4V delAngVel1Z = V4Mul(invInertia1X2, cangVel1X); delAngVel1X = V4MulAdd(invInertia1Y0, cangVel1Y, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Y1, cangVel1Y, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Y2, cangVel1Y, delAngVel1Z); delAngVel1X = V4MulAdd(invInertia1Z0, cangVel1Z, delAngVel1X); delAngVel1Y = V4MulAdd(invInertia1Z1, cangVel1Z, delAngVel1Y); delAngVel1Z = V4MulAdd(invInertia1Z2, cangVel1Z, delAngVel1Z); Vec4V err = c.error; { const Vec4V proj0 = V4Mul(V4MulAdd(header->angOrthoAxis0X[0], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[0], delAngVel0Y, V4MulAdd(header->angOrthoAxis0Z[0], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[0], delAngVel1X, V4MulAdd(header->angOrthoAxis1Y[0], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[0], delAngVel1Z)))))), header->angOrthoRecipResponse[0]); const Vec4V proj1 = V4Mul(V4MulAdd(header->angOrthoAxis0X[1], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[1], delAngVel0Y, V4MulAdd(header->angOrthoAxis0Z[1], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[1], delAngVel1X, V4MulAdd(header->angOrthoAxis1Y[1], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[1], delAngVel1Z)))))), header->angOrthoRecipResponse[1]); const Vec4V proj2 = V4Mul(V4MulAdd(header->angOrthoAxis0X[2], delAngVel0X, V4MulAdd(header->angOrthoAxis0Y[2], delAngVel0Y, V4MulAdd(header->angOrthoAxis0Z[2], delAngVel0Z, V4MulAdd(header->angOrthoAxis1X[2], delAngVel1X, V4MulAdd(header->angOrthoAxis1Y[2], delAngVel1Y, V4Mul(header->angOrthoAxis1Z[2], delAngVel1Z)))))), header->angOrthoRecipResponse[2]); const Vec4V delta0X = V4MulAdd(header->angOrthoAxis0X[0], proj0, V4MulAdd(header->angOrthoAxis0X[1], proj1, V4Mul(header->angOrthoAxis0X[2], proj2))); const Vec4V delta0Y = V4MulAdd(header->angOrthoAxis0Y[0], proj0, V4MulAdd(header->angOrthoAxis0Y[1], proj1, V4Mul(header->angOrthoAxis0Y[2], proj2))); const Vec4V delta0Z = V4MulAdd(header->angOrthoAxis0Z[0], proj0, V4MulAdd(header->angOrthoAxis0Z[1], proj1, V4Mul(header->angOrthoAxis0Z[2], proj2))); const Vec4V delta1X = V4MulAdd(header->angOrthoAxis1X[0], proj0, V4MulAdd(header->angOrthoAxis1X[1], proj1, V4Mul(header->angOrthoAxis1X[2], proj2))); const Vec4V delta1Y = V4MulAdd(header->angOrthoAxis1Y[0], proj0, V4MulAdd(header->angOrthoAxis1Y[1], proj1, V4Mul(header->angOrthoAxis1Y[2], proj2))); const Vec4V delta1Z = V4MulAdd(header->angOrthoAxis1Z[0], proj0, V4MulAdd(header->angOrthoAxis1Z[1], proj1, V4Mul(header->angOrthoAxis1Z[2], proj2))); delAngVel0X = V4NegMulSub(delta0X, angOrthoCoefficient, delAngVel0X); delAngVel0Y = V4NegMulSub(delta0Y, angOrthoCoefficient, delAngVel0Y); delAngVel0Z = V4NegMulSub(delta0Z, angOrthoCoefficient, delAngVel0Z); delAngVel1X = V4NegMulSub(delta1X, angOrthoCoefficient, delAngVel1X); delAngVel1Y = V4NegMulSub(delta1Y, angOrthoCoefficient, delAngVel1Y); delAngVel1Z = V4NegMulSub(delta1Z, angOrthoCoefficient, delAngVel1Z); err = V4Sub(err, V4Mul(V4MulAdd(error0, proj0, V4MulAdd(error1, proj1, V4Mul(error2, proj2))), angOrthoCoefficient)); } Vec4V ang0IX = V4Mul(invInertia0X0, delAngVel0X); Vec4V ang0IY = V4Mul(invInertia0X1, delAngVel0X); Vec4V ang0IZ = V4Mul(invInertia0X2, delAngVel0X); ang0IX = V4MulAdd(invInertia0Y0, delAngVel0Y, ang0IX); ang0IY = V4MulAdd(invInertia0Y1, delAngVel0Y, ang0IY); ang0IZ = V4MulAdd(invInertia0Y2, delAngVel0Y, ang0IZ); ang0IX = V4MulAdd(invInertia0Z0, delAngVel0Z, ang0IX); ang0IY = V4MulAdd(invInertia0Z1, delAngVel0Z, ang0IY); ang0IZ = V4MulAdd(invInertia0Z2, delAngVel0Z, ang0IZ); Vec4V ang1IX = V4Mul(invInertia1X0, delAngVel1X); Vec4V ang1IY = V4Mul(invInertia1X1, delAngVel1X); Vec4V ang1IZ = V4Mul(invInertia1X2, delAngVel1X); ang1IX = V4MulAdd(invInertia1Y0, delAngVel1Y, ang1IX); ang1IY = V4MulAdd(invInertia1Y1, delAngVel1Y, ang1IY); ang1IZ = V4MulAdd(invInertia1Y2, delAngVel1Y, ang1IZ); ang1IX = V4MulAdd(invInertia1Z0, delAngVel1Z, ang1IX); ang1IY = V4MulAdd(invInertia1Z1, delAngVel1Z, ang1IY); ang1IZ = V4MulAdd(invInertia1Z2, delAngVel1Z, ang1IZ); const Vec4V clinVel0X = c.lin0[0]; const Vec4V clinVel0Y = c.lin0[1]; const Vec4V clinVel0Z = c.lin0[2]; const Vec4V clinVel1X = c.lin1[0]; const Vec4V clinVel1Y = c.lin1[1]; const Vec4V clinVel1Z = c.lin1[2]; const Vec4V clinVel0X_ = c.lin0[0]; const Vec4V clinVel0Y_ = c.lin0[1]; const Vec4V clinVel0Z_ = c.lin0[2]; const Vec4V clinVel1X_ = c.lin1[0]; const Vec4V clinVel1Y_ = c.lin1[1]; const Vec4V clinVel1Z_ = c.lin1[2]; //KS - compute raXnI and effective mass. Unfortunately, the joints are noticeably less stable if we don't do this each //iteration. It's skippable. If we do that, there's no need for the invInertiaTensors const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0X, delAngVel0X, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0Z, delAngVel0Z))); const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1X, delAngVel1X, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1Z, delAngVel1Z))); const Vec4V dotRbXnAngDelta0 = V4MulAdd(delAngVel0X, angDelta0T0, V4MulAdd(delAngVel0Y, angDelta0T1, V4Mul(delAngVel0Z, angDelta0T2))); const Vec4V dotRbXnAngDelta1 = V4MulAdd(delAngVel1X, angDelta1T0, V4MulAdd(delAngVel1Y, angDelta1T1, V4Mul(delAngVel1Z, angDelta1T2))); const Vec4V dotRaMotion = V4MulAdd(clinVel0X_, raMotionX, V4MulAdd(clinVel0Y_, raMotionY, V4Mul(clinVel0Z_, raMotionZ))); const Vec4V dotRbMotion = V4MulAdd(clinVel1X_, rbMotionX, V4MulAdd(clinVel1Y_, rbMotionY, V4Mul(clinVel1Z_, rbMotionZ))); const Vec4V deltaAng = V4Mul(c.angularErrorScale, V4Sub(dotRbXnAngDelta0, dotRbXnAngDelta1)); const Vec4V errorChange = V4NegScaleSub(c.velTarget, elapsedTime, V4Add(V4Sub(dotRaMotion, dotRbMotion), deltaAng)); const Vec4V dotClinVel0 = V4MulAdd(clinVel0X, clinVel0X, V4MulAdd(clinVel0Y, clinVel0Y, V4Mul(clinVel0Z, clinVel0Z))); const Vec4V dotClinVel1 = V4MulAdd(clinVel1X, clinVel1X, V4MulAdd(clinVel1Y, clinVel1Y, V4Mul(clinVel1Z, clinVel1Z))); const Vec4V resp0 = V4MulAdd(mass0, dotClinVel0, V4Mul(invInertiaScale0, dotDelAngVel0)); const Vec4V resp1 = V4MulAdd(mass1, dotClinVel1, V4Mul(invInertiaScale1, dotDelAngVel1)); const Vec4V response = V4Add(resp0, resp1); const Vec4V recipResponse = V4Sel(V4IsGrtr(response, V4Zero()), V4Recip(response), V4Zero()); const Vec4V vMul = V4Mul(recipResponse, c.velMultiplier); const BoolV isLimitConstraint = VecI32V_IsEq(VecI32V_And(flags, limitMask), limitMask); const Vec4V minBias = V4Sel(isLimitConstraint, V4Neg(Vec4V_From_FloatV(FMax())), V4Neg(c.maxBias)); const Vec4V unclampedBias = V4MulAdd(errorChange, c.biasScale, err); const Vec4V bias = V4Clamp(unclampedBias, minBias, c.maxBias); const Vec4V constant = V4Mul(recipResponse, V4Add(bias, c.velTarget)); const Vec4V normalVel0 = V4MulAdd(clinVel0X_, linVel0T0, V4MulAdd(clinVel0Y_, linVel0T1, V4Mul(clinVel0Z_, linVel0T2))); const Vec4V normalVel1 = V4MulAdd(clinVel1X_, linVel1T0, V4MulAdd(clinVel1Y_, linVel1T1, V4Mul(clinVel1Z_, linVel1T2))); const Vec4V angVel0 = V4MulAdd(delAngVel0X, angState0T0, V4MulAdd(delAngVel0Y, angState0T1, V4Mul(delAngVel0Z, angState0T2))); const Vec4V angVel1 = V4MulAdd(delAngVel1X, angState1T0, V4MulAdd(delAngVel1Y, angState1T1, V4Mul(delAngVel1Z, angState1T2))); const Vec4V normalVel = V4Add(V4Sub(normalVel0, normalVel1), V4Sub(angVel0, angVel1)); const Vec4V unclampedForce = V4Add(c.appliedForce, V4MulAdd(vMul, normalVel, constant)); const Vec4V clampedForce = V4Clamp(unclampedForce, c.minImpulse, c.maxImpulse); const Vec4V deltaF = V4Sub(clampedForce, c.appliedForce); c.appliedForce = clampedForce; const Vec4V deltaFIM0 = V4Mul(deltaF, mass0); const Vec4V deltaFIM1 = V4Mul(deltaF, mass1); const Vec4V angDetaF0 = V4Mul(deltaF, invInertiaScale0); const Vec4V angDetaF1 = V4Mul(deltaF, invInertiaScale1); linVel0T0 = V4MulAdd(clinVel0X_, deltaFIM0, linVel0T0); linVel1T0 = V4NegMulSub(clinVel1X_, deltaFIM1, linVel1T0); angState0T0 = V4MulAdd(delAngVel0X, angDetaF0, angState0T0); angState1T0 = V4NegMulSub(delAngVel1X, angDetaF1, angState1T0); linVel0T1 = V4MulAdd(clinVel0Y_, deltaFIM0, linVel0T1); linVel1T1 = V4NegMulSub(clinVel1Y_, deltaFIM1, linVel1T1); angState0T1 = V4MulAdd(delAngVel0Y, angDetaF0, angState0T1); angState1T1 = V4NegMulSub(delAngVel1Y, angDetaF1, angState1T1); linVel0T2 = V4MulAdd(clinVel0Z_, deltaFIM0, linVel0T2); linVel1T2 = V4NegMulSub(clinVel1Z_, deltaFIM1, linVel1T2); angState0T2 = V4MulAdd(delAngVel0Z, angDetaF0, angState0T2); angState1T2 = V4NegMulSub(delAngVel1Z, angDetaF1, 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); PX_ASSERT(b00.linearVelocity.isFinite()); PX_ASSERT(b00.angularVelocity.isFinite()); PX_ASSERT(b10.linearVelocity.isFinite()); PX_ASSERT(b10.angularVelocity.isFinite()); PX_ASSERT(b20.linearVelocity.isFinite()); PX_ASSERT(b20.angularVelocity.isFinite()); PX_ASSERT(b30.linearVelocity.isFinite()); PX_ASSERT(b30.angularVelocity.isFinite()); PX_ASSERT(b01.linearVelocity.isFinite()); PX_ASSERT(b01.angularVelocity.isFinite()); PX_ASSERT(b11.linearVelocity.isFinite()); PX_ASSERT(b11.angularVelocity.isFinite()); PX_ASSERT(b21.linearVelocity.isFinite()); PX_ASSERT(b21.angularVelocity.isFinite()); PX_ASSERT(b31.linearVelocity.isFinite()); PX_ASSERT(b31.angularVelocity.isFinite()); // Write back V4StoreA(linVel00, &b00.linearVelocity.x); V4StoreA(angState00, &b00.angularVelocity.x); V4StoreA(linVel10, &b10.linearVelocity.x); V4StoreA(angState10, &b10.angularVelocity.x); V4StoreA(linVel20, &b20.linearVelocity.x); V4StoreA(angState20, &b20.angularVelocity.x); V4StoreA(linVel30, &b30.linearVelocity.x); V4StoreA(angState30, &b30.angularVelocity.x); V4StoreA(linVel01, &b01.linearVelocity.x); V4StoreA(angState01, &b01.angularVelocity.x); V4StoreA(linVel11, &b11.linearVelocity.x); V4StoreA(angState11, &b11.angularVelocity.x); V4StoreA(linVel21, &b21.linearVelocity.x); V4StoreA(angState21, &b21.angularVelocity.x); V4StoreA(linVel31, &b31.linearVelocity.x); V4StoreA(angState31, &b31.angularVelocity.x); PX_ASSERT(b00.linearVelocity.isFinite()); PX_ASSERT(b00.angularVelocity.isFinite()); PX_ASSERT(b10.linearVelocity.isFinite()); PX_ASSERT(b10.angularVelocity.isFinite()); PX_ASSERT(b20.linearVelocity.isFinite()); PX_ASSERT(b20.angularVelocity.isFinite()); PX_ASSERT(b30.linearVelocity.isFinite()); PX_ASSERT(b30.angularVelocity.isFinite()); PX_ASSERT(b01.linearVelocity.isFinite()); PX_ASSERT(b01.angularVelocity.isFinite()); PX_ASSERT(b11.linearVelocity.isFinite()); PX_ASSERT(b11.angularVelocity.isFinite()); PX_ASSERT(b21.linearVelocity.isFinite()); PX_ASSERT(b21.angularVelocity.isFinite()); PX_ASSERT(b31.linearVelocity.isFinite()); PX_ASSERT(b31.angularVelocity.isFinite()); } void solve1D4(DY_TGS_SOLVE_METHOD_PARAMS) { PX_UNUSED(minPenetration); PX_UNUSED(cache); solve1DStep4(desc + hdr.startIndex, txInertias, elapsedTime); } void writeBack1D4(DY_TGS_WRITEBACK_METHOD_PARAMS) { PX_UNUSED(cache); ConstraintWriteback* writeback0 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex].writeBack); ConstraintWriteback* writeback1 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 1].writeBack); ConstraintWriteback* writeback2 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 2].writeBack); ConstraintWriteback* writeback3 = reinterpret_cast<ConstraintWriteback*>(desc[hdr.startIndex + 3].writeBack); if (writeback0 || writeback1 || writeback2 || writeback3) { SolverConstraint1DHeaderStep4* header = reinterpret_cast<SolverConstraint1DHeaderStep4*>(desc[hdr.startIndex].constraint); SolverConstraint1DStep4* base = reinterpret_cast<SolverConstraint1DStep4*>(desc[hdr.startIndex].constraint + sizeof(SolverConstraint1DHeaderStep4)); 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 SolverConstraint1DStep4* c = 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->lin0[0], appliedForce, linX); linY = V4MulAdd(c->lin0[1], appliedForce, linY); linZ = V4MulAdd(c->lin0[2], appliedForce, linZ); angX = V4MulAdd(c->ang0[0], appliedForce, angX); angY = V4MulAdd(c->ang0[1], appliedForce, angY); angZ = V4MulAdd(c->ang0[2], appliedForce, angZ); base++; } //We need to do the cross product now angX = V4Sub(angX, V4NegMulSub(header->body0WorkOffset[0], linY, V4Mul(header->body0WorkOffset[1], linZ))); angY = V4Sub(angY, V4NegMulSub(header->body0WorkOffset[1], linZ, V4Mul(header->body0WorkOffset[2], linX))); angZ = V4Sub(angZ, V4NegMulSub(header->body0WorkOffset[2], linX, V4Mul(header->body0WorkOffset[0], 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->breakable[0] ? 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->breakable[1] ? 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->breakable[2] ? 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->breakable[3] ? PxU32(iBroken[3] != 0) : 0; } } } static void concludeContact4_Block(const PxSolverConstraintDesc* PX_RESTRICT desc) { PX_UNUSED(desc); //const PxU8* PX_RESTRICT last = desc[0].constraint + getConstraintLength(desc[0]); ////hopefully pointer aliasing doesn't bite. //PxU8* PX_RESTRICT currPtr = desc[0].constraint; //const Vec4V zero = V4Zero(); ////const PxU8 type = *desc[0].constraint; //const PxU32 contactSize = sizeof(SolverContactPointStepBlock); //const PxU32 frictionSize = sizeof(SolverContactFrictionStepBlock); //while ((currPtr < last)) //{ // SolverContactHeaderStepBlock* PX_RESTRICT hdr = reinterpret_cast<SolverContactHeaderStepBlock*>(currPtr); // currPtr = reinterpret_cast<PxU8*>(hdr + 1); // const PxU32 numNormalConstr = hdr->numNormalConstr; // const PxU32 numFrictionConstr = hdr->numFrictionConstr; // //Applied forces // currPtr += sizeof(Vec4V)*numNormalConstr; // //SolverContactPointStepBlock* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointStepBlock*>(currPtr); // currPtr += (numNormalConstr * contactSize); // bool hasMaxImpulse = (hdr->flag & SolverContactHeader4::eHAS_MAX_IMPULSE) != 0; // if (hasMaxImpulse) // currPtr += sizeof(Vec4V) * numNormalConstr; // currPtr += sizeof(Vec4V)*numFrictionConstr; // SolverContactFrictionStepBlock* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionStepBlock*>(currPtr); // currPtr += (numFrictionConstr * frictionSize); // /*for (PxU32 i = 0; i<numNormalConstr; i++) // { // contacts[i].biasCoefficient = V4Sel(V4IsGrtr(contacts[i].separation, zero), contacts[i].biasCoefficient, zero); // }*/ // for (PxU32 i = 0; i<numFrictionConstr; i++) // { // frictions[i].biasCoefficient = zero; // } //} } static void conclude1DStep4(const PxSolverConstraintDesc* PX_RESTRICT desc) { PxU8* PX_RESTRICT bPtr = desc->constraint; if (bPtr == NULL) return; const SolverConstraint1DHeaderStep4* PX_RESTRICT header = reinterpret_cast<const SolverConstraint1DHeaderStep4*>(bPtr); SolverConstraint1DStep4* PX_RESTRICT base = reinterpret_cast<SolverConstraint1DStep4*>(bPtr + sizeof(SolverConstraint1DHeaderStep4)); const VecI32V mask = I4Load(DY_SC_FLAG_KEEP_BIAS); const Vec4V zero = V4Zero(); const PxU32 count = header->count; for (PxU32 i = 0; i<count; ++i, base++) { PxPrefetchLine(base + 1); SolverConstraint1DStep4& c = *base; const VecI32V flags = I4LoadA(reinterpret_cast<PxI32*>(c.flags)); const BoolV keepBias = VecI32V_IsEq(VecI32V_And(flags, mask), mask); c.biasScale = V4Sel(keepBias, c.biasScale, zero); c.error = V4Sel(keepBias, c.error, zero); } } void solveConcludeContact4(DY_TGS_CONCLUDE_METHOD_PARAMS) { PX_UNUSED(txInertias); PX_UNUSED(cache); solveContact4_Block(desc + hdr.startIndex, true, -PX_MAX_F32, elapsedTime); concludeContact4_Block(desc + hdr.startIndex); } void solveConclude1D4(DY_TGS_CONCLUDE_METHOD_PARAMS) { PX_UNUSED(cache); solve1DStep4(desc + hdr.startIndex, txInertias, elapsedTime); conclude1DStep4(desc + hdr.startIndex); } } }
156,992
C++
43.024958
185
0.743751
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContactPF4.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_CONTACT_PF_4_H #define DY_SOLVER_CONTACT_PF_4_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "foundation/PxVecMath.h" namespace physx { using namespace aos; namespace Sc { class ShapeInteraction; } namespace Dy { struct SolverContactCoulombHeader4 { PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU16 frictionOffset; PxU8 numNormalConstr0, numNormalConstr1, numNormalConstr2, numNormalConstr3; PxU8 flags[4]; PxU32 pad; //16 Vec4V restitution; //32 Vec4V normalX; //48 Vec4V normalY; //64 Vec4V normalZ; //80 Vec4V invMassADom; //96 Vec4V invMassBDom; //112 Vec4V angD0; //128 Vec4V angD1; //144 Sc::ShapeInteraction* shapeInteraction[4]; //160 or 176 }; #if !PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader4) == 160); #else PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader4) == 176); #endif struct SolverContact4Base { Vec4V raXnX; Vec4V raXnY; Vec4V raXnZ; Vec4V appliedForce; Vec4V velMultiplier; Vec4V targetVelocity; Vec4V scaledBias; Vec4V maxImpulse; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContact4Base) == 128); struct SolverContact4Dynamic : public SolverContact4Base { Vec4V rbXnX; Vec4V rbXnY; Vec4V rbXnZ; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContact4Dynamic) == 176); struct SolverFrictionHeader4 { PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU8 numFrictionConstr; PxU8 numNormalConstr0; PxU8 numNormalConstr1; PxU8 numNormalConstr2; PxU8 numNormalConstr3; PxU8 numFrictionConstr0; PxU8 numFrictionConstr1; PxU8 numFrictionConstr2; PxU8 numFrictionConstr3; PxU8 pad0; PxU32 frictionPerContact; Vec4V staticFriction; Vec4V invMassADom; Vec4V invMassBDom; Vec4V angD0; Vec4V angD1; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionHeader4) == 96); struct SolverFriction4Base { Vec4V normalX; Vec4V normalY; Vec4V normalZ; Vec4V raXnX; Vec4V raXnY; Vec4V raXnZ; Vec4V appliedForce; Vec4V velMultiplier; Vec4V targetVelocity; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverFriction4Base) == 144); struct SolverFriction4Dynamic : public SolverFriction4Base { Vec4V rbXnX; Vec4V rbXnY; Vec4V rbXnZ; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverFriction4Dynamic) == 192); } } #endif
4,133
C
26.019608
93
0.760707
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThresholdTable.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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/PxHash.h" #include "foundation/PxAllocator.h" #include "DyThresholdTable.h" #include "foundation/PxUtilities.h" namespace physx { namespace Dy { bool ThresholdTable::check(const ThresholdStream& stream, const PxU32 nodeIndexA, const PxU32 nodeIndexB, PxReal dt) { PxU32* PX_RESTRICT hashes = mHash; PxU32* PX_RESTRICT nextIndices = mNexts; Pair* PX_RESTRICT pairs = mPairs; /*const PxsRigidBody* b0 = PxMin(body0, body1); const PxsRigidBody* b1 = PxMax(body0, body1);*/ const PxU32 nA = PxMin(nodeIndexA, nodeIndexB); const PxU32 nB = PxMax(nodeIndexA, nodeIndexB); PxU32 hashKey = computeHashKey(nodeIndexA, nodeIndexB, mHashSize); PxU32 pairIndex = hashes[hashKey]; while(NO_INDEX != pairIndex) { Pair& pair = pairs[pairIndex]; const PxU32 thresholdStreamIndex = pair.thresholdStreamIndex; PX_ASSERT(thresholdStreamIndex < stream.size()); const ThresholdStreamElement& otherElement = stream[thresholdStreamIndex]; if(otherElement.nodeIndexA.index()==nA && otherElement.nodeIndexB.index()==nB) return (pair.accumulatedForce > (otherElement.threshold * dt)); pairIndex = nextIndices[pairIndex]; } return false; } } }
2,951
C++
42.411764
118
0.749238
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep4PF.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DySolverContactPF4.h" #include "PxsMaterialManager.h" #include "DyContactPrepShared.h" using namespace physx::Gu; using namespace physx::aos; namespace physx { namespace Dy { SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, PxFrictionType::Enum frictionType); static bool setupFinalizeSolverConstraintsCoulomb4(PxSolverContactDesc* PX_RESTRICT descs, PxU8* PX_RESTRICT workspace, const PxReal invDtF32, PxReal bounceThresholdF32, CorrelationBuffer& c, const PxU32 numFrictionPerPoint, const PxU32 numContactPoints4, const PxU32 /*solverConstraintByteSize*/, const aos::Vec4VArg invMassScale0, const aos::Vec4VArg invInertiaScale0, const aos::Vec4VArg invMassScale1, const aos::Vec4VArg invInertiaScale1) { //KS - final step. Create the constraints in the place we pre-allocated... 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 bTrue = BTTTT(); 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) }; //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) const bool isDynamic = ((descs[0].bodyState1 | descs[1].bodyState1 | descs[2].bodyState1 | descs[3].bodyState1) & PxSolverContactDesc::eDYNAMIC_BODY) != 0; const PxU32 constraintSize = isDynamic ? sizeof(SolverContact4Dynamic) : sizeof(SolverContact4Base); const PxU32 frictionSize = isDynamic ? sizeof(SolverFriction4Dynamic) : sizeof(SolverFriction4Base); 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(V4Merge(FLoad(descs[0].data0->penBiasClamp), FLoad(descs[1].data0->penBiasClamp), FLoad(descs[2].data0->penBiasClamp), FLoad(descs[3].data0->penBiasClamp)), V4Merge(FLoad(descs[0].data1->penBiasClamp), FLoad(descs[1].data1->penBiasClamp), FLoad(descs[2].data1->penBiasClamp), FLoad(descs[3].data1->penBiasClamp))); const Vec4V restDistance = V4Merge(FLoad(descs[0].restDistance), FLoad(descs[1].restDistance), FLoad(descs[2].restDistance), FLoad(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 invMass0 = V4Merge(FLoad(descs[0].data0->invMass), FLoad(descs[1].data0->invMass), FLoad(descs[2].data0->invMass), FLoad(descs[3].data0->invMass)); const Vec4V invMass1 = V4Merge(FLoad(descs[0].data1->invMass), FLoad(descs[1].data1->invMass), FLoad(descs[2].data1->invMass), FLoad(descs[3].data1->invMass)); const Vec4V invMass0_dom0fV = V4Mul(dom0, invMass0); const Vec4V invMass1_dom1fV = V4Mul(dom1, invMass1); Vec4V invInertia00X = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column0)); Vec4V invInertia00Y = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column1)); Vec4V invInertia00Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data0->sqrtInvInertia.column2)); Vec4V invInertia10X = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column0)); Vec4V invInertia10Y = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column1)); Vec4V invInertia10Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data0->sqrtInvInertia.column2)); Vec4V invInertia20X = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column0)); Vec4V invInertia20Y = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column1)); Vec4V invInertia20Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data0->sqrtInvInertia.column2)); Vec4V invInertia30X = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column0)); Vec4V invInertia30Y = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column1)); Vec4V invInertia30Z = Vec4V_From_Vec3V(V3LoadU(descs[3].data0->sqrtInvInertia.column2)); Vec4V invInertia01X = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column0)); Vec4V invInertia01Y = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column1)); Vec4V invInertia01Z = Vec4V_From_Vec3V(V3LoadU(descs[0].data1->sqrtInvInertia.column2)); Vec4V invInertia11X = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column0)); Vec4V invInertia11Y = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column1)); Vec4V invInertia11Z = Vec4V_From_Vec3V(V3LoadU(descs[1].data1->sqrtInvInertia.column2)); Vec4V invInertia21X = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column0)); Vec4V invInertia21Y = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column1)); Vec4V invInertia21Z = Vec4V_From_Vec3V(V3LoadU(descs[2].data1->sqrtInvInertia.column2)); Vec4V invInertia31X = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column0)); Vec4V invInertia31Y = Vec4V_From_Vec3V(V3LoadU(descs[3].data1->sqrtInvInertia.column1)); 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 p8 = FLoad(0.8f); //const Vec4V p84 = V4Splat(p8); const Vec4V p1 = V4Splat(FLoad(0.1f)); const Vec4V bounceThreshold = V4Splat(FLoad(bounceThresholdF32)); const Vec4V orthoThreshold = V4Splat(FLoad(0.70710678f)); 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); PxPrefetchLine(c.contactID); PxPrefetchLine(c.contactID, 128); PxU32 frictionIndex0 = 0, frictionIndex1 = 0, frictionIndex2 = 0, frictionIndex3 = 0; PxU32 maxPatches = PxMax(descs[0].numFrictionPatches, PxMax(descs[1].numFrictionPatches, PxMax(descs[2].numFrictionPatches, descs[3].numFrictionPatches))); PxU32 maxContacts = numContactPoints4; //This is the address at which the first friction patch exists PxU8* ptr2 = ptr + ((sizeof(SolverContactCoulombHeader4) * maxPatches) + constraintSize * maxContacts); //PxU32 contactId = 0; for(PxU32 i=0;i<maxPatches;i++) { bool hasFinished[4]; 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 clampedFric0 = clampedContacts0 * numFrictionPerPoint; const PxU32 clampedFric1 = clampedContacts1 * numFrictionPerPoint; const PxU32 clampedFric2 = clampedContacts2 * numFrictionPerPoint; const PxU32 clampedFric3 = clampedContacts3 * numFrictionPerPoint; const PxU32 numContacts = PxMax(clampedContacts0, PxMax(clampedContacts1, PxMax(clampedContacts2, clampedContacts3))); const PxU32 numFrictions = PxMax(clampedFric0, PxMax(clampedFric1, PxMax(clampedFric2, clampedFric3))); 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 = V4Merge(FLoad(contactBase0->restitution), FLoad(contactBase1->restitution), FLoad(contactBase2->restitution), FLoad(contactBase3->restitution)); const Vec4V staticFriction = V4Merge(FLoad(contactBase0->staticFriction), FLoad(contactBase1->staticFriction), FLoad(contactBase2->staticFriction), FLoad(contactBase3->staticFriction)); SolverContactCoulombHeader4* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader4*>(ptr); header->frictionOffset = PxU16(ptr2 - ptr); ptr += sizeof(SolverContactCoulombHeader4); SolverFrictionHeader4* PX_RESTRICT fricHeader = reinterpret_cast<SolverFrictionHeader4*>(ptr2); ptr2 += sizeof(SolverFrictionHeader4) + sizeof(Vec4V) * numContacts; header->numNormalConstr0 = PxTo8(clampedContacts0); header->numNormalConstr1 = PxTo8(clampedContacts1); header->numNormalConstr2 = PxTo8(clampedContacts2); header->numNormalConstr3 = PxTo8(clampedContacts3); header->numNormalConstr = PxTo8(numContacts); header->invMassADom = invMass0_dom0fV; header->invMassBDom = invMass1_dom1fV; header->angD0 = angDom0; header->angD1 = angDom1; header->restitution = restitution; header->flags[0] = flags[0]; header->flags[1] = flags[1]; header->flags[2] = flags[2]; header->flags[3] = flags[3]; header->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_RB_CONTACT : DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT); header->shapeInteraction[0] = getInteraction(descs[0]); header->shapeInteraction[1] = getInteraction(descs[1]); header->shapeInteraction[2] = getInteraction(descs[2]); header->shapeInteraction[3] = getInteraction(descs[3]); fricHeader->invMassADom = invMass0_dom0fV; fricHeader->invMassBDom = invMass1_dom1fV; fricHeader->angD0 = angDom0; fricHeader->angD1 = angDom1; fricHeader->numFrictionConstr0 = PxTo8(clampedFric0); fricHeader->numFrictionConstr1 = PxTo8(clampedFric1); fricHeader->numFrictionConstr2 = PxTo8(clampedFric2); fricHeader->numFrictionConstr3 = PxTo8(clampedFric3); fricHeader->numNormalConstr = PxTo8(numContacts); fricHeader->numNormalConstr0 = PxTo8(clampedContacts0); fricHeader->numNormalConstr1 = PxTo8(clampedContacts1); fricHeader->numNormalConstr2 = PxTo8(clampedContacts2); fricHeader->numNormalConstr3 = PxTo8(clampedContacts3); fricHeader->type = PxTo8(isDynamic ? DY_SC_TYPE_BLOCK_FRICTION : DY_SC_TYPE_BLOCK_STATIC_FRICTION); fricHeader->staticFriction = staticFriction; fricHeader->frictionPerContact = PxU32(numFrictionPerPoint == 2 ? 1 : 0); fricHeader->numFrictionConstr = PxTo8(numFrictions); 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); header->normalX = normalX; header->normalY = normalY; header->normalZ = normalZ; const Vec4V normalLenSq = V4MulAdd(normalZ, normalZ, V4MulAdd(normalY, normalY, V4Mul(normalX, normalX))); const Vec4V linNorVel0 = V4MulAdd(normalZ, linVelT20, V4MulAdd(normalY, linVelT10, V4Mul(normalX, linVelT00))); const Vec4V linNorVel1 = V4MulAdd(normalZ, linVelT21, V4MulAdd(normalY, linVelT11, V4Mul(normalX, linVelT01))); const Vec4V invMassNorLenSq0 = V4Mul(invMass0_dom0fV, normalLenSq); const Vec4V invMassNorLenSq1 = V4Mul(invMass1_dom1fV, normalLenSq); //Calculate friction directions 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, dotNormalVrel, vrelX); const Vec4V vrelSubNorVelY = V4NegMulSub(normalY, dotNormalVrel, vrelY); const Vec4V vrelSubNorVelZ = V4NegMulSub(normalZ, dotNormalVrel, 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(t0X, t0X, V4MulAdd(t0Y, t0Y, V4Mul(t0Z, t0Z)))); t0X = V4Mul(t0X, recipLen); t0Y = V4Mul(t0Y, recipLen); t0Z = V4Mul(t0Z, recipLen); const Vec4V t1X = V4NegMulSub(normalZ, t0Y, V4Mul(normalY, t0Z)); const Vec4V t1Y = V4NegMulSub(normalX, t0Z, V4Mul(normalZ, t0X)); const Vec4V t1Z = V4NegMulSub(normalY, t0X, V4Mul(normalX, t0Y)); const Vec4V tFallbackX[2] = {t0X, t1X}; const Vec4V tFallbackY[2] = {t0Y, t1Y}; const Vec4V tFallbackZ[2] = {t0Z, t1Z}; //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; iter0.nextContact(patch0, contact0); iter1.nextContact(patch1, contact1); iter2.nextContact(patch2, contact2); 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); PxU32 fricIndex = 0; while(finished != 0xf) { finished = newFinished; ++contactCount; PxPrefetchLine(p, 384); PxPrefetchLine(p, 512); PxPrefetchLine(p, 640); SolverContact4Base* PX_RESTRICT solverContact = reinterpret_cast<SolverContact4Base*>(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); Vec4V targetVel0 = V4LoadA(&con0.targetVel.x); Vec4V targetVel1 = V4LoadA(&con1.targetVel.x); Vec4V targetVel2 = V4LoadA(&con2.targetVel.x); Vec4V targetVel3 = V4LoadA(&con3.targetVel.x); Vec4V targetVelX, targetVelY, targetVelZ; PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ); Vec4V raX = V4Sub(pointX, bodyFrame0pX); Vec4V raY = V4Sub(pointY, bodyFrame0pY); Vec4V raZ = V4Sub(pointZ, bodyFrame0pZ); Vec4V rbX = V4Sub(pointX, bodyFrame1pX); Vec4V rbY = V4Sub(pointY, bodyFrame1pY); 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); { const Vec4V separation = V4Merge(FLoad(con0.separation), FLoad(con1.separation), FLoad(con2.separation), FLoad(con3.separation)); const Vec4V maxImpulse = V4Merge(FLoad(con0.maxImpulse), FLoad(con1.maxImpulse), FLoad(con2.maxImpulse), FLoad(con3.maxImpulse)); const Vec4V cTargetVel = V4MulAdd(normalX, targetVelX, V4MulAdd(normalY, targetVelY, V4Mul(normalZ, targetVelZ))); //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); const Vec4V raXnX = V4NegMulSub(raZ, normalY, V4Mul(raY, normalZ)); const Vec4V raXnY = V4NegMulSub(raX, normalZ, V4Mul(raZ, normalX)); const Vec4V raXnZ = V4NegMulSub(raY, normalX, V4Mul(raX, normalY)); const Vec4V v0a0 = V4Mul(invInertia0X0, raXnX); const Vec4V v0a1 = V4Mul(invInertia0X1, raXnX); const Vec4V v0a2 = V4Mul(invInertia0X2, raXnX); const Vec4V v0PlusV1a0 = V4MulAdd(invInertia0Y0, raXnY, v0a0); const Vec4V v0PlusV1a1 = V4MulAdd(invInertia0Y1, raXnY, v0a1); const Vec4V v0PlusV1a2 = V4MulAdd(invInertia0Y2, raXnY, v0a2); const Vec4V delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, v0PlusV1a0); const Vec4V delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, v0PlusV1a1); const Vec4V delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, v0PlusV1a2); const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X))); const Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00))); Vec4V unitResponse = V4Add(invMassNorLenSq0, dotDelAngVel0); Vec4V vrel = V4Add(linNorVel0, dotRaXnAngVel0); //The dynamic-only parts - need to if-statement these up. A branch here shouldn't cost us too much if(isDynamic) { SolverContact4Dynamic* PX_RESTRICT dynamicContact = static_cast<SolverContact4Dynamic*>(solverContact); const Vec4V rbXnX = V4NegMulSub(rbZ, normalY, V4Mul(rbY, normalZ)); const Vec4V rbXnY = V4NegMulSub(rbX, normalZ, V4Mul(rbZ, normalX)); const Vec4V rbXnZ = V4NegMulSub(rbY, normalX, V4Mul(rbX, normalY)); const Vec4V v0b0 = V4Mul(invInertia1X0, rbXnX); const Vec4V v0b1 = V4Mul(invInertia1X1, rbXnX); const Vec4V v0b2 = V4Mul(invInertia1X2, rbXnX); const Vec4V v0PlusV1b0 = V4MulAdd(invInertia1Y0, rbXnY, v0b0); const Vec4V v0PlusV1b1 = V4MulAdd(invInertia1Y1, rbXnY, v0b1); const Vec4V v0PlusV1b2 = V4MulAdd(invInertia1Y2, rbXnY, v0b2); const Vec4V delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, v0PlusV1b0); const Vec4V delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, v0PlusV1b1); const Vec4V delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, v0PlusV1b2); //V3Dot(raXn, delAngVel0) const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X))); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01))); const Vec4V resp1 = V4Add(dotDelAngVel1, invMassNorLenSq1); unitResponse = V4Add(unitResponse, resp1); const Vec4V vrel2 = V4Add(linNorVel1, dotRbXnAngVel1); vrel = V4Sub(vrel, vrel2); //These are for dynamic-only contacts. dynamicContact->rbXnX = delAngVel1X; dynamicContact->rbXnY = delAngVel1Y; dynamicContact->rbXnZ = delAngVel1Z; } const Vec4V velMultiplier = V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero); const Vec4V penetration = V4Sub(separation, restDistance); const Vec4V penInvDtp8 = V4Max(maxPenBias, V4Scale(penetration, invDtp8)); Vec4V scaledBias = V4Mul(velMultiplier, penInvDtp8); const Vec4V penetrationInvDt = V4Scale(penetration, invDt); const BoolV isGreater2 = BAnd(BAnd(V4IsGrtr(restitution, zero), V4IsGrtr(bounceThreshold, vrel)), V4IsGrtr(V4Neg(vrel), penetrationInvDt)); const BoolV ccdSeparationCondition = V4IsGrtrOrEq(ccdMaxSeparation, penetration); scaledBias = V4Sel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias); const Vec4V sumVRel(vrel); const Vec4V targetVelocity = V4Sub(V4Add(V4Sel(isGreater2, V4Mul(V4Neg(sumVRel), restitution), zero), cTargetVel), vrel); //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->appliedForce = zero; solverContact->scaledBias = V4Sel(bFinished, zero, scaledBias); solverContact->targetVelocity = targetVelocity; solverContact->maxImpulse = maxImpulse; } //PxU32 conId = contactId++; /*Vec4V targetVel0 = V4LoadA(&con0.targetVel.x); Vec4V targetVel1 = V4LoadA(&con1.targetVel.x); Vec4V targetVel2 = V4LoadA(&con2.targetVel.x); Vec4V targetVel3 = V4LoadA(&con3.targetVel.x); Vec4V targetVelX, targetVelY, targetVelZ; PX_TRANSPOSE_44_34(targetVel0, targetVel1, targetVel2, targetVel3, targetVelX, targetVelY, targetVelZ);*/ for(PxU32 a = 0; a < numFrictionPerPoint; ++a) { SolverFriction4Base* PX_RESTRICT friction = reinterpret_cast<SolverFriction4Base*>(ptr2); ptr2 += frictionSize; const Vec4V tX = tFallbackX[fricIndex]; const Vec4V tY = tFallbackY[fricIndex]; const Vec4V tZ = tFallbackZ[fricIndex]; fricIndex = 1 - fricIndex; const Vec4V raXnX = V4NegMulSub(raZ, tY, V4Mul(raY, tZ)); const Vec4V raXnY = V4NegMulSub(raX, tZ, V4Mul(raZ, tX)); const Vec4V raXnZ = V4NegMulSub(raY, tX, V4Mul(raX, tY)); const Vec4V v0a0 = V4Mul(invInertia0X0, raXnX); const Vec4V v0a1 = V4Mul(invInertia0X1, raXnX); const Vec4V v0a2 = V4Mul(invInertia0X2, raXnX); const Vec4V v0PlusV1a0 = V4MulAdd(invInertia0Y0, raXnY, v0a0); const Vec4V v0PlusV1a1 = V4MulAdd(invInertia0Y1, raXnY, v0a1); const Vec4V v0PlusV1a2 = V4MulAdd(invInertia0Y2, raXnY, v0a2); const Vec4V delAngVel0X = V4MulAdd(invInertia0Z0, raXnZ, v0PlusV1a0); const Vec4V delAngVel0Y = V4MulAdd(invInertia0Z1, raXnZ, v0PlusV1a1); const Vec4V delAngVel0Z = V4MulAdd(invInertia0Z2, raXnZ, v0PlusV1a2); const Vec4V dotDelAngVel0 = V4MulAdd(delAngVel0Z, delAngVel0Z, V4MulAdd(delAngVel0Y, delAngVel0Y, V4Mul(delAngVel0X, delAngVel0X))); const Vec4V norVel0 = V4MulAdd(tX, linVelT00, V4MulAdd(tY, linVelT10, V4Mul(tZ, linVelT20))); const Vec4V dotRaXnAngVel0 = V4MulAdd(raXnZ, angVelT20, V4MulAdd(raXnY, angVelT10, V4Mul(raXnX, angVelT00))); Vec4V vrel = V4Add(norVel0, dotRaXnAngVel0); Vec4V unitResponse = V4Add(invMass0_dom0fV, dotDelAngVel0); if(isDynamic) { SolverFriction4Dynamic* PX_RESTRICT dFric = static_cast<SolverFriction4Dynamic*>(friction); const Vec4V rbXnX = V4NegMulSub(rbZ, tY, V4Mul(rbY, tZ)); const Vec4V rbXnY = V4NegMulSub(rbX, tZ, V4Mul(rbZ, tX)); const Vec4V rbXnZ = V4NegMulSub(rbY, tX, V4Mul(rbX, tY)); const Vec4V v0b0 = V4Mul(invInertia1X0, rbXnX); const Vec4V v0b1 = V4Mul(invInertia1X1, rbXnX); const Vec4V v0b2 = V4Mul(invInertia1X2, rbXnX); const Vec4V v0PlusV1b0 = V4MulAdd(invInertia1Y0, rbXnY, v0b0); const Vec4V v0PlusV1b1 = V4MulAdd(invInertia1Y1, rbXnY, v0b1); const Vec4V v0PlusV1b2 = V4MulAdd(invInertia1Y2, rbXnY, v0b2); const Vec4V delAngVel1X = V4MulAdd(invInertia1Z0, rbXnZ, v0PlusV1b0); const Vec4V delAngVel1Y = V4MulAdd(invInertia1Z1, rbXnZ, v0PlusV1b1); const Vec4V delAngVel1Z = V4MulAdd(invInertia1Z2, rbXnZ, v0PlusV1b2); const Vec4V dotDelAngVel1 = V4MulAdd(delAngVel1Z, delAngVel1Z, V4MulAdd(delAngVel1Y, delAngVel1Y, V4Mul(delAngVel1X, delAngVel1X))); const Vec4V norVel1 = V4MulAdd(tX, linVelT01, V4MulAdd(tY, linVelT11, V4Mul(tZ, linVelT21))); const Vec4V dotRbXnAngVel1 = V4MulAdd(rbXnZ, angVelT21, V4MulAdd(rbXnY, angVelT11, V4Mul(rbXnX, angVelT01))); vrel = V4Sub(vrel, V4Add(norVel1, dotRbXnAngVel1)); const Vec4V resp1 = V4Add(dotDelAngVel1, invMassNorLenSq1); unitResponse = V4Add(unitResponse, resp1); dFric->rbXnX = delAngVel1X; dFric->rbXnY = delAngVel1Y; dFric->rbXnZ = delAngVel1Z; } const Vec4V velMultiplier = V4Neg(V4Sel(V4IsGrtr(unitResponse, zero), V4Recip(unitResponse), zero)); friction->appliedForce = zero; friction->raXnX = delAngVel0X; friction->raXnY = delAngVel0Y; friction->raXnZ = delAngVel0Z; friction->velMultiplier = velMultiplier; friction->targetVelocity = V4Sub(V4MulAdd(targetVelZ, tZ, V4MulAdd(targetVelY, tY, V4Mul(targetVelX, tX))), vrel); friction->normalX = tX; friction->normalY = tY; friction->normalZ = tZ; } } // 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; } return true; } //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 computeBlockStreamByteSizesCoulomb4(PxSolverContactDesc* descs, ThreadContext& threadContext, const CorrelationBuffer& c, const PxU32 numFrictionPerPoint, PxU32& _solverConstraintByteSize, PxU32* _axisConstraintCount, PxU32& _numContactPoints4) { PX_ASSERT(0 == _solverConstraintByteSize); PX_UNUSED(threadContext); PxU32 maxPatches = 0; PxU32 maxContactCount[CorrelationBuffer::MAX_FRICTION_PATCHES]; PxU32 maxFrictionCount[CorrelationBuffer::MAX_FRICTION_PATCHES]; PxMemZero(maxContactCount, sizeof(maxContactCount)); PxMemZero(maxFrictionCount, sizeof(maxFrictionCount)); for(PxU32 a = 0; a < 4; ++a) { PxU32 axisConstraintCount = 0; 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; //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 = c.frictionPatches[ind].numConstraints; const PxU32 fricCount = c.frictionPatchContactCounts[ind] * numFrictionPerPoint; maxFrictionCount[i] = PxMax(fricCount, maxFrictionCount[i]); axisConstraintCount += fricCount; } } } maxPatches = PxMax(descs[a].numFrictionPatches, maxPatches); _axisConstraintCount[a] = axisConstraintCount; } PxU32 totalContacts = 0, totalFriction = 0; for(PxU32 a = 0; a < maxPatches; ++a) { totalContacts += maxContactCount[a]; totalFriction += maxFrictionCount[a]; } _numContactPoints4 = totalContacts; //OK, we have a given number of friction patches, contact points and friction constraints so we can calculate how much memory we need const bool isStatic = (((descs[0].bodyState1 | descs[1].bodyState1 | descs[2].bodyState1 | descs[3].bodyState1) & PxSolverContactDesc::eDYNAMIC_BODY) == 0); const PxU32 headerSize = (sizeof(SolverContactCoulombHeader4) + sizeof(SolverFrictionHeader4)) * maxPatches; //Add on 1 Vec4V per contact for the applied force buffer const PxU32 constraintSize = isStatic ? ((sizeof(SolverContact4Base) + sizeof(Vec4V)) * totalContacts) + ( sizeof(SolverFriction4Base) * totalFriction) : ((sizeof(SolverContact4Dynamic) + sizeof(Vec4V)) * totalContacts) + (sizeof(SolverFriction4Dynamic) * totalFriction); _solverConstraintByteSize = ((constraintSize + headerSize + 0x0f) & ~0x0f); PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f)); } static SolverConstraintPrepState::Enum reserveBlockStreamsCoulomb4(PxSolverContactDesc* descs, ThreadContext& threadContext, const CorrelationBuffer& c, PxU8*& solverConstraint, const PxU32 numFrictionPerContactPoint, PxU32& solverConstraintByteSize, PxU32* axisConstraintCount, PxU32& numContactPoints4, PxConstraintAllocator& constraintAllocator) { PX_ASSERT(NULL == solverConstraint); PX_ASSERT(0 == solverConstraintByteSize); //From constraintBlockStream we need to reserve contact points, contact forces, and a char buffer for the solver constraint data (already have a variable for this). //From frictionPatchStream we just need to reserve a single buffer. //Compute the sizes of all the buffers. computeBlockStreamByteSizesCoulomb4( descs, threadContext, c, numFrictionPerContactPoint, solverConstraintByteSize, axisConstraintCount, numContactPoints4); //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 true if neither of the two block reservations failed. return ((0==constraintBlockByteSize || constraintBlock)) ? SolverConstraintPrepState::eSUCCESS : SolverConstraintPrepState::eOUT_OF_MEMORY; } SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb1D( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator) { return createFinalizeSolverContacts4Coulomb(outputs, threadContext, blockDescs, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eONE_DIRECTIONAL); } SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb2D( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator) { return createFinalizeSolverContacts4Coulomb(outputs, threadContext, blockDescs, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eTWO_DIRECTIONAL); } SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, PxFrictionType::Enum frictionType) { PX_UNUSED(frictionOffsetThreshold); PX_UNUSED(correlationDistance); PX_UNUSED(dtF32); for(PxU32 i = 0; i < 4; ++i) { blockDescs[i].desc->constraintLengthOver16 = 0; } PX_ASSERT(outputs[0]->nbContacts && outputs[1]->nbContacts && outputs[2]->nbContacts && outputs[3]->nbContacts); PxContactBuffer& buffer = threadContext.mContactBuffer; buffer.count = 0; PxU32 numContacts = 0; CorrelationBuffer& c = threadContext.mCorrelationBuffer; c.frictionPatchCount = 0; c.contactPatchCount = 0; PxU32 numFrictionPerPoint = PxU32(frictionType == PxFrictionType::eONE_DIRECTIONAL ? 1 : 2); PX_ALIGN(16, PxReal invMassScale0[4]); PX_ALIGN(16, PxReal invMassScale1[4]); PX_ALIGN(16, PxReal invInertiaScale0[4]); PX_ALIGN(16, PxReal invInertiaScale1[4]); for(PxU32 a = 0; a < 4; ++a) { PxSolverContactDesc& blockDesc = blockDescs[a]; PxSolverConstraintDesc& desc = *blockDesc.desc; //blockDesc.startContactIndex = numContacts; blockDesc.contacts = &buffer.contacts[numContacts]; PxPrefetchLine(desc.bodyA); PxPrefetchLine(desc.bodyB); if((numContacts + outputs[a]->nbContacts) > 64) { return SolverConstraintPrepState::eUNBATCHABLE; } bool hasMaxImpulse, hasTargetVelocity; const PxReal defaultMaxImpulse = PxMin(blockDesc.data0->maxContactImpulse, blockDesc.data1->maxContactImpulse); PxU32 contactCount = extractContacts(buffer, *outputs[a], hasMaxImpulse, hasTargetVelocity, invMassScale0[a], invMassScale1[a], invInertiaScale0[a], invInertiaScale1[a], defaultMaxImpulse); if(contactCount == 0) return SolverConstraintPrepState::eUNBATCHABLE; numContacts+=contactCount; blockDesc.numContacts = contactCount; blockDesc.hasMaxImpulse = hasMaxImpulse; blockDesc.startFrictionPatchIndex = c.frictionPatchCount; blockDesc.startContactPatchIndex = c.contactPatchCount; createContactPatches(c, blockDesc.contacts, contactCount, PXC_SAME_NORMAL); bool overflow = correlatePatches(c, blockDesc.contacts, blockDesc.bodyFrame0, blockDesc.bodyFrame1, PXC_SAME_NORMAL, blockDesc.startContactPatchIndex, blockDesc.startFrictionPatchIndex); if(overflow) return SolverConstraintPrepState::eUNBATCHABLE; blockDesc.numContactPatches = PxU16(c.contactPatchCount - blockDesc.startContactPatchIndex); blockDesc.numFrictionPatches = c.frictionPatchCount - blockDesc.startFrictionPatchIndex; invMassScale0[a] *= blockDesc.invMassScales.linear0; invMassScale1[a] *= blockDesc.invMassScales.linear1; invInertiaScale0[a] *= blockDesc.invMassScales.angular0; invInertiaScale1[a] *= blockDesc.invMassScales.angular1; } //OK, now we need to work out how much memory to allocate, allocate it and then block-create the constraints... PxU8* solverConstraint = NULL; PxU32 solverConstraintByteSize = 0; PxU32 axisConstraintCount[4]; PxU32 numContactPoints4 = 0; SolverConstraintPrepState::Enum state = reserveBlockStreamsCoulomb4(blockDescs, threadContext, c, solverConstraint, numFrictionPerPoint, solverConstraintByteSize, axisConstraintCount, numContactPoints4, constraintAllocator); if(state != SolverConstraintPrepState::eSUCCESS) return state; //OK, we allocated the memory, now let's create the constraints for(PxU32 a = 0; a < 4; ++a) { PxSolverConstraintDesc& desc = *blockDescs[a].desc; //n[a]->solverConstraintPointer = solverConstraint; desc.constraint = solverConstraint; //KS - TODO - add back in counters for axisConstraintCount somewhere... blockDescs[a].axisConstraintCount += PxTo16(axisConstraintCount[a]); desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize/16); void* writeBack = outputs[a]->contactForces; desc.writeBack = writeBack; } const Vec4V iMassScale0 = V4LoadA(invMassScale0); const Vec4V iInertiaScale0 = V4LoadA(invInertiaScale0); const Vec4V iMassScale1 = V4LoadA(invMassScale1); const Vec4V iInertiaScale1 = V4LoadA(invInertiaScale1); bool hasFriction = setupFinalizeSolverConstraintsCoulomb4(blockDescs, solverConstraint, invDtF32, bounceThresholdF32, c, numFrictionPerPoint, numContactPoints4, solverConstraintByteSize, iMassScale0, iInertiaScale0, iMassScale1, iInertiaScale1); *(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0; *(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize + 4)) = hasFriction ? 0xFFFFFFFF : 0; return SolverConstraintPrepState::eSUCCESS; } } }
44,333
C++
43.113433
175
0.750186
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneArticulation.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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/PxMathUtils.h" #include "CmConeLimitHelper.h" #include "DySolverConstraint1D.h" #include "DyFeatherstoneArticulation.h" #include "PxsRigidBody.h" #include "PxcConstraintBlockStream.h" #include "DyArticulationContactPrep.h" #include "DyDynamics.h" #include "DyArticulationPImpl.h" #include "DyFeatherstoneArticulationLink.h" #include "DyFeatherstoneArticulationJointData.h" #include "DySolverConstraint1DStep.h" #include "DyTGSDynamics.h" #include "DyConstraintPrep.h" #include "common/PxProfileZone.h" #include "PxsContactManager.h" #include "DyContactPrep.h" #include "DySolverContext.h" #include "DyTGSContactPrep.h" #include "DyArticulationCpuGpu.h" #ifndef FEATURESTONE_DEBUG #define FEATURESTONE_DEBUG 0 #endif // we encode articulation link handles in the lower bits of the pointer, so the // articulation has to be aligned, which in an aligned pool means we need to size it // appropriately namespace physx { namespace Dy { extern PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3]; ArticulationData::~ArticulationData() { PX_FREE(mLinksData); PX_FREE(mJointData); PX_FREE(mPathToRootElements); } void ArticulationData::resizeLinkData(const PxU32 linkCount) { const PxU32 oldSize = mMotionVelocities.size(); mMotionVelocities.reserve(linkCount); mMotionVelocities.forceSize_Unsafe(linkCount); mSolverLinkSpatialDeltaVels.reserve(linkCount); mSolverLinkSpatialDeltaVels.forceSize_Unsafe(linkCount); mSolverLinkSpatialImpulses.reserve(linkCount); mSolverLinkSpatialImpulses.forceSize_Unsafe(linkCount); mSolverLinkSpatialForces.reserve(linkCount); mSolverLinkSpatialForces.forceSize_Unsafe(linkCount); mMotionAccelerations.reserve(linkCount); mMotionAccelerations.forceSize_Unsafe(linkCount); mLinkIncomingJointForces.reserve(linkCount); mLinkIncomingJointForces.forceSize_Unsafe(linkCount); mMotionAccelerationsInternal.reserve(linkCount); mMotionAccelerationsInternal.forceSize_Unsafe(linkCount); mCorioliseVectors.reserve(linkCount); mCorioliseVectors.forceSize_Unsafe(linkCount); mZAForces.reserve(linkCount); mZAForces.forceSize_Unsafe(linkCount); mZAInternalForces.reserve(linkCount); mZAInternalForces.forceSize_Unsafe(linkCount); mNbStatic1DConstraints.reserve(linkCount); mNbStatic1DConstraints.forceSize_Unsafe(linkCount); mStatic1DConstraintStartIndex.reserve(linkCount); mStatic1DConstraintStartIndex.forceSize_Unsafe(linkCount); mNbStaticContactConstraints.reserve(linkCount); mNbStaticContactConstraints.forceSize_Unsafe(linkCount); mStaticContactConstraintStartIndex.reserve(linkCount); mStaticContactConstraintStartIndex.forceSize_Unsafe(linkCount); mDeltaMotionVector.reserve(linkCount); mDeltaMotionVector.forceSize_Unsafe(linkCount); mPreTransform.reserve(linkCount); mPreTransform.forceSize_Unsafe(linkCount); mResponseMatrixW.reserve(linkCount); mResponseMatrixW.forceSize_Unsafe(linkCount); mWorldSpatialArticulatedInertia.reserve(linkCount); mWorldSpatialArticulatedInertia.forceSize_Unsafe(linkCount); mWorldIsolatedSpatialArticulatedInertia.reserve(linkCount); mWorldIsolatedSpatialArticulatedInertia.forceSize_Unsafe(linkCount); mMasses.reserve(linkCount); mMasses.forceSize_Unsafe(linkCount); mInvStIs.reserve(linkCount); mInvStIs.forceSize_Unsafe(linkCount); /*mMotionMatrix.resize(linkCount); mWorldMotionMatrix.reserve(linkCount); mWorldMotionMatrix.forceSize_Unsafe(linkCount);*/ mAccumulatedPoses.reserve(linkCount); mAccumulatedPoses.forceSize_Unsafe(linkCount); mDeltaQ.reserve(linkCount); mDeltaQ.forceSize_Unsafe(linkCount); mPosIterMotionVelocities.reserve(linkCount); mPosIterMotionVelocities.forceSize_Unsafe(linkCount); mJointTransmittedForce.reserve(linkCount); mJointTransmittedForce.forceSize_Unsafe(linkCount); mRw.reserve(linkCount); mRw.forceSize_Unsafe(linkCount); //This stores how much an impulse on a given link influences the root link. //We combine this with the back-propagation of joint forces to compute the //change in velocity of a given impulse! mRootResponseMatrix.reserve(linkCount); mRootResponseMatrix.forceSize_Unsafe(linkCount); mRelativeQuat.resize(linkCount); if (oldSize < linkCount) { ArticulationLinkData* oldLinks = mLinksData; ArticulationJointCoreData* oldJoints = mJointData; mLinksData = PX_ALLOCATE(ArticulationLinkData, linkCount, "ArticulationLinkData"); mJointData = PX_ALLOCATE(ArticulationJointCoreData, linkCount, "ArticulationJointCoreData"); PxMemCopy(mLinksData, oldLinks, sizeof(ArticulationLinkData)*oldSize); PxMemCopy(mJointData, oldJoints, sizeof(ArticulationJointCoreData)*oldSize); PX_FREE(oldLinks); PX_FREE(oldJoints); const PxU32 newElems = (linkCount - oldSize); PxMemZero(mLinksData + oldSize, sizeof(ArticulationLinkData) * newElems); PxMemZero(mJointData + oldSize, sizeof(ArticulationJointCoreData) * newElems); for (PxU32 linkID = oldSize; linkID < linkCount; ++linkID) { PX_PLACEMENT_NEW(mLinksData + linkID, ArticulationLinkData)(); PX_PLACEMENT_NEW(mJointData + linkID, ArticulationJointCoreData)(); } } } void ArticulationData::resizeJointData(const PxU32 dofs) { mJointAcceleration.reserve(dofs); mJointAcceleration.forceSize_Unsafe(dofs); mJointInternalAcceleration.reserve(dofs); mJointInternalAcceleration.forceSize_Unsafe(dofs); mJointVelocity.reserve(dofs); mJointVelocity.forceSize_Unsafe(dofs); mJointNewVelocity.reserve(dofs+3); mJointNewVelocity.forceSize_Unsafe(dofs+3); mJointPosition.reserve(dofs); mJointPosition.forceSize_Unsafe(dofs); mJointForce.reserve(dofs); mJointForce.forceSize_Unsafe(dofs); mJointTargetPositions.reserve(dofs); mJointTargetPositions.forceSize_Unsafe(dofs); mJointTargetVelocities.reserve(dofs); mJointTargetVelocities.forceSize_Unsafe(dofs); mMotionMatrix.resize(dofs); mJointSpaceJacobians.resize(dofs*mLinkCount); mJointSpaceDeltaVMatrix.resize(((dofs + 3) / 4)*mLinkCount); mJointSpaceResponseMatrix.resize(dofs); //This is only an entry per-dof mPropagationAccelerator.resize(dofs); mWorldMotionMatrix.reserve(dofs); mWorldMotionMatrix.forceSize_Unsafe(dofs); mJointAxis.reserve(dofs); mJointAxis.forceSize_Unsafe(dofs); mIsW.reserve(dofs); mIsW.forceSize_Unsafe(dofs); mDeferredQstZ.reserve(dofs); mDeferredQstZ.forceSize_Unsafe(dofs); mJointConstraintForces.resizeUninitialized(dofs); qstZIc.reserve(dofs); qstZIc.forceSize_Unsafe(dofs); qstZIntIc.reserve(dofs); qstZIntIc.forceSize_Unsafe(dofs); mISInvStIS.reserve(dofs); mISInvStIS.forceSize_Unsafe(dofs); mPosIterJointVelocities.reserve(dofs); mPosIterJointVelocities.forceSize_Unsafe(dofs); PxMemZero(mJointAcceleration.begin(), sizeof(PxReal) * dofs); PxMemZero(mJointVelocity.begin(), sizeof(PxReal) * dofs); PxMemZero(mJointPosition.begin(), sizeof(PxReal) * dofs); PxMemZero(mJointForce.begin(), sizeof(PxReal) * dofs); PxMemZero(mJointTargetPositions.begin(), sizeof(PxReal) * dofs); PxMemZero(mJointTargetVelocities.begin(), sizeof(PxReal) * dofs); } ArticulationLinkData& ArticulationData::getLinkData(PxU32 index) const { PX_ASSERT(index < mLinkCount); return mLinksData[index]; } FeatherstoneArticulation::FeatherstoneArticulation(void* userData) : mUserData(userData), mContext(NULL), mUpdateSolverData(true), mMaxDepth(0), mJcalcDirty(true) { mGPUDirtyFlags = 0; } FeatherstoneArticulation::~FeatherstoneArticulation() { } void FeatherstoneArticulation::copyJointData(const ArticulationData& data, PxReal* toJointData, const PxReal* fromJointData) { const PxU32 dofCount = data.getDofs(); PxMemCopy(toJointData, fromJointData, sizeof(PxReal)*dofCount); } PxU32 FeatherstoneArticulation::computeDofs() { const PxU32 linkCount = mArticulationData.getLinkCount(); PxU32 totalDofs = 0; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = mArticulationData.getLink(linkID); ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); const PxU8 dof = jointDatum.computeJointDofs(link.inboundJoint); totalDofs += dof; } return totalDofs; } bool FeatherstoneArticulation::resize(const PxU32 linkCount) { if (mUpdateSolverData) { if (linkCount != mSolverDesc.linkCount) { mSolverDesc.acceleration = mAcceleration.begin(); mSolverDesc.articulation = this; } mUpdateSolverData = false; if (linkCount != mSolverDesc.linkCount) mArticulationData.resizeLinkData(linkCount); return true; } return false; } void FeatherstoneArticulation::getDataSizes(PxU32 /*linkCount*/, PxU32& solverDataSize, PxU32& totalSize, PxU32& scratchSize) { solverDataSize = 0; totalSize = 0; scratchSize = 0; } void FeatherstoneArticulation::setupLinks(PxU32 nbLinks, Dy::ArticulationLink* links) { //if this is needed, we need to re-allocated the link data resize(nbLinks); mSolverDesc.links = links; mSolverDesc.linkCount = PxTo8(nbLinks); mArticulationData.mLinks = links; mArticulationData.mLinkCount = PxTo8(nbLinks); mArticulationData.mFlags = mSolverDesc.core ? &mSolverDesc.core->flags : mSolverDesc.flags; // PT: PX-1399 mArticulationData.mExternalAcceleration = mSolverDesc.acceleration; mArticulationData.mArticulation = this; //allocate memory for articulation data PxU32 totalDofs = computeDofs(); const PxU32 existedTotalDofs = mArticulationData.getDofs(); if (totalDofs != existedTotalDofs) { mArticulationData.resizeJointData(totalDofs + 1); mArticulationData.setDofs(totalDofs); } } void FeatherstoneArticulation::allocatePathToRootElements(const PxU32 totalPathToRootElements) { if (mArticulationData.mNumPathToRootElements < totalPathToRootElements) { mArticulationData.mPathToRootElements = PX_ALLOCATE(PxU32, totalPathToRootElements, "PxU32"); mArticulationData.mNumPathToRootElements = totalPathToRootElements; } } void FeatherstoneArticulation::initPathToRoot() { Dy::ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); links[0].mPathToRootCount = 0; links[0].mPathToRootStartIndex = 0; PxU32 totalPathToRootCount = 1; //add on root for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { Dy::ArticulationLink& link = links[linkID]; PxU32 parent = link.parent; PxU32 pathToRootCount = 1; // add myself to the path while (parent != 0) // don't add the root { parent = links[parent].parent; pathToRootCount++; } link.mPathToRootStartIndex = totalPathToRootCount; link.mPathToRootCount = PxU16(pathToRootCount); totalPathToRootCount += pathToRootCount; } allocatePathToRootElements(totalPathToRootCount); PxU32* pathToRootElements = mArticulationData.getPathToRootElements(); pathToRootElements[0] = 0; //add on root index for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { Dy::ArticulationLink& link = links[linkID]; PxU32* pathToRoot = &pathToRootElements[link.mPathToRootStartIndex]; PxU32 numElements = link.mPathToRootCount; pathToRoot[--numElements] = linkID; PxU32 parent = links[linkID].parent; while (parent != 0) { pathToRoot[--numElements] = parent; parent = links[parent].parent; } } } void FeatherstoneArticulation::assignTendons(const PxU32 nbTendons, Dy::ArticulationSpatialTendon** tendons) { mArticulationData.mSpatialTendons = tendons; mArticulationData.mNumSpatialTendons = nbTendons; } void FeatherstoneArticulation::assignTendons(const PxU32 nbTendons, Dy::ArticulationFixedTendon** tendons) { mArticulationData.mFixedTendons = tendons; mArticulationData.mNumFixedTendons = nbTendons; } void FeatherstoneArticulation::assignSensors(const PxU32 nbSensors, Dy::ArticulationSensor** sensors, PxSpatialForce* sensorForces) { mArticulationData.mSensors = sensors; mArticulationData.mNbSensors = nbSensors; mArticulationData.mSensorForces = sensorForces; } PxU32 FeatherstoneArticulation::getDofs() const { return mArticulationData.getDofs(); } PxU32 FeatherstoneArticulation::getDof(const PxU32 linkID) { const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); return jointDatum.dof; } bool FeatherstoneArticulation::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, bool& shouldWake) { return applyCacheToDest(mArticulationData, cache, mArticulationData.getJointVelocities(), mArticulationData.getJointPositions(), mArticulationData.getJointForces(), mArticulationData.getJointTargetPositions(), mArticulationData.getJointTargetVelocities(), flag, shouldWake); } void FeatherstoneArticulation::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) { if (flag & PxArticulationCacheFlag::eVELOCITY) { copyJointData(mArticulationData, cache.jointVelocity, mArticulationData.getJointVelocities()); } if (flag & PxArticulationCacheFlag::eACCELERATION) { copyJointData(mArticulationData, cache.jointAcceleration, mArticulationData.getJointAccelerations()); } if (flag & PxArticulationCacheFlag::ePOSITION) { copyJointData(mArticulationData, cache.jointPosition, mArticulationData.getJointPositions()); } if (flag & PxArticulationCacheFlag::eFORCE) { copyJointData(mArticulationData, cache.jointForce, mArticulationData.getJointForces()); } if (flag & PxArticulationCacheFlag::eJOINT_SOLVER_FORCES) { copyJointData(mArticulationData, cache.jointSolverForces, mArticulationData.getJointConstraintForces()); } if (flag & PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS) { copyJointData(mArticulationData, cache.jointTargetPositions, mArticulationData.getJointTargetPositions()); } if (flag & PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES) { copyJointData(mArticulationData, cache.jointTargetVelocities, mArticulationData.getJointTargetVelocities()); } if (flag & PxArticulationCacheFlag::eLINK_VELOCITY) { const Cm::SpatialVectorF* vels = mArticulationData.getMotionVelocities(); const PxU32 numLinks = mArticulationData.getLinkCount(); for (PxU32 i = 0; i < numLinks; ++i) { const Cm::SpatialVectorF& vel = vels[i]; cache.linkVelocity[i].linear = vel.bottom; cache.linkVelocity[i].angular = vel.top; } } if (flag & PxArticulationCacheFlag::eLINK_ACCELERATION) { const PxU32 linkCount = mArticulationData.getLinkCount(); if(mArticulationData.getDt() == 0.0f) { PxMemZero(cache.linkAcceleration, sizeof(PxSpatialVelocity)*linkCount); } else if(isGpuSimEnabled) { const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin(); //Iterate over all links and compute the acceleration for each link. for (PxU32 i = 0; i < linkCount; ++i) { cache.linkAcceleration[i].linear = linkMotionAccelerationsW[i].bottom; cache.linkAcceleration[i].angular = linkMotionAccelerationsW[i].top; } } else { const PxReal invDt = 1.0f/mArticulationData.getDt(); const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin(); const Cm::SpatialVectorF* linkSpatialDeltaVelsW = mArticulationData.mSolverLinkSpatialDeltaVels.begin(); //Iterate over all links and compute the acceleration for each link. for (PxU32 i = 0; i < linkCount; ++i) { cache.linkAcceleration[i].linear = linkMotionAccelerationsW[i].bottom + linkSpatialDeltaVelsW[i].bottom*invDt; cache.linkAcceleration[i].angular = linkMotionAccelerationsW[i].top + linkSpatialDeltaVelsW[i].top*invDt; } } } if(flag & PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE) { const PxU32 linkCount = mArticulationData.getLinkCount(); if (mArticulationData.getDt() == 0.0f) { PxMemZero(cache.linkIncomingJointForce, sizeof(PxSpatialForce)*linkCount); } else if(isGpuSimEnabled) { //Calculation already completed on gpu. const Cm::SpatialVectorF* incomingJointForces = mArticulationData.getLinkIncomingJointForces(); //Root links have no incoming joint. cache.linkIncomingJointForce[0].force = PxVec3(PxZero); cache.linkIncomingJointForce[0].torque = PxVec3(PxZero); //Iterate over all links and get the incoming joint force for each link. for (PxU32 i = 1; i < linkCount; ++i) { cache.linkIncomingJointForce[i].force = incomingJointForces[i].top; cache.linkIncomingJointForce[i].torque = incomingJointForces[i].bottom; } } else { const PxReal invDt = 1.0f/mArticulationData.getDt(); //Get everything we need. const Cm::SpatialVectorF* linkZAForcesExtW = mArticulationData.mZAForces.begin(); const Cm::SpatialVectorF* linkZAForcesIntW = mArticulationData.mZAInternalForces.begin(); const Cm::SpatialVectorF* linkMotionAccelerationsW = mArticulationData.mMotionAccelerations.begin(); const SpatialMatrix* linkSpatialInertiasW = mArticulationData.mWorldSpatialArticulatedInertia.begin(); const Cm::SpatialVectorF* linkSpatialDeltaVelsW = mArticulationData.mSolverLinkSpatialDeltaVels.begin(); const Cm::SpatialVectorF* linkSpatialImpulsesW = mArticulationData.mSolverLinkSpatialImpulses.begin(); //Root links have no incoming joint. cache.linkIncomingJointForce[0].force = PxVec3(PxZero); cache.linkIncomingJointForce[0].torque = PxVec3(PxZero); //Iterate over all links and compute the incoming joint force for each link. for (PxU32 i = 1; i < linkCount; ++i) { const ArticulationLink& link = mArticulationData.getLink(i); const ArticulationJointCore* joint = link.inboundJoint; const PxTransform Gc = link.bodyCore->body2World; const PxTransform Lc = joint->childPose; const PxTransform GcLc = Gc*Lc; const PxVec3 dW = Gc.rotate(Lc.p); //Compute the force measured at the link. const Cm::SpatialVectorF incomingJointForceAtLinkW = linkSpatialInertiasW[i]*(linkMotionAccelerationsW[i] + linkSpatialDeltaVelsW[i]*invDt) + (linkZAForcesExtW[i] + linkZAForcesIntW[i] + linkSpatialImpulsesW[i]*invDt); //Compute the equivalent force measured at the joint. const Cm::SpatialVectorF incomingJointForceAtJointW = FeatherstoneArticulation::translateSpatialVector(-dW, incomingJointForceAtLinkW); //Transform the force to the child joint frame. cache.linkIncomingJointForce[i].force = GcLc.rotateInv(incomingJointForceAtJointW.top); cache.linkIncomingJointForce[i].torque = GcLc.rotateInv(incomingJointForceAtJointW.bottom); } } } if (flag & PxArticulationCacheFlag::eROOT_TRANSFORM) { const ArticulationLink& rLink = mArticulationData.getLink(0); const PxsBodyCore& rBodyCore = *rLink.bodyCore; const PxTransform& body2World = rBodyCore.body2World; // PT:: tag: scalar transform*transform cache.rootLinkData->transform = body2World * rBodyCore.getBody2Actor().getInverse(); } if (flag & PxArticulationCacheFlag::eROOT_VELOCITIES) { const Cm::SpatialVectorF& vel = mArticulationData.getMotionVelocity(0); cache.rootLinkData->worldLinVel = vel.bottom; cache.rootLinkData->worldAngVel = vel.top; const Cm::SpatialVectorF& accel = mArticulationData.getMotionAcceleration(0); cache.rootLinkData->worldLinAccel = accel.bottom; cache.rootLinkData->worldAngAccel = accel.top; } if (flag & PxArticulationCacheFlag::eSENSOR_FORCES) { const PxU32 nbSensors = mArticulationData.mNbSensors; PxMemCopy(cache.sensorForces, mArticulationData.mSensorForces, sizeof(PxSpatialForce)*nbSensors); } } PxU32 FeatherstoneArticulation::getCacheDataSize(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount) { const PxU32 totalSize = sizeof(PxSpatialForce) * linkCount // external force + sizeof(PxSpatialForce) * sensorCount // sensors (PxArticulationCacheFlag::eSENSOR_FORCES) + sizeof(PxReal) * (6 + totalDofs) * (linkCount * 6) // Free floating base dofs = 6 + totalDofs, and each link (incl. base) velocity has 6 elements // == offset to end of dense jacobian (assuming free floating base) + sizeof(PxReal) * totalDofs * totalDofs // mass matrix + sizeof(PxReal) * totalDofs * 7 // jointVelocity (PxArticulationCacheFlag::eVELOCITY) // jointAcceleration (PxArticulationCacheFlag::eACCELERATION) // jointPosition (PxArticulationCacheFlag::ePOSITION) // joint force (PxArticulationCacheFlag::eFORCE) // joint constraint force (PxArticulationCacheFlag::eJOINT_SOLVER_FORCES) // joint target positions (PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS) // joint target velocities (PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES) + sizeof(PxSpatialVelocity) * linkCount * 2 // link velocity, (PxArticulationCacheFlag::eLINK_VELOCITY) // link acceleration (PxArticulationCacheFlag::eLINK_ACCELERATION) + sizeof(PxSpatialForce) * linkCount // link incoming joint forces (PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE) + sizeof(PxArticulationRootLinkData); // root link data (PxArticulationCacheFlag::eROOT_TRANSFORM, PxArticulationCacheFlag::eROOT_VELOCITIES) return totalSize; } // AD: attention - some of the types here have 16B alignment requirements. // But the size of PxArticulationCache is not necessarily a multiple of 16B. PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVector)==sizeof(PxSpatialForce)); PxArticulationCache* FeatherstoneArticulation::createCache(PxU32 totalDofs, PxU32 linkCount, PxU32 sensorCount) { const PxU32 pxArticulationCacheSize16BAligned = (sizeof(PxArticulationCache) + 15) & ~15; const PxU32 totalSize = getCacheDataSize(totalDofs, linkCount, sensorCount) + pxArticulationCacheSize16BAligned; PxU8* tCache = reinterpret_cast<PxU8*>(PX_ALLOC(totalSize, "Articulation cache")); PX_ASSERT(((size_t)tCache & 15) == 0); PxMemZero(tCache, totalSize); PxArticulationCache* cache = reinterpret_cast<PxArticulationCache*>(tCache); PxU32 offset = pxArticulationCacheSize16BAligned; // the following code assumes that the size of PxSpatialForce and PxSpatialVelocity are multiples of 16B PX_COMPILE_TIME_ASSERT((sizeof(PxSpatialForce) & 15) == 0); PX_COMPILE_TIME_ASSERT((sizeof(PxSpatialVelocity) & 15) == 0); // PT: filled in FeatherstoneArticulation::getGeneralizedExternalForce, size = mArticulationData.getLinkCount() // 16B aligned PX_ASSERT((offset & 15) == 0); cache->externalForces = reinterpret_cast<PxSpatialForce*>(tCache + offset); offset += sizeof(PxSpatialForce) * linkCount; // PT: PxArticulationCacheFlag::eSENSOR_FORCES // 16B aligned PX_ASSERT((offset & 15) == 0); cache->sensorForces = reinterpret_cast<PxSpatialForce*>(tCache + offset); offset += sizeof(PxSpatialForce) * sensorCount; // PT: PxArticulationCacheFlag::eLINK_VELOCITY // 16B aligned PX_ASSERT((offset & 15) == 0); cache->linkVelocity = reinterpret_cast<PxSpatialVelocity*>(tCache + offset); offset += sizeof(PxSpatialVelocity) * linkCount; // PT: PxArticulationCacheFlag::eLINK_ACCELERATION // 16B aligned PX_ASSERT((offset & 15) == 0); cache->linkAcceleration = reinterpret_cast<PxSpatialVelocity*>(tCache + offset); offset += sizeof(PxSpatialVelocity) * linkCount; // PT: PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE // 16B aligned PX_ASSERT((offset & 15) == 0); cache->linkIncomingJointForce = reinterpret_cast<PxSpatialForce*>(tCache + offset); offset += sizeof(PxSpatialForce) * linkCount; cache->denseJacobian = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * (6 + totalDofs) * (linkCount * 6); //size of dense jacobian assuming free floating base link. cache->massMatrix = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs * totalDofs; // PT: PxArticulationCacheFlag::eVELOCITY cache->jointVelocity = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PT: PxArticulationCacheFlag::eACCELERATION cache->jointAcceleration = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PT: PxArticulationCacheFlag::ePOSITION cache->jointPosition = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PT: PxArticulationCacheFlag::eFORCE cache->jointForce = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PT: PxArticulationCacheFlag::eJOINT_SOLVER_FORCES cache->jointSolverForces = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS cache->jointTargetPositions = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES cache->jointTargetVelocities = reinterpret_cast<PxReal*>(tCache + offset); offset += sizeof(PxReal) * totalDofs; // PT: PxArticulationCacheFlag::eROOT_TRANSFORM, PxArticulationCacheFlag::eROOT_VELOCITIES cache->rootLinkData = reinterpret_cast<PxArticulationRootLinkData*>(tCache + offset); PX_ASSERT((offset + sizeof(PxArticulationRootLinkData)) == totalSize); cache->coefficientMatrix = NULL; cache->lambda = NULL; PxU32 scratchMemorySize = sizeof(Cm::SpatialVectorF) * linkCount * 5 //motionVelocity, motionAccelerations, coriolisVectors, spatialZAVectors, externalAccels; + sizeof(Dy::SpatialMatrix) * linkCount //compositeSpatialInertias; + sizeof(PxReal) * totalDofs * 7; //jointVelocity, jointAcceleration, jointForces, jointPositions, jointFrictionForces, jointTargetPositions, jointTargetVelocities scratchMemorySize = (scratchMemorySize+15)&~15; void* scratchMemory = PX_ALLOC(scratchMemorySize, "Cache scratch memory"); cache->scratchMemory = scratchMemory; PxcScratchAllocator* sa = PX_NEW(PxcScratchAllocator); sa->setBlock(scratchMemory, scratchMemorySize); cache->scratchAllocator = sa; return cache; } static PX_FORCE_INLINE Mat33V loadPxMat33(const PxMat33& m) { return Mat33V(Vec3V_From_Vec4V(V4LoadU(&m.column0.x)), Vec3V_From_Vec4V(V4LoadU(&m.column1.x)), V3LoadU(&m.column2.x)); } static PX_FORCE_INLINE void storePxMat33(const Mat33V& src, PxMat33& dst) { V3StoreU(src.col0, dst.column0); V3StoreU(src.col1, dst.column1); V3StoreU(src.col2, dst.column2); } void FeatherstoneArticulation::transformInertia(const SpatialTransform& sTod, SpatialMatrix& spatialInertia) { #if 1 const SpatialTransform dTos = sTod.getTranspose(); Mat33V tL = loadPxMat33(spatialInertia.topLeft); Mat33V tR = loadPxMat33(spatialInertia.topRight); Mat33V bL = loadPxMat33(spatialInertia.bottomLeft); Mat33V R = loadPxMat33(sTod.R); Mat33V T = loadPxMat33(sTod.T); Mat33V tl = M33MulM33(R, tL); Mat33V tr = M33MulM33(R, tR); Mat33V bl = M33Add(M33MulM33(T, tL), M33MulM33(R, bL)); Mat33V br = M33Add(M33MulM33(T, tR), M33MulM33(R, M33Trnsps(tL))); Mat33V dR = loadPxMat33(dTos.R); Mat33V dT = loadPxMat33(dTos.T); tL = M33Add(M33MulM33(tl, dR), M33MulM33(tr, dT)); tR = M33MulM33(tr, dR); bL = M33Add(M33MulM33(bl, dR), M33MulM33(br, dT)); bL = M33Scale(M33Add(bL, M33Trnsps(bL)), FHalf()); storePxMat33(tL, spatialInertia.topLeft); storePxMat33(tR, spatialInertia.topRight); storePxMat33(bL, spatialInertia.bottomLeft); #else const SpatialTransform dTos = sTod.getTranspose(); PxMat33 tl = sTod.R * spatialInertia.topLeft; PxMat33 tr = sTod.R * spatialInertia.topRight; PxMat33 bl = sTod.T * spatialInertia.topLeft + sTod.R * spatialInertia.bottomLeft; PxMat33 br = sTod.T * spatialInertia.topRight + sTod.R * spatialInertia.getBottomRight(); spatialInertia.topLeft = tl * dTos.R + tr * dTos.T; spatialInertia.topRight = tr * dTos.R; spatialInertia.bottomLeft = bl * dTos.R + br * dTos.T; //aligned inertia spatialInertia.bottomLeft = (spatialInertia.bottomLeft + spatialInertia.bottomLeft.getTranspose()) * 0.5f; #endif } PxMat33 FeatherstoneArticulation::translateInertia(const PxMat33& inertia, const PxReal mass, const PxVec3& t) { PxMat33 s(PxVec3(0, t.z, -t.y), PxVec3(-t.z, 0, t.x), PxVec3(t.y, -t.x, 0)); PxMat33 translatedIT = s.getTranspose() * s * mass + inertia; return translatedIT; } void FeatherstoneArticulation::translateInertia(const PxMat33& sTod, SpatialMatrix& inertia) { #if 1 Mat33V sTodV = loadPxMat33(sTod); Mat33V dTos = M33Trnsps(sTodV); const Mat33V tL = loadPxMat33(inertia.topLeft); const Mat33V tR = loadPxMat33(inertia.topRight); const Mat33V bL = loadPxMat33(inertia.bottomLeft); const Mat33V bl = M33Add(M33MulM33(sTodV, tL), bL); const Mat33V br = M33Add(M33MulM33(sTodV, tR), M33Trnsps(tL)); const Mat33V bottomLeft = M33Add(bl, M33MulM33(br, dTos)); storePxMat33(M33Add(tL, M33MulM33(tR, dTos)), inertia.topLeft); storePxMat33(M33Scale(M33Add(bottomLeft, M33Trnsps(bottomLeft)), FHalf()), inertia.bottomLeft); #else const PxMat33 dTos = sTod.getTranspose(); PxMat33 bl = sTod * inertia.topLeft + inertia.bottomLeft; PxMat33 br = sTod * inertia.topRight + inertia.getBottomRight(); inertia.topLeft = inertia.topLeft + inertia.topRight * dTos; inertia.bottomLeft = bl + br * dTos; //aligned inertia - make it symmetrical! OPTIONAL!!!! inertia.bottomLeft = (inertia.bottomLeft + inertia.bottomLeft.getTranspose()) * 0.5f; #endif } void FeatherstoneArticulation::getImpulseResponse( PxU32 linkID, Cm::SpatialVectorF* Z, const Cm::SpatialVector& impulse, Cm::SpatialVector& deltaVV) const { PX_UNUSED(Z); PX_ASSERT(impulse.pad0 == 0.f && impulse.pad1 == 0.f); //impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body //| R(t), 0 | //| R(t)*r, R(t)| //r is the vector from center of mass to contact point //p(impluse) = |n| // |0| Cm::SpatialVectorF deltaV = mArticulationData.getImpulseResponseMatrixWorld()[linkID].getResponse(reinterpret_cast<const Cm::SpatialVectorF&>(impulse)); deltaVV.linear = deltaV.bottom; deltaVV.angular = deltaV.top; } void FeatherstoneArticulation::getImpulseResponse( PxU32 linkID, Cm::SpatialVectorV* /*Z*/, const Cm::SpatialVectorV& impulse, Cm::SpatialVectorV& deltaVV) const { #if 0 const PxTransform& body2World = mArticulationData.getPreTransform(linkID); QuatV rot = QuatVLoadU(&body2World.q.x); Cm::SpatialVectorV impl(QuatRotateInv(rot, impulse.linear), QuatRotateInv(rot, impulse.angular)); //transform p(impluse) from world space to the local space of linkId //Cm::SpatialVectorF impl(impulse.linear, impulse.angular); Cm::SpatialVectorV deltaV = mArticulationData.getImpulseResponseMatrix()[linkID].getResponse(impl); deltaVV.linear = QuatRotate(rot, deltaV.angular); deltaVV.angular = QuatRotate(rot, deltaV.linear); #else Cm::SpatialVectorV deltaV = mArticulationData.getImpulseResponseMatrixWorld()[linkID].getResponse(impulse); deltaVV.linear = deltaV.angular; deltaVV.angular = deltaV.linear; #endif } //This will return world space SpatialVectorV Cm::SpatialVectorV FeatherstoneArticulation::getLinkVelocity(const PxU32 linkID) const { //This is in the world space const Cm::SpatialVectorF& motionVelocity = mArticulationData.getMotionVelocity(linkID); Cm::SpatialVectorV velocity; velocity.linear = V3LoadA(motionVelocity.bottom); velocity.angular = V3LoadA(motionVelocity.top); return velocity; } Cm::SpatialVector FeatherstoneArticulation::getLinkScalarVelocity(const PxU32 linkID) const { //This is in the world space const Cm::SpatialVectorF& motionVelocity = mArticulationData.getMotionVelocity(linkID); return Cm::SpatialVector(motionVelocity.bottom, motionVelocity.top); } Cm::SpatialVectorV FeatherstoneArticulation::getLinkMotionVector(const PxU32 linkID) const { const Cm::SpatialVectorF& motionVector = mArticulationData.getDeltaMotionVector(linkID); Cm::SpatialVectorV velocity; velocity.linear = V3LoadU(motionVector.bottom); velocity.angular = V3LoadU(motionVector.top); return velocity; } //this is called by island gen to determine whether the articulation should be awake or sleep Cm::SpatialVector FeatherstoneArticulation::getMotionVelocity(const PxU32 linkID) const { //This is in the world space const Cm::SpatialVectorF& motionVelocity = mArticulationData.getPosIterMotionVelocities()[linkID]; return Cm::SpatialVector(motionVelocity.bottom, motionVelocity.top); } Cm::SpatialVector FeatherstoneArticulation::getMotionAcceleration(const PxU32 linkID, const bool isGpuSimEnabled) const { Cm::SpatialVector a = Cm::SpatialVector::zero(); if(mArticulationData.getDt() > 0.0f) { if(isGpuSimEnabled) { const Cm::SpatialVectorF& linkAccel = mArticulationData.mMotionAccelerations[linkID]; a = Cm::SpatialVector(linkAccel.bottom, linkAccel.top); } else { const PxReal invDt = 1.0f/mArticulationData.getDt(); const Cm::SpatialVectorF linkAccel = mArticulationData.mMotionAccelerations[linkID] + mArticulationData.mSolverLinkSpatialDeltaVels[linkID]*invDt; a = Cm::SpatialVector(linkAccel.bottom, linkAccel.top); } } return a; } void FeatherstoneArticulation::fillIndexType(const PxU32 linkId, PxU8& indexType) { ArticulationLink& link = mArticulationData.getLink(linkId); //turn the fixed-base links to static for the solver if(link.bodyCore->fixedBaseLink) indexType = PxsIndexedInteraction::eWORLD; else indexType = PxsIndexedInteraction::eARTICULATION; } PxReal FeatherstoneArticulation::getLinkMaxPenBias(const PxU32 linkID) const { return mArticulationData.getLinkData(linkID).maxPenBias; } PxReal FeatherstoneArticulation::getCfm(const PxU32 linkID) const { return mArticulationData.getLink(linkID).cfm; } void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool computeForces) { PX_ASSERT(deltaV); ArticulationData& data = articulation.mArticulationData; const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities(); //Cm::SpatialVectorF* deferredZ = data.getSpatialZAVectors(); ArticulationLink* links = data.getLinks(); ArticulationJointCoreData* jointData = data.getJointData(); //PxTransform* poses = data.getAccumulatedPoses(); //const PxTransform* poses = data.getPreTransform(); //This will be zero at the begining of the frame PxReal* jointNewVelocities = data.getJointNewVelocities(); data.getSolverSpatialForce(0) -= data.getRootDeferredZ(); if (fixBase) { deltaV[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); } else { //ArticulationLink& link = links[0]; deltaV[0] = data.getBaseInvSpatialArticulatedInertiaW() * -data.getRootDeferredZ(); motionVelocities[0] += deltaV[0]; PX_ASSERT(motionVelocities[0].isFinite()); } const PxU32 linkCount = data.getLinkCount(); for (PxU32 i = 1; i < linkCount; i++) { const ArticulationLink& tLink = links[i]; const ArticulationJointCoreData& tJointDatum = jointData[i]; const Cm::SpatialVectorF dV = FeatherstoneArticulation::propagateAccelerationW(data.getRw(i), data.getInvStIs(i), &data.getWorldMotionMatrix(tJointDatum.jointOffset), &jointNewVelocities[tJointDatum.jointOffset], deltaV[tLink.parent], tJointDatum.dof, &data.getIsW(tJointDatum.jointOffset), &data.getDeferredQstZ()[tJointDatum.jointOffset]); deltaV[i] = dV; motionVelocities[i] += dV; //Cm::SpatialVectorF& v = motionVelocities[i]; //printf("linkID %i motionV(%f, %f, %f, %f, %f, %f)\n", i, v.top.x, v.top.y, v.top.z, v.bottom.x, v.bottom.y, v.bottom.z); /*if(computeForces) data.getSolverSpatialForce(i) += data.getWorldSpatialArticulatedInertia(i) * dV;*/ data.incrementSolverSpatialDeltaVel(i, dV); if (computeForces) data.getSolverSpatialForce(i) += dV; PX_ASSERT(motionVelocities[i].isFinite()); } //PxMemZero(deferredZ, sizeof(Cm::SpatialVectorF)*linkCount); PxMemZero(data.getDeferredQstZ(), sizeof(PxReal) * data.getDofs()); data.getRootDeferredZ() = Cm::SpatialVectorF::Zero(); } void FeatherstoneArticulation::recordDeltaMotion(const ArticulationSolverDesc& desc, const PxReal dt, Cm::SpatialVectorF* deltaV, const PxReal /*totalInvDt*/) { PX_ASSERT(deltaV); FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation); ArticulationData& data = articulation->mArticulationData; const PxU32 linkCount = data.getLinkCount(); const PxU32 flags = data.getArticulationFlags(); if (data.mJointDirty) { bool doForces = (flags & PxArticulationFlag::eCOMPUTE_JOINT_FORCES) || data.getSensorCount(); PxcFsFlushVelocity(*articulation, deltaV, doForces); } Cm::SpatialVectorF* deltaMotion = data.getDeltaMotionVector(); Cm::SpatialVectorF* posMotionVelocities = data.getPosIterMotionVelocities(); Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities(); PxReal* jointPosition = data.getJointPositions(); PxReal* jointNewVelocities = data.getJointNewVelocities(); //data.mAccumulatedDt += dt; data.setDt(dt); const bool fixBase = flags & PxArticulationFlag::eFIX_BASE; if (!fixBase) { Cm::SpatialVectorF& motionVelocity = motionVelocities[0]; PX_ASSERT(motionVelocity.top.isFinite()); PX_ASSERT(motionVelocity.bottom.isFinite()); const PxTransform preTrans = data.mAccumulatedPoses[0]; const PxVec3 lin = motionVelocity.bottom; const PxVec3 ang = motionVelocity.top; const PxVec3 newP = preTrans.p + lin * dt; const PxTransform newPose = PxTransform(newP, PxExp(ang*dt) * preTrans.q); //PxVec3 lin, ang; /*calculateNewVelocity(newPose, data.mPreTransform[0], 1.f, lin, ang); */ data.mAccumulatedPoses[0] = newPose; PxQuat dq = newPose.q * data.mPreTransform[0].q.getConjugate(); if (dq.w < 0.f) dq = -dq; data.mDeltaQ[0] = dq; Cm::SpatialVectorF delta = motionVelocity * dt; deltaMotion[0] += delta; posMotionVelocities[0] += delta; } for (PxU32 linkID = 1; linkID < linkCount; linkID++) { ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const PxTransform newPose = articulation->propagateTransform(linkID, data.getLinks(), jointDatum, data.getMotionVelocities(), dt, data.mAccumulatedPoses[data.getLink(linkID).parent], data.mAccumulatedPoses[linkID], jointNewVelocities, jointPosition, &data.getMotionMatrix(jointDatum.jointOffset), &data.getWorldMotionMatrix(jointDatum.jointOffset)); //data.mDeltaQ[linkID] = data.mPreTransform[linkID].q.getConjugate() * newPose.q; PxQuat dq = newPose.q * data.mPreTransform[linkID].q.getConjugate(); if(dq.w < 0.f) dq = -dq; data.mDeltaQ[linkID] = dq; /*PxVec3 lin, ang; calculateNewVelocity(newPose, data.mPreTransform[linkID], 1.f, lin, ang);*/ PxVec3 lin = (newPose.p - data.mPreTransform[linkID].p); Cm::SpatialVectorF delta = motionVelocities[linkID] * dt; //deltaMotion[linkID].top = ang;// motionVeloties[linkID].top * dt; deltaMotion[linkID].top += delta.top; deltaMotion[linkID].bottom = lin;// motionVeloties[linkID].top * dt; posMotionVelocities[linkID] += delta; //Record the new current pose data.mAccumulatedPoses[linkID] = newPose; } } void FeatherstoneArticulation::deltaMotionToMotionVelocity(const ArticulationSolverDesc& desc, PxReal invDt) { FeatherstoneArticulation* articulation = static_cast<FeatherstoneArticulation*>(desc.articulation); ArticulationData& data = articulation->mArticulationData; const PxU32 linkCount = data.getLinkCount(); const Cm::SpatialVectorF* deltaMotion = data.getDeltaMotionVector(); for (PxU32 linkID = 0; linkID<linkCount; linkID++) { Cm::SpatialVectorF& v = data.getMotionVelocity(linkID); Cm::SpatialVectorF delta = deltaMotion[linkID] * invDt; v = delta; desc.motionVelocity[linkID] = reinterpret_cast<Cm::SpatialVectorV&>(delta); } } //This is used in the solveExt1D, solveExtContact Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocity(PxU32 linkID) { //Cm::SpatialVectorF* deferredZ = mArticulationData.getSpatialZAVectors(); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; ArticulationLink* links = mArticulationData.getLinks(); Cm::SpatialVectorF deltaV(PxVec3(0.f), PxVec3(0.f)); if (!fixBase) { //deltaV = mArticulationData.mBaseInvSpatialArticulatedInertia * (-deferredZ[0]); //DeferredZ now in world space! deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * -mArticulationData.getRootDeferredZ(); } const PxU32 startIndex = links[linkID].mPathToRootStartIndex; const PxU32 elementCount = links[linkID].mPathToRootCount; const PxU32* pathToRootElements = &mArticulationData.mPathToRootElements[startIndex]; for (PxU32 i = 0; i < elementCount; ++i) { const PxU32 index = pathToRootElements[i]; PX_ASSERT(links[index].parent < index); const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(index).dof; deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]); } Cm::SpatialVectorF vel = mArticulationData.getMotionVelocity(linkID) + deltaV; return Cm::SpatialVector(vel.bottom, vel.top); } void FeatherstoneArticulation::pxcFsGetVelocities(PxU32 linkID, PxU32 linkID1, Cm::SpatialVectorV& v0, Cm::SpatialVectorV& v1) { { const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; ArticulationLink* links = mArticulationData.getLinks(); Cm::SpatialVectorF deltaV(PxVec3(0.f), PxVec3(0.f)); if (!fixBase) { //deltaV = mArticulationData.mBaseInvSpatialArticulatedInertia * (-deferredZ[0]); deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-mArticulationData.mRootDeferredZ); } const PxU32* pathToRootElements = mArticulationData.mPathToRootElements; Dy::ArticulationLink& link0 = links[linkID]; Dy::ArticulationLink& link1 = links[linkID1]; const PxU32* pathToRoot0 = &pathToRootElements[link0.mPathToRootStartIndex]; const PxU32* pathToRoot1 = &pathToRootElements[link1.mPathToRootStartIndex]; const PxU32 numElems0 = link0.mPathToRootCount; const PxU32 numElems1 = link1.mPathToRootCount; PxU32 offset = 0; while (pathToRoot0[offset] == pathToRoot1[offset]) { const PxU32 index = pathToRoot0[offset++]; PX_ASSERT(links[index].parent < index); if (offset >= numElems0 || offset >= numElems1) break; const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(index).dof; deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]); } Cm::SpatialVectorF deltaV1 = deltaV; for (PxU32 idx = offset; idx < numElems0; ++idx) { const PxU32 index = pathToRoot0[idx]; PX_ASSERT(links[index].parent < index); const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(index).dof; deltaV = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[jointOffset], deltaV, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]); } for (PxU32 idx = offset; idx < numElems1; ++idx) { const PxU32 index = pathToRoot1[idx]; PX_ASSERT(links[index].parent < index); const PxU32 jointOffset = mArticulationData.getJointData(index).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(index).dof; deltaV1 = propagateAccelerationW(mArticulationData.getRw(index), mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[jointOffset], deltaV1, dofCount, &mArticulationData.mIsW[jointOffset], &mArticulationData.mDeferredQstZ[jointOffset]); } Cm::SpatialVectorF vel = mArticulationData.getMotionVelocity(linkID) + deltaV; v0 = Cm::SpatialVector(vel.bottom, vel.top); Cm::SpatialVectorF vel1 = mArticulationData.getMotionVelocity(linkID1) + deltaV1; v1 = Cm::SpatialVector(vel1.bottom, vel1.top); } } /*Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocity(PxU32 linkID) { Cm::SpatialVectorF& vel = mArticulationData.getMotionVelocity(linkID); return Cm::SpatialVector(vel.bottom, vel.top); }*/ Cm::SpatialVectorV FeatherstoneArticulation::pxcFsGetVelocityTGS(PxU32 linkID) { return getLinkVelocity(linkID); } //This is used in the solveExt1D, solveExtContact void FeatherstoneArticulation::pxcFsApplyImpulse(PxU32 linkID, aos::Vec3V linear, aos::Vec3V angular, Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*deltaV*/) { const ArticulationSolverDesc* desc = &mSolverDesc; ArticulationLink* links = static_cast<ArticulationLink*>(desc->links); //initialize all zero acceration impulse to be zero ArticulationData& data = mArticulationData; data.mJointDirty = true; //impulse is in world space Cm::SpatialVector impulse; V4StoreA(Vec4V_From_Vec3V(angular), &impulse.angular.x); V4StoreA(Vec4V_From_Vec3V(linear), &impulse.linear.x); Cm::SpatialVectorF Z0(-impulse.linear, -impulse.angular); for (PxU32 i = linkID; i; i = links[i].parent) { const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(i).dof; data.mSolverLinkSpatialImpulses[i] += Z0; Z0 = FeatherstoneArticulation::propagateImpulseW( mArticulationData.getRw(i), Z0, &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount, &mArticulationData.mDeferredQstZ[jointOffset]); } data.mRootDeferredZ += Z0; } void FeatherstoneArticulation::pxcFsApplyImpulses(Cm::SpatialVectorF* Z) { ArticulationLink* links = mArticulationData.getLinks(); //initialize all zero acceration impulse to be zero ArticulationData& data = mArticulationData; const PxU32 linkCount = mArticulationData.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); data.mJointDirty = true; for (PxU32 linkID = startIndex; linkID > 0; --linkID) { ArticulationLink& tLink = links[linkID]; const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID).dof; Cm::SpatialVectorF ZA = Z[linkID]; Z[tLink.parent] += propagateImpulseW( mArticulationData.getRw(linkID), ZA, &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount, &mArticulationData.mDeferredQstZ[jointOffset]); } data.mRootDeferredZ += Z[0]; } void FeatherstoneArticulation::pxcFsApplyImpulses(PxU32 linkID, const aos::Vec3V& linear, const aos::Vec3V& angular, PxU32 linkID2, const aos::Vec3V& linear2, const aos::Vec3V& angular2, Cm::SpatialVectorF* /*Z*/, Cm::SpatialVectorF* /*deltaV*/) { if (0) { pxcFsApplyImpulse(linkID, linear, angular, NULL, NULL); pxcFsApplyImpulse(linkID2, linear2, angular2, NULL, NULL); } else { const ArticulationSolverDesc* desc = &mSolverDesc; ArticulationData& data = mArticulationData; data.mJointDirty = true; ArticulationLink* links = static_cast<ArticulationLink*>(desc->links); //impulse is in world space Cm::SpatialVector impulse0; V3StoreU(angular, impulse0.angular); V3StoreU(linear, impulse0.linear); Cm::SpatialVector impulse1; V3StoreU(angular2, impulse1.angular); V3StoreU(linear2, impulse1.linear); Cm::SpatialVectorF Z1(-impulse0.linear, -impulse0.angular); Cm::SpatialVectorF Z2(-impulse1.linear, -impulse1.angular); ArticulationLink& link0 = links[linkID]; ArticulationLink& link1 = links[linkID2]; const PxU32* pathToRoot0 = &mArticulationData.mPathToRootElements[link0.mPathToRootStartIndex]; const PxU32* pathToRoot1 = &mArticulationData.mPathToRootElements[link1.mPathToRootStartIndex]; const PxU32 numElems0 = link0.mPathToRootCount; const PxU32 numElems1 = link1.mPathToRootCount; //find the common link, work from one to that common, then the other to that common, then go from there upwards... PxU32 offset = 0; PxU32 commonLink = 0; while (pathToRoot0[offset] == pathToRoot1[offset]) { commonLink = pathToRoot0[offset++]; PX_ASSERT(links[commonLink].parent < commonLink); if (offset >= numElems0 || offset >= numElems1) break; } //The common link will either be linkID2, or its ancestors. //The common link cannot be an index before either linkID2 or linkID for (PxU32 i = linkID2; i != commonLink; i = links[i].parent) { const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(i).dof; Z2 = propagateImpulseW( mArticulationData.getRw(i), Z2, &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount, &data.mDeferredQstZ[jointOffset]); } for (PxU32 i = linkID; i != commonLink; i = links[i].parent) { const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(i).dof; Z1 = propagateImpulseW( mArticulationData.getRw(i), Z1, &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset],dofCount, &data.mDeferredQstZ[jointOffset]); } Cm::SpatialVectorF ZCommon = Z1 + Z2; for (PxU32 i = commonLink; i; i = links[i].parent) { const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(i).dof; ZCommon = propagateImpulseW( mArticulationData.getRw(i), ZCommon, &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount, &data.mDeferredQstZ[jointOffset]); } data.mRootDeferredZ += ZCommon; } } //Z is the link space(drag force) void FeatherstoneArticulation::applyImpulses(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) { ArticulationLink* links = mArticulationData.getLinks(); //initialize all zero acceration impulse to be zero ArticulationData& data = mArticulationData; const PxU32 linkCount = mArticulationData.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); for (PxU32 linkID = startIndex; linkID > 0; --linkID) { ArticulationLink& tLink = links[linkID]; const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID).dof; Z[tLink.parent] += propagateImpulseW( mArticulationData.getRw(linkID), Z[linkID], &data.mISInvStIS[jointOffset],&data.mWorldMotionMatrix[jointOffset], dofCount); } getDeltaV(Z, deltaV); } void FeatherstoneArticulation::getDeltaV(Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) { const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; Cm::SpatialVectorF* motionVelocities = mArticulationData.getMotionVelocities(); ArticulationLink* links = mArticulationData.getLinks(); ArticulationJointCoreData* jointData = mArticulationData.getJointData(); //This will be zero at the begining of the frame PxReal* jointDeltaVelocities = mArticulationData.getJointNewVelocities(); if (fixBase) { deltaV[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); } else { deltaV[0] = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-Z[0]); motionVelocities[0] += deltaV[0]; PX_ASSERT(motionVelocities[0].isFinite()); } const PxU32 linkCount = mArticulationData.getLinkCount(); for (PxU32 i = 1; i < linkCount; i++) { ArticulationLink& tLink = links[i]; ArticulationJointCoreData& tJointDatum = jointData[i]; const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(i).dof; Cm::SpatialVectorF dV = propagateVelocityW(mArticulationData.getRw(i), mArticulationData.mWorldSpatialArticulatedInertia[i], mArticulationData.mInvStIs[i], &mArticulationData.mWorldMotionMatrix[jointOffset], Z[i], &jointDeltaVelocities[tJointDatum.jointOffset], deltaV[tLink.parent], dofCount); deltaV[i] = dV; motionVelocities[i] += dV; PX_ASSERT(motionVelocities[i].isFinite()); } } //This version uses in updateBodies PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat, const PxQuat& newRot, const PxQuat& pBody2WorldRot, PxReal* jPositions, const Cm::UnAlignedSpatialVector* motionMatrix, const PxU32 dofs); PxQuat computeSphericalJointPositions(const PxQuat& relativeQuat, const PxQuat& newRot, const PxQuat& pBody2WorldRot); PxTransform FeatherstoneArticulation::propagateTransform(const PxU32 linkID, ArticulationLink* links, ArticulationJointCoreData& jointDatum, Cm::SpatialVectorF* motionVelocities, const PxReal dt, const PxTransform& pBody2World, const PxTransform& currentTransform, PxReal* jointVelocities, PxReal* jointPositions, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::UnAlignedSpatialVector* /*worldMotionMatrix*/) { ArticulationLink& link = links[linkID]; const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID]; ArticulationJointCore* joint = link.inboundJoint; PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; PxQuat newParentToChild; PxQuat newWorldQ; PxVec3 r; const PxVec3 childOffset = -joint->childPose.p; const PxVec3 parentOffset = joint->parentPose.p; switch (joint->jointType) { case PxArticulationJointType::ePRISMATIC: { PxReal tJointPosition = jPosition[0] + (jVelocity[0]) * dt; const PxU32 dofId = link.inboundJoint->dofIds[0]; if (link.inboundJoint->motion[dofId] == PxArticulationMotion::eLIMITED) { if (tJointPosition < (link.inboundJoint->limits[dofId].low)) tJointPosition = link.inboundJoint->limits[dofId].low; if (tJointPosition >(link.inboundJoint->limits[dofId].high)) tJointPosition = link.inboundJoint->limits[dofId].high; } jPosition[0] = tJointPosition; newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d + motionMatrix[0].bottom * tJointPosition; break; } case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { PxReal tJointPosition = jPosition[0] + (jVelocity[0]) * dt; /*PxU8 dofId = link.inboundJoint->dofIds[0]; if (link.inboundJoint->motion[dofId] == PxArticulationMotion::eLIMITED) { if (tJointPosition < (link.inboundJoint->limits[dofId].low)) tJointPosition = link.inboundJoint->limits[dofId].low; if (tJointPosition >(link.inboundJoint->limits[dofId].high)) tJointPosition = link.inboundJoint->limits[dofId].high; }*/ jPosition[0] = tJointPosition; const PxVec3& u = motionMatrix[0].top; PxQuat jointRotation = PxQuat(-tJointPosition, u); if (jointRotation.w < 0) //shortest angle. jointRotation = -jointRotation; newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eSPHERICAL: { Cm::SpatialVectorF worldVel = motionVelocities[linkID]; const PxTransform oldTransform = currentTransform; PxVec3 worldAngVel = worldVel.top; //PxVec3 worldAngVel = motionVelocities[linkID].top; PxReal dist = worldAngVel.normalize() * dt; if (dist > 1e-6f) newWorldQ = PxQuat(dist, worldAngVel) * oldTransform.q; else newWorldQ = oldTransform.q; //newWorldQ = Ps::exp(worldAngVel*dt) * oldTransform.q; //PxVec3 axis; newParentToChild = computeSphericalJointPositions(mArticulationData.mRelativeQuat[linkID], newWorldQ, pBody2World.q); PxQuat jointRotation = newParentToChild * relativeQuat.getConjugate(); if(jointRotation.w < 0.0f) jointRotation = -jointRotation; /*PxVec3 axis = jointRotation.getImaginaryPart(); for (PxU32 i = 0; i < jointDatum.dof; ++i) { PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top; PxReal angle = -compAng(sa.dot(axis), jointRotation.w); jPosition[i] = angle; }*/ PxVec3 axis; PxReal angle; jointRotation.toRadiansAndUnitAxis(angle, axis); axis *= angle; for (PxU32 i = 0; i < jointDatum.dof; ++i) { PxVec3 sa = mArticulationData.getMotionMatrix(jointDatum.jointOffset + i).top; PxReal ang = -sa.dot(axis); jPosition[i] = ang; } const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eFIX: { //this is fix joint so joint don't have velocity newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; break; } default: break; } PxTransform cBody2World; cBody2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized(); cBody2World.p = pBody2World.p + cBody2World.q.rotate(r); PX_ASSERT(cBody2World.isSane()); return cBody2World; } const PxTransform& FeatherstoneArticulation::getCurrentTransform(PxU32 linkID) const { return mArticulationData.mAccumulatedPoses[linkID]; } const PxQuat& FeatherstoneArticulation::getDeltaQ(PxU32 linkID) const { return mArticulationData.mDeltaQ[linkID]; } ////Z is the spatial acceleration impulse of links[linkID] //Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocity(const Dy::SpatialTransform& c2p, const Dy::SpatialMatrix& spatialInertia, // const InvStIs& invStIs, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z, PxReal* jointVelocity, const Cm::SpatialVectorF& hDeltaV) //{ // const PxU32 dofCount = motionMatrix.getNumColumns(); // Cm::SpatialVectorF pDeltaV = c2p.transposeTransform(hDeltaV); //parent velocity change // Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z; // PxReal tJointDelta[6]; // for (PxU32 ind = 0; ind < dofCount; ++ind) // { // const Cm::SpatialVectorF& sa = motionMatrix[ind]; // tJointDelta[ind] = -sa.innerProduct(temp); // } // Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f)); // for (PxU32 ind = 0; ind < dofCount; ++ind) // { // PxReal jDelta = 0.f; // for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) // { // jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2]; // } // jointVelocity[ind] += jDelta; // const Cm::SpatialVectorF& sa = motionMatrix[ind]; // jointSpatialDeltaV += sa * jDelta; // } // return pDeltaV + jointSpatialDeltaV; //} ////This method calculate the velocity change due to collision/constraint impulse //Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityTestImpulse(const Dy::SpatialTransform& c2p, const Dy::SpatialMatrix& spatialInertia, // const InvStIs& invStIs, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z, // const Cm::SpatialVectorF& hDeltaV) //{ // const PxU32 dofCount = motionMatrix.getNumColumns(); // Cm::SpatialVectorF pDeltaV = c2p.transposeTransform(hDeltaV); //parent velocity change // Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z; // PxReal tJointDelta[6]; // for (PxU32 ind = 0; ind < dofCount; ++ind) // { // const Cm::SpatialVectorF& sa = motionMatrix[ind]; // tJointDelta[ind] = -sa.innerProduct(temp); // } // Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f)); // for (PxU32 ind = 0; ind < dofCount; ++ind) // { // PxReal jDelta = 0.f; // for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) // { // jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2]; // } // const Cm::SpatialVectorF& sa = motionMatrix[ind]; // jointSpatialDeltaV += sa * jDelta; // } // return pDeltaV + jointSpatialDeltaV; //} PX_CUDA_CALLABLE PX_FORCE_INLINE Cm::SpatialVectorF translateImpulse(const Cm::SpatialVectorF& s, const PxVec3& offset) { return Cm::SpatialVectorF(s.top, offset.cross(s.top) + s.bottom); } //This method calculate the velocity change due to collision/constraint impulse, record joint velocity and acceleration Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia, const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z, PxReal* jointVelocity, const Cm::SpatialVectorF& hDeltaV, const PxU32 dofCount) { Cm::SpatialVectorF pDeltaV = translateImpulse(hDeltaV, -c2p); //parent velocity change Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z; PxReal tJointDelta[6]; for (PxU32 ind = 0; ind < dofCount; ++ind) { const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind]; tJointDelta[ind] = -sa.innerProduct(temp); } Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < dofCount; ++ind) { PxReal jDelta = 0.f; for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) { jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2]; } jointVelocity[ind] += jDelta; const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind]; jointSpatialDeltaV.top += sa.top * jDelta; jointSpatialDeltaV.bottom += sa.bottom * jDelta; } return pDeltaV + jointSpatialDeltaV; } Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p, const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZIc) { Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change PxReal tJAccel[3]; for (PxU32 ind = 0; ind < dofCount; ++ind) { //stI * pAcceleration const PxReal temp = IsW[ind].innerProduct(motionAcceleration); tJAccel[ind] = (qstZIc[ind] - temp); } //calculate jointAcceleration for (PxU32 ind = 0; ind < dofCount; ++ind) { PxReal jVel = 0.f; //for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) { jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2]; } //PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000); motionAcceleration.top += motionMatrix[ind].top * jVel; motionAcceleration.bottom += motionMatrix[ind].bottom * jVel; jointVelocity[ind] += jVel; } return motionAcceleration; } Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p, const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& pAcceleration, const PxU32 dofCount, const Cm::SpatialVectorF* IsW, PxReal* qstZ) { Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change PxReal tJAccel[3]; for (PxU32 ind = 0; ind < dofCount; ++ind) { //stI * pAcceleration const PxReal temp = IsW[ind].innerProduct(motionAcceleration); tJAccel[ind] = (qstZ[ind] - temp); } //calculate jointAcceleration for (PxU32 ind = 0; ind < dofCount; ++ind) { PxReal jVel = 0.f; for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) { jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2]; } //PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000); motionAcceleration.top += motionMatrix[ind].top * jVel; motionAcceleration.bottom += motionMatrix[ind].bottom * jVel; } return motionAcceleration; } Cm::SpatialVectorF FeatherstoneArticulation::propagateAccelerationW(const PxVec3& c2p, const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, PxReal* jointVelocity, const Cm::SpatialVectorF& pAcceleration, Cm::SpatialVectorF& Z, const PxU32 dofCount, const Cm::SpatialVectorF* IsW) { Cm::SpatialVectorF motionAcceleration = translateImpulse(pAcceleration, -c2p); //parent velocity change PxReal tJAccel[3]; for (PxU32 ind = 0; ind < dofCount; ++ind) { //stI * pAcceleration const PxReal temp = IsW[ind].innerProduct(motionAcceleration); PxReal qstZ = -motionMatrix[ind].innerProduct(Z); tJAccel[ind] = (qstZ - temp); } //calculate jointAcceleration for (PxU32 ind = 0; ind < dofCount; ++ind) { PxReal jVel = 0.f; for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) { jVel += invStIs.invStIs[ind2][ind] * tJAccel[ind2]; } //PX_ASSERT(PxAbs(jointAcceleration[ind]) < 5000); motionAcceleration.top += motionMatrix[ind].top * jVel; motionAcceleration.bottom += motionMatrix[ind].bottom * jVel; jointVelocity[ind] += jVel; } return motionAcceleration; } //This method calculate the velocity change due to collision/constraint impulse Cm::SpatialVectorF FeatherstoneArticulation::propagateVelocityTestImpulseW(const PxVec3& c2p, const Dy::SpatialMatrix& spatialInertia, const InvStIs& invStIs, const Cm::UnAlignedSpatialVector* motionMatrix, const Cm::SpatialVectorF& Z, const Cm::SpatialVectorF& hDeltaV, const PxU32 dofCount) { Cm::SpatialVectorF pDeltaV = translateImpulse(hDeltaV, -c2p); //parent velocity change //Convert parent velocity change into an impulse Cm::SpatialVectorF temp = spatialInertia * pDeltaV + Z; PxReal tJointDelta[3]; for (PxU32 ind = 0; ind < dofCount; ++ind) { const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind]; tJointDelta[ind] = -sa.innerProduct(temp); } Cm::SpatialVectorF jointSpatialDeltaV(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < dofCount; ++ind) { PxReal jDelta = 0.f; for (PxU32 ind2 = 0; ind2 < dofCount; ++ind2) { jDelta += invStIs.invStIs[ind2][ind] * tJointDelta[ind2]; } const Cm::UnAlignedSpatialVector& sa = motionMatrix[ind]; jointSpatialDeltaV.top += sa.top * jDelta; jointSpatialDeltaV.bottom += sa.bottom * jDelta; } return pDeltaV + jointSpatialDeltaV; } //Cm::SpatialVectorF FeatherstoneArticulation::propagateImpulse(const IsInvD& isInvD, // const SpatialTransform& childToParent, const SpatialSubspaceMatrix& motionMatrix, const Cm::SpatialVectorF& Z) //{ // const PxU32 dofCount = motionMatrix.getNumColumns(); // Cm::SpatialVectorF temp(PxVec3(0.f), PxVec3(0.f)); // for (PxU32 ind = 0; ind < dofCount; ++ind) // { // const Cm::SpatialVectorF& sa = motionMatrix[ind]; // const PxReal stZ = sa.innerProduct(Z); // temp += isInvD.isInvD[ind] * stZ; // } // //parent space's spatial zero acceleration impulse // return childToParent * (Z - temp); //} Cm::SpatialVectorF FeatherstoneArticulation::propagateImpulseW( const PxVec3& childToParent, const Cm::SpatialVectorF& linkYW, const Cm::SpatialVectorF* jointDofISInvStISW, const Cm::UnAlignedSpatialVector* jointDofMotionMatrixW, const PxU8 dofCount, PxReal* jointDofQStY) { //See Mirtich Figure 5.7 page 141 //Mirtich equivalent: {1 - [(I * s)/(s^T * I * s)] * s^T} * Y //We actually compute: Y - [(I * s)/(s^T * I * s)] * s^T * Y Cm::SpatialVectorF temp = linkYW; for (PxU8 ind = 0; ind < dofCount; ++ind) { //Y - [(I * s)/(s^T * I * s)] * s^T * Y const Cm::UnAlignedSpatialVector& sa = jointDofMotionMatrixW[ind]; const PxReal stZY = -(sa.innerProduct(linkYW)); PX_ASSERT(PxIsFinite(stZY)); temp += jointDofISInvStISW[ind] * stZY; //Accumulate (-s^T * Y) PX_ASSERT(!jointDofQStY || PxIsFinite(jointDofQStY[ind])); if(jointDofQStY) jointDofQStY[ind] += stZY; } //parent space's spatial zero acceleration impulse return FeatherstoneArticulation::translateSpatialVector(childToParent, temp); } Cm::SpatialVectorF FeatherstoneArticulation::getDeltaVWithDeltaJV(const bool fixBase, const PxU32 linkID, const ArticulationData& data, Cm::SpatialVectorF* Z, PxReal* jointVelocities) { Cm::SpatialVectorF deltaV = Cm::SpatialVectorF::Zero(); if (!fixBase) { //velocity change //SpatialMatrix inverseArticulatedInertia = hLinkDatum.spatialArticulatedInertia.getInverse(); const SpatialMatrix& inverseArticulatedInertia = data.mBaseInvSpatialArticulatedInertiaW; deltaV = inverseArticulatedInertia * (-Z[0]); } ArticulationLink* links = data.getLinks(); const ArticulationLink& link = links[linkID]; const PxU32* pathToRoot = &data.mPathToRootElements[link.mPathToRootStartIndex]; const PxU32 numElems = link.mPathToRootCount; for (PxU32 i = 0; i < numElems; ++i) { const PxU32 index = pathToRoot[i]; PX_ASSERT(links[index].parent < index); ArticulationJointCoreData& tJointDatum = data.getJointData(index); PxReal* jVelocity = &jointVelocities[tJointDatum.jointOffset]; deltaV = FeatherstoneArticulation::propagateVelocityW(data.getRw(index), data.mWorldSpatialArticulatedInertia[index], data.mInvStIs[index], &data.mWorldMotionMatrix[tJointDatum.jointOffset], Z[index], jVelocity, deltaV, tJointDatum.dof); } return deltaV; } void FeatherstoneArticulation::getZ(const PxU32 linkID, const ArticulationData& data, Cm::SpatialVectorF* Z, const Cm::SpatialVectorF& impulse) { ArticulationLink* links = data.getLinks(); //impulse need to be in linkID space!!! Z[linkID] = -impulse; for (PxU32 i = linkID; i; i = links[i].parent) { ArticulationLink& tLink = links[i]; const PxU32 jointOffset = data.getJointData(i).jointOffset; const PxU8 dofCount = data.getJointData(i).dof; Z[tLink.parent] = FeatherstoneArticulation::propagateImpulseW( data.getRw(i), Z[i], &data.mISInvStIS[jointOffset], &data.mWorldMotionMatrix[jointOffset], dofCount); } } Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseW( const PxU32 linkID, const ArticulationData& data, const Cm::SpatialVectorF& impulse) { return data.getImpulseResponseMatrixWorld()[linkID].getResponse(impulse); } //This method use in impulse self response. The input impulse is in the link space Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseWithJ( const PxU32 linkID, const bool fixBase, const ArticulationData& data, Cm::SpatialVectorF* Z, const Cm::SpatialVectorF& impulse, PxReal* jointVelocites) { getZ(linkID, data, Z, impulse); return getDeltaVWithDeltaJV(fixBase, linkID, data, Z, jointVelocites); } void FeatherstoneArticulation::saveVelocity(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* deltaV) { ArticulationData& data = articulation->mArticulationData; //update all links' motion velocity, joint delta velocity if there are contacts/constraints if (data.mJointDirty) { bool doForces = (data.getArticulationFlags() & PxArticulationFlag::eCOMPUTE_JOINT_FORCES) || data.getSensorCount(); PxcFsFlushVelocity(*articulation, deltaV, doForces); } const PxU32 linkCount = data.getLinkCount(); //copy motion velocites Cm::SpatialVectorF* vels = data.getMotionVelocities(); Cm::SpatialVectorF* posVels = data.getPosIterMotionVelocities(); PxMemCopy(posVels, vels, sizeof(Cm::SpatialVectorF) * linkCount); //copy joint velocities const PxU32 dofs = data.getDofs(); PxReal* jPosVels = data.getPosIterJointVelocities(); const PxReal* jNewVels = data.getJointNewVelocities(); PxMemCopy(jPosVels, jNewVels, sizeof(PxReal) * dofs); articulation->concludeInternalConstraints(false); /* for (PxU32 i = 0; i < dofs; ++i) { PX_ASSERT(PxAbs(jPosDeltaVels[i]) < 30.f); }*/ } void FeatherstoneArticulation::saveVelocityTGS(FeatherstoneArticulation* articulation, PxReal invDtF32) { ArticulationData& data = articulation->mArticulationData; //KS - we should not need to flush velocity because we will have already stepped the articulation with TGS const PxU32 linkCount = data.getLinkCount(); Cm::SpatialVectorF* posVels = data.getPosIterMotionVelocities(); for (PxU32 i = 0; i < linkCount; ++i) { posVels[i] = posVels[i] * invDtF32; } } void FeatherstoneArticulation::getImpulseSelfResponse( PxU32 linkID0, PxU32 linkID1, Cm::SpatialVectorF* Z, const Cm::SpatialVector& impulse0, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV0, Cm::SpatialVector& deltaV1) const { FeatherstoneArticulation::getImpulseSelfResponse(mArticulationData.getLinks(), Z, const_cast<Dy::ArticulationData&>(mArticulationData), linkID0, reinterpret_cast<const Cm::SpatialVectorV&>(impulse0), reinterpret_cast<Cm::SpatialVectorV&>(deltaV0), linkID1, reinterpret_cast<const Cm::SpatialVectorV&>(impulse1), reinterpret_cast<Cm::SpatialVectorV&>(deltaV1)); } void FeatherstoneArticulation::getImpulseResponseSlow(Dy::ArticulationLink* links, ArticulationData& data, PxU32 linkID0_, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxU32 linkID1_, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, Cm::SpatialVectorF* /*Z*/) { const PxU32 linkCount = data.getLinkCount(); PX_ALLOCA(_stack, PxU32, linkCount); PxU32* stack = _stack; PxU32 i0, i1;//, ic; PxU32 linkID0 = linkID0_; PxU32 linkID1 = linkID1_; for (i0 = linkID0, i1 = linkID1; i0 != i1;) // find common path { if (i0<i1) i1 = links[i1].parent; else i0 = links[i0].parent; } PxU32 common = i0; Cm::SpatialVectorF Z0(-impulse0.linear, -impulse0.angular); Cm::SpatialVectorF Z1(-impulse1.linear, -impulse1.angular); PxReal qstZ[192]; PxMemZero(qstZ, data.getDofs() * sizeof(PxReal)); //Z[linkID0] = Z0; //Z[linkID1] = Z1; for (i0 = 0; linkID0 != common; linkID0 = links[linkID0].parent) { const PxU32 jointOffset = data.getJointData(linkID0).jointOffset; const PxU8 dofCount = data.getJointData(linkID0).dof; Z0 = FeatherstoneArticulation::propagateImpulseW( data.getRw(linkID0), Z0, &data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset), dofCount, &qstZ[jointOffset]); stack[i0++] = linkID0; } for (i1 = i0; linkID1 != common; linkID1 = links[linkID1].parent) { const PxU32 jointOffset = data.getJointData(linkID1).jointOffset; const PxU8 dofCount = data.getJointData(linkID1).dof; Z1 = FeatherstoneArticulation::propagateImpulseW( data.getRw(linkID1), Z1, &data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset), dofCount, &qstZ[jointOffset]); stack[i1++] = linkID1; } Cm::SpatialVectorF ZZ = Z0 + Z1; Cm::SpatialVectorF v = data.getImpulseResponseMatrixWorld()[common].getResponse(-ZZ); Cm::SpatialVectorF dv1 = v; for (PxU32 index = i1; (index--) > i0;) { //Dy::ArticulationLinkData& tLinkDatum = data.getLinkData(stack[index]); const PxU32 id = stack[index]; const PxU32 jointOffset = data.getJointData(id).jointOffset; const PxU32 dofCount = data.getJointData(id).dof; dv1 = propagateAccelerationW(data.getRw(id), data.mInvStIs[id], &data.mWorldMotionMatrix[jointOffset], dv1, dofCount, &data.mIsW[jointOffset], &qstZ[jointOffset]); } Cm::SpatialVectorF dv0= v; for (PxU32 index = i0; (index--) > 0;) { const PxU32 id = stack[index]; const PxU32 jointOffset = data.getJointData(id).jointOffset; const PxU32 dofCount = data.getJointData(id).dof; dv0 = propagateAccelerationW(data.getRw(id), data.mInvStIs[id], &data.mWorldMotionMatrix[jointOffset], dv0, dofCount, &data.mIsW[jointOffset], &qstZ[jointOffset]); } deltaV0.linear = dv0.bottom; deltaV0.angular = dv0.top; deltaV1.linear = dv1.bottom; deltaV1.angular = dv1.top; } void FeatherstoneArticulation::getImpulseSelfResponse(ArticulationLink* links, Cm::SpatialVectorF* Z, ArticulationData& data, PxU32 linkID0, const Cm::SpatialVectorV& impulse0, Cm::SpatialVectorV& deltaV0, PxU32 linkID1, const Cm::SpatialVectorV& impulse1, Cm::SpatialVectorV& deltaV1) { ArticulationLink& link = links[linkID1]; if (link.parent == linkID0) { PX_ASSERT(linkID0 == link.parent); PX_ASSERT(linkID0 < linkID1); //impulse is in world space Cm::SpatialVectorF imp1; V4StoreA(Vec4V_From_Vec3V(impulse1.angular), &imp1.bottom.x); V4StoreA(Vec4V_From_Vec3V(impulse1.linear), &imp1.top.x); Cm::SpatialVectorF imp0; V4StoreA(Vec4V_From_Vec3V(impulse0.angular), &imp0.bottom.x); V4StoreA(Vec4V_From_Vec3V(impulse0.linear), &imp0.top.x); Cm::SpatialVectorF Z1W(-imp1.top, -imp1.bottom); const PxU32 jointOffset1 = data.getJointData(linkID1).jointOffset; const PxU8 dofCount1 = data.getJointData(linkID1).dof; PxReal qstZ[3] = { 0.f, 0.f, 0.f }; const Cm::SpatialVectorF Z0W = FeatherstoneArticulation::propagateImpulseW( data.getRw(linkID1), Z1W, &data.mISInvStIS[jointOffset1], &data.mWorldMotionMatrix[jointOffset1], dofCount1, qstZ); //in parent space const Cm::SpatialVectorF impulseDifW = imp0 - Z0W; //calculate velocity change start from the parent link to the root const Cm::SpatialVectorF delV0W = FeatherstoneArticulation::getImpulseResponseW(linkID0, data, impulseDifW); //calculate velocity change for child link /*const Cm::SpatialVectorF delV1W = FeatherstoneArticulation::propagateVelocityTestImpulseW(data.getLinkData(linkID1).rw, data.mWorldSpatialArticulatedInertia[linkID1], data.mInvStIs[linkID1], &data.mWorldMotionMatrix[jointOffset1], Z1W, delV0W, dofCount1);*/ const Cm::SpatialVectorF delV1W = propagateAccelerationW(data.getRw(linkID1), data.mInvStIs[linkID1], &data.mWorldMotionMatrix[jointOffset1], delV0W, dofCount1, &data.mIsW[jointOffset1], qstZ); deltaV0.linear = Vec3V_From_Vec4V(V4LoadA(&delV0W.bottom.x)); deltaV0.angular = Vec3V_From_Vec4V(V4LoadA(&delV0W.top.x)); deltaV1.linear = Vec3V_From_Vec4V(V4LoadA(&delV1W.bottom.x)); deltaV1.angular = Vec3V_From_Vec4V(V4LoadA(&delV1W.top.x)); } else { getImpulseResponseSlow(links, data, linkID0, reinterpret_cast<const Cm::SpatialVector&>(impulse0), reinterpret_cast<Cm::SpatialVector&>(deltaV0), linkID1, reinterpret_cast<const Cm::SpatialVector&>(impulse1), reinterpret_cast<Cm::SpatialVector&>(deltaV1), Z); } } struct ArticulationStaticConstraintSortPredicate { bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const { PxU32 linkIndexA = left.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? left.linkIndexA : left.linkIndexB; PxU32 linkIndexB = right.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? right.linkIndexA : right.linkIndexB; return linkIndexA < linkIndexB; } }; bool createFinalizeSolverContactsStep(PxTGSSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal invTotalDt, const PxReal totalDt, const PxReal stepDt, const PxReal bounceThresholdF32, const PxReal frictionOffsetThreshold, const PxReal correlationDistance, const PxReal biasCoefficient, PxConstraintAllocator& constraintAllocator); void FeatherstoneArticulation::prepareStaticConstraintsTGS(const PxReal stepDt, const PxReal totalDt, const PxReal invStepDt, const PxReal invTotalDt, PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxTGSSolverBodyData* solverBodyData, PxTGSSolverBodyTxInertia* txInertia, PxsConstraintBlockManager& blockManager, Dy::ConstraintWriteback* constraintWritebackPool, const PxReal biasCoefficient, const PxReal lengthScale) { BlockAllocator blockAllocator(blockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize); const PxTransform id(PxIdentity); PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStatic1DConstraints.begin(), mStatic1DConstraints.size(), ArticulationStaticConstraintSortPredicate()); PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStaticContactConstraints.begin(), mStaticContactConstraints.size(), ArticulationStaticConstraintSortPredicate()); for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[i]; PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB; PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D); const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint); SolverConstraintShaderPrepDesc shaderPrepDesc; PxTGSSolverConstraintPrepDesc prepDesc; const PxConstraintSolverPrep solverPrep = constraint->solverPrep; const void* constantBlock = constraint->constantBlock; const PxU32 constantBlockByteSize = constraint->constantBlockSize; const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id); const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id); const PxTGSSolverBodyVel* sbody0 = desc.tgsBodyA; const PxTGSSolverBodyVel* sbody1 = desc.tgsBodyB; PxTGSSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyADataIndex]; PxTGSSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyBDataIndex]; PxTGSSolverBodyTxInertia& txI0 = txInertia[desc.bodyADataIndex]; PxTGSSolverBodyTxInertia& txI1 = txInertia[desc.bodyBDataIndex]; shaderPrepDesc.constantBlock = constantBlock; shaderPrepDesc.constantBlockByteSize = constantBlockByteSize; shaderPrepDesc.constraint = constraint; shaderPrepDesc.solverPrep = solverPrep; prepDesc.desc = static_cast<PxSolverConstraintDesc*>(&desc); prepDesc.bodyFrame0 = pose0; prepDesc.bodyFrame1 = pose1; prepDesc.body0 = sbody0; prepDesc.body1 = sbody1; prepDesc.body0TxI = &txI0; prepDesc.body1TxI = &txI1; prepDesc.bodyData0 = sbodyData0; prepDesc.bodyData1 = sbodyData1; prepDesc.linBreakForce = constraint->linBreakForce; prepDesc.angBreakForce = constraint->angBreakForce; prepDesc.writeback = &constraintWritebackPool[constraint->index]; setupConstraintFlags(prepDesc, constraint->flags); prepDesc.minResponseThreshold = constraint->minResponseThreshold; prepDesc.bodyState0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION; prepDesc.bodyState1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION; SetupSolverConstraintStep(shaderPrepDesc, prepDesc, blockAllocator, stepDt, totalDt, invStepDt, invTotalDt, lengthScale, biasCoefficient); if (desc.constraint) { if (mArticulationData.mNbStatic1DConstraints[linkIndex] == 0) mArticulationData.mStatic1DConstraintStartIndex[linkIndex] = i; mArticulationData.mNbStatic1DConstraints[linkIndex]++; } else { //Shuffle down mStatic1DConstraints.remove(i); i--; } } for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[i]; PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB; PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT); PxTGSSolverContactDesc blockDesc; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); PxcNpWorkUnit& unit = cm->getWorkUnit(); PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex); PxTGSSolverBodyVel& b0 = *desc.tgsBodyA; PxTGSSolverBodyVel& b1 = *desc.tgsBodyB; PxTGSSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex]; PxTGSSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex]; PxTGSSolverBodyTxInertia& txI0 = txInertia[desc.bodyADataIndex]; PxTGSSolverBodyTxInertia& txI1 = txInertia[desc.bodyBDataIndex]; blockDesc.bodyFrame0 = unit.rigidCore0->body2World; blockDesc.bodyFrame1 = unit.rigidCore1->body2World; blockDesc.shapeInteraction = cm->getShapeInteraction(); blockDesc.contactForces = cmOutput->contactForces; blockDesc.desc = static_cast<PxSolverConstraintDesc*>(&desc); blockDesc.body0 = &b0; blockDesc.body1 = &b1; blockDesc.body0TxI = &txI0; blockDesc.body1TxI = &txI1; blockDesc.bodyData0 = &data0; blockDesc.bodyData1 = &data1; blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD); blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION); blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY; blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? PxSolverContactDesc::eARTICULATION : (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY : ((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY); //blockDesc.flags = unit.flags; PxReal maxImpulse0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : data0.maxContactImpulse; PxReal maxImpulse1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : data1.maxContactImpulse; PxReal dominance0 = unit.dominance0 ? 1.f : 0.f; PxReal dominance1 = unit.dominance1 ? 1.f : 0.f; blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0; blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1; blockDesc.restDistance = unit.restDistance; blockDesc.frictionPtr = unit.frictionDataPtr; blockDesc.frictionCount = unit.frictionPatchCount; blockDesc.maxCCDSeparation = PX_MAX_F32; blockDesc.maxImpulse = PxMin(maxImpulse0, maxImpulse1); blockDesc.torsionalPatchRadius = unit.mTorsionalPatchRadius; blockDesc.minTorsionalPatchRadius = unit.mMinTorsionalPatchRadius; blockDesc.offsetSlop = unit.mOffsetSlop; createFinalizeSolverContactsStep(blockDesc, *cmOutput, threadContext, invStepDt, invTotalDt, totalDt, stepDt, bounceThreshold, frictionOffsetThreshold, correlationDist, biasCoefficient, blockAllocator); getContactManagerConstraintDesc(*cmOutput, *cm, desc); unit.frictionDataPtr = blockDesc.frictionPtr; unit.frictionPatchCount = blockDesc.frictionCount; //KS - Don't track this for now! //axisConstraintCount += blockDesc.axisConstraintCount; if (desc.constraint) { if (mArticulationData.mNbStaticContactConstraints[linkIndex] == 0) mArticulationData.mStaticContactConstraintStartIndex[linkIndex] = i; mArticulationData.mNbStaticContactConstraints[linkIndex]++; } else { //Shuffle down mStaticContactConstraints.remove(i); i--; } } } void FeatherstoneArticulation::prepareStaticConstraints(const PxReal dt, const PxReal invDt, PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal correlationDist, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxReal ccdMaxSeparation, PxSolverBodyData* solverBodyData, PxsConstraintBlockManager& blockManager, Dy::ConstraintWriteback* constraintWritebackPool) { BlockAllocator blockAllocator(blockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize); const PxTransform id(PxIdentity); Cm::SpatialVectorF* Z = threadContext.mZVector.begin(); PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStatic1DConstraints.begin(), mStatic1DConstraints.size(), ArticulationStaticConstraintSortPredicate()); PxSort<PxSolverConstraintDesc, ArticulationStaticConstraintSortPredicate>(mStaticContactConstraints.begin(), mStaticContactConstraints.size(), ArticulationStaticConstraintSortPredicate()); for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[i]; PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB; PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D); const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint); SolverConstraintShaderPrepDesc shaderPrepDesc; PxSolverConstraintPrepDesc prepDesc; const PxConstraintSolverPrep solverPrep = constraint->solverPrep; const void* constantBlock = constraint->constantBlock; const PxU32 constantBlockByteSize = constraint->constantBlockSize; const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id); const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id); const PxSolverBody* sbody0 = desc.bodyA; const PxSolverBody* sbody1 = desc.bodyB; PxSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyADataIndex]; PxSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? 0 : desc.bodyBDataIndex]; shaderPrepDesc.constantBlock = constantBlock; shaderPrepDesc.constantBlockByteSize = constantBlockByteSize; shaderPrepDesc.constraint = constraint; shaderPrepDesc.solverPrep = solverPrep; prepDesc.desc = &desc; prepDesc.bodyFrame0 = pose0; prepDesc.bodyFrame1 = pose1; prepDesc.data0 = sbodyData0; prepDesc.data1 = sbodyData1; prepDesc.body0 = sbody0; prepDesc.body1 = sbody1; prepDesc.linBreakForce = constraint->linBreakForce; prepDesc.angBreakForce = constraint->angBreakForce; prepDesc.writeback = &constraintWritebackPool[constraint->index]; setupConstraintFlags(prepDesc, constraint->flags); prepDesc.minResponseThreshold = constraint->minResponseThreshold; SetupSolverConstraint(shaderPrepDesc, prepDesc, blockAllocator, dt, invDt, Z); if (desc.constraint) { if (mArticulationData.mNbStatic1DConstraints[linkIndex] == 0) mArticulationData.mStatic1DConstraintStartIndex[linkIndex] = i; mArticulationData.mNbStatic1DConstraints[linkIndex]++; } else { //Shuffle down mStatic1DConstraints.remove(i); i--; } } for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[i]; PxU32 linkIndex = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? desc.linkIndexA : desc.linkIndexB; PX_ASSERT(desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT); PxSolverContactDesc blockDesc; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); PxcNpWorkUnit& unit = cm->getWorkUnit(); PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex); PxSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex]; PxSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex]; blockDesc.data0 = &data0; blockDesc.data1 = &data1; PxU8 flags = unit.rigidCore0->mFlags; if (unit.rigidCore1) flags |= PxU8(unit.rigidCore1->mFlags); blockDesc.bodyFrame0 = unit.rigidCore0->body2World; blockDesc.bodyFrame1 = unit.rigidCore1 ? unit.rigidCore1->body2World : id; blockDesc.shapeInteraction = cm->getShapeInteraction(); blockDesc.contactForces = cmOutput->contactForces; blockDesc.desc = &desc; blockDesc.body0 = desc.bodyA; blockDesc.body1 = desc.bodyB; blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD); blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION); blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY; blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? PxSolverContactDesc::eARTICULATION : (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY : ((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY); //blockDesc.flags = unit.flags; PxReal dominance0 = unit.dominance0 ? 1.f : 0.f; PxReal dominance1 = unit.dominance1 ? 1.f : 0.f; blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0; blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1; blockDesc.restDistance = unit.restDistance; blockDesc.frictionPtr = unit.frictionDataPtr; blockDesc.frictionCount = unit.frictionPatchCount; blockDesc.maxCCDSeparation = (flags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) ? ccdMaxSeparation : PX_MAX_F32; blockDesc.offsetSlop = unit.mOffsetSlop; createFinalizeSolverContacts(blockDesc, *cmOutput, threadContext, invDt, dt, bounceThreshold, frictionOffsetThreshold, correlationDist, blockAllocator, Z); getContactManagerConstraintDesc(*cmOutput, *cm, desc); unit.frictionDataPtr = blockDesc.frictionPtr; unit.frictionPatchCount = blockDesc.frictionCount; //KS - Don't track this for now! //axisConstraintCount += blockDesc.axisConstraintCount; if (desc.constraint) { if (mArticulationData.mNbStaticContactConstraints[linkIndex] == 0) mArticulationData.mStaticContactConstraintStartIndex[linkIndex] = i; mArticulationData.mNbStaticContactConstraints[linkIndex]++; } else { mStaticContactConstraints.remove(i); i--; } } } void setupComplexLimit(ArticulationLink* links, Cm::SpatialVectorF* Z, ArticulationData& data, const PxU32 linkID, const PxReal angle, const PxReal lowLimit, const PxReal highLimit, const PxVec3& axis, const PxReal cfm, ArticulationInternalConstraint& complexConstraint, ArticulationInternalLimit& limit) { Cm::SpatialVectorV deltaVA, deltaVB; FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data, links[linkID].parent, Cm::SpatialVector(PxVec3(0), axis), deltaVA, linkID, Cm::SpatialVector(PxVec3(0), -axis), deltaVB); const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA); const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB); const PxReal r0 = deltaV0.angular.dot(axis); const PxReal r1 = deltaV1.angular.dot(axis); const PxReal unitResponse = r0 - r1; const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (cfm + unitResponse) : 0.0f; complexConstraint.row0 = Cm::UnAlignedSpatialVector(PxVec3(0), axis); complexConstraint.row1 = Cm::UnAlignedSpatialVector(PxVec3(0), axis); complexConstraint.deltaVA.top = unsimdRef(deltaVA).angular; complexConstraint.deltaVA.bottom = unsimdRef(deltaVA).linear; complexConstraint.deltaVB.top = unsimdRef(deltaVB).angular; complexConstraint.deltaVB.bottom = unsimdRef(deltaVB).linear; complexConstraint.recipResponse = recipResponse; complexConstraint.response = unitResponse; complexConstraint.isLinearConstraint = true; limit.errorLow = angle - lowLimit; limit.errorHigh = highLimit - angle; limit.lowImpulse = 0.f; limit.highImpulse = 0.f; } void FeatherstoneArticulation::setupInternalConstraintsRecursive( ArticulationLink* links, const PxU32 linkCount, const bool fixBase, ArticulationData& data, Cm::SpatialVectorF* Z, const PxReal stepDt, const PxReal dt, const PxReal invDt, const bool isTGSSolver, const PxU32 linkID, const PxReal maxForceScale) { const ArticulationLink& link = links[linkID]; ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const ArticulationLink& pLink = links[link.parent]; const ArticulationJointCore& j = *link.inboundJoint; //const bool jointDrive = (j.driveType != PxArticulationJointDriveType::eNONE); bool hasFriction = j.frictionCoefficient > 0.f; const PxReal fCoefficient = j.frictionCoefficient * stepDt; const PxU32 limitedRows = jointDatum.limitMask; PxU8 driveRows = 0; for (PxU32 i = 0; i < PxArticulationAxis::eCOUNT; ++i) { if (j.drives[i].maxForce > 0.f && (j.drives[i].stiffness > 0.f || j.drives[i].damping > 0.f)) driveRows++; } const PxU8 frictionRows = hasFriction ? jointDatum.dof : PxU8(0); const PxU8 constraintCount = PxU8(driveRows + frictionRows + limitedRows); if (!constraintCount) { //Skip these constraints... //constraints += jointDatum.dof; jointDatum.dofInternalConstraintMask = 0; } else { const PxReal transmissionForce = data.getTransmittedForce(linkID).magnitude() * fCoefficient; // PT:: tag: scalar transform*transform const PxTransform cA2w = pLink.bodyCore->body2World.transform(j.parentPose); const PxTransform cB2w = link.bodyCore->body2World.transform(j.childPose); const PxU32 parent = link.parent; const PxReal cfm = PxMax(link.cfm, pLink.cfm); //Linear, then angular... PxVec3 driveError(0.f); PxVec3 angles(0.f); PxVec3 row[3]; if (j.jointType == PxArticulationJointType::eSPHERICAL && jointDatum.dof > 1) { //It's a spherical joint. We can't directly work on joint positions with spherical joints, so we instead need to compute the quaternion //and from that compute the joint error projected onto the DOFs. This will yield a rotation that is singularity-free, where the joint //angles match the target joint angles provided provided the angles are within +/- Pi around each axis. Spherical joints do not support //quaternion double cover cases/wide angles. PxVec3 driveAxis(0.f); bool hasAngularDrives = false; PxU32 tmpDofId = 0; for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i) { if (j.motion[i] != PxArticulationMotion::eLOCKED) { const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].driveType != PxArticulationDriveType::eNONE); if (hasDrive) { const PxVec3 axis = data.mMotionMatrix[jointDatum.jointOffset + tmpDofId].top; PxReal target = data.mJointTargetPositions[jointDatum.jointOffset + tmpDofId]; driveAxis += axis * target; hasAngularDrives = true; } tmpDofId++; } } { PxQuat qB2qA = cA2w.q.getConjugate() * cB2w.q; { //Spherical joint drive calculation using 3x child-space Euler angles if (hasAngularDrives) { PxReal angle = driveAxis.normalize(); if (angle < 1e-12f) { driveAxis = PxVec3(1.f, 0.f, 0.f); angle = 0.f; } PxQuat targetQ = PxQuat(angle, driveAxis); if (targetQ.dot(qB2qA) < 0.f) targetQ = -targetQ; driveError = -2.f * (targetQ.getConjugate() * qB2qA).getImaginaryPart(); } for (PxU32 i = 0, tmpDof = 0; i < PxArticulationAxis::eX; ++i) { if (j.motion[i] != PxArticulationMotion::eLOCKED) { angles[i] = data.mJointPosition[j.jointOffset + tmpDof]; row[i] = data.mWorldMotionMatrix[jointDatum.jointOffset + tmpDof].top; tmpDof++; } } } } } else { for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i) { if (j.motion[i] != PxArticulationMotion::eLOCKED) { driveError[i] = data.mJointTargetPositions[j.jointOffset] - data.mJointPosition[j.jointOffset]; angles[i] = data.mJointPosition[j.jointOffset]; row[i] = data.mWorldMotionMatrix[jointDatum.jointOffset].top; } } } PxU32 dofId = 0; PxU8 dofMask = 0; for (PxU32 i = 0; i < PxArticulationAxis::eX; ++i) { if (j.motion[i] != PxArticulationMotion::eLOCKED) { const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].driveType != PxArticulationDriveType::eNONE); if (j.motion[i] == PxArticulationMotion::eLIMITED || hasDrive || frictionRows) { dofMask |= (1 << dofId); //Impulse response vector and axes are common for all constraints on this axis besides locked axis!!! const PxVec3 axis = row[i]; Cm::SpatialVectorV deltaVA, deltaVB; FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data, parent, Cm::SpatialVector(PxVec3(0), axis), deltaVA, linkID, Cm::SpatialVector(PxVec3(0), -axis), deltaVB); const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA); const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB); const PxReal r0 = deltaV0.angular.dot(axis); const PxReal r1 = deltaV1.angular.dot(axis); const PxReal unitResponse = r0 - r1; const PxReal recipResponse = unitResponse <= 0.f ? 0.f : 1.0f / (unitResponse+cfm); const PxU32 count = data.mInternalConstraints.size(); data.mInternalConstraints.forceSize_Unsafe(count + 1); ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count]; constraints->recipResponse = recipResponse; constraints->response = unitResponse; constraints->row0 = Cm::SpatialVectorF(PxVec3(0), axis); constraints->row1 = Cm::SpatialVectorF(PxVec3(0), axis); constraints->deltaVA.top = unsimdRef(deltaVA).angular; constraints->deltaVA.bottom = unsimdRef(deltaVA).linear; constraints->deltaVB.top = unsimdRef(deltaVB).angular; constraints->deltaVB.bottom = unsimdRef(deltaVB).linear; constraints->isLinearConstraint = false; constraints->frictionForce = 0.f; constraints->frictionMaxForce = hasFriction ? transmissionForce : 0.f; constraints->frictionForceCoefficient = isTGSSolver ? 0.f : 1.f; constraints->driveForce = 0.0f; constraints->driveMaxForce = j.drives[i].maxForce * maxForceScale; if(hasDrive) { constraints->setImplicitDriveDesc( computeImplicitDriveParams( j.drives[i].driveType, j.drives[i].stiffness, j.drives[i].damping, isTGSSolver ? stepDt: dt, unitResponse, recipResponse, driveError[i], data.mJointTargetVelocities[j.jointOffset + dofId], isTGSSolver)); } else { constraints->setImplicitDriveDesc(ArticulationImplicitDriveDesc(PxZero)); } if (j.motion[i] == PxArticulationMotion::eLIMITED) { const PxU32 limitCount = data.mInternalLimits.size(); data.mInternalLimits.forceSize_Unsafe(limitCount + 1); ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount]; const PxReal jPos = angles[i]; limits->errorHigh = j.limits[i].high - jPos; limits->errorLow = jPos - j.limits[i].low; limits->lowImpulse = 0.f; limits->highImpulse = 0.f; } } dofId++; } } for (PxU32 i = PxArticulationAxis::eX; i < PxArticulationAxis::eCOUNT; ++i) { if (j.motion[i] != PxArticulationMotion::eLOCKED) { const bool hasDrive = (j.motion[i] != PxArticulationMotion::eLOCKED && j.drives[i].maxForce > 0.f && (j.drives[i].stiffness > 0.f || j.drives[i].damping > 0.f)); if (j.motion[i] == PxArticulationMotion::eLIMITED || hasDrive || frictionRows) { dofMask |= (1 << dofId); //Impulse response vector and axes are common for all constraints on this axis besides locked axis!!! const PxVec3 axis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofId].bottom; const PxVec3 ang0 = (cA2w.p - pLink.bodyCore->body2World.p).cross(axis); const PxVec3 ang1 = (cB2w.p - link.bodyCore->body2World.p).cross(axis); Cm::SpatialVectorV deltaVA, deltaVB; FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data, links[linkID].parent, Cm::SpatialVector(axis, ang0), deltaVA, linkID, Cm::SpatialVector(-axis, -ang1), deltaVB); //Now add in friction rows, then limit rows, then drives... const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA); const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB); const PxReal r0 = deltaV0.linear.dot(axis) + deltaV0.angular.dot(ang0); const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(ang1); const PxReal unitResponse = r0 - r1; //const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse+cfm) : 0.0f; const PxReal recipResponse = 1.0f / (unitResponse + cfm); const PxU32 count = data.mInternalConstraints.size(); data.mInternalConstraints.forceSize_Unsafe(count + 1); ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count]; constraints->response = unitResponse; constraints->recipResponse = recipResponse; constraints->row0 = Cm::SpatialVectorF(axis, ang0); constraints->row1 = Cm::SpatialVectorF(axis, ang1); constraints->deltaVA.top = unsimdRef(deltaVA).angular; constraints->deltaVA.bottom = unsimdRef(deltaVA).linear; constraints->deltaVB.top = unsimdRef(deltaVB).angular; constraints->deltaVB.bottom = unsimdRef(deltaVB).linear; constraints->isLinearConstraint = true; constraints->frictionForce = 0.f; constraints->frictionMaxForce = hasFriction ? transmissionForce : 0.f; constraints->frictionForceCoefficient = isTGSSolver ? 0.f : 1.f; constraints->driveForce = 0.0f; constraints->driveMaxForce = j.drives[i].maxForce * maxForceScale; if(hasDrive) { constraints->setImplicitDriveDesc( computeImplicitDriveParams( j.drives[i].driveType, j.drives[i].stiffness, j.drives[i].damping, isTGSSolver ? stepDt : dt, unitResponse, recipResponse, data.mJointTargetPositions[j.jointOffset + dofId] - data.mJointPosition[j.jointOffset + dofId], data.mJointTargetVelocities[j.jointOffset + dofId], isTGSSolver)); } else { constraints->setImplicitDriveDesc(ArticulationImplicitDriveDesc(PxZero)); } if (j.motion[i] == PxArticulationMotion::eLIMITED) { const PxU32 limitCount = data.mInternalLimits.size(); data.mInternalLimits.forceSize_Unsafe(limitCount + 1); ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount]; const PxReal jPos = data.mJointPosition[j.jointOffset + dofId]; limits->errorHigh = j.limits[i].high - jPos; limits->errorLow = jPos - j.limits[i].low; limits->lowImpulse = 0.f; limits->highImpulse = 0.f; } } dofId++; } } if (jointDatum.limitMask) { for (PxU32 dof = 0; dof < jointDatum.dof; ++dof) { PxU32 i = j.dofIds[dof]; if (j.motion[i] == PxArticulationMotion::eLOCKED) { const PxU32 count = data.mInternalConstraints.size(); data.mInternalConstraints.forceSize_Unsafe(count + 1); ArticulationInternalConstraint* constraints = &data.mInternalConstraints[count]; const PxU32 limitCount = data.mInternalLimits.size(); data.mInternalLimits.forceSize_Unsafe(limitCount + 1); ArticulationInternalLimit* limits = &data.mInternalLimits[limitCount]; const PxVec3 axis = row[i]; PxReal angle = angles[i]; //A locked axis is equivalent to a limit of 0 PxReal low = 0.f; PxReal high = 0.f; setupComplexLimit(links, Z, data, linkID, angle, low, high, axis, cfm, *constraints, *limits++); } } } jointDatum.dofInternalConstraintMask = dofMask; } const PxU32 numChildren = link.mNumChildren; const PxU32 offset = link.mChildrenStartIndex; for (PxU32 i = 0; i < numChildren; ++i) { const PxU32 child = offset + i; setupInternalConstraintsRecursive(links, linkCount, fixBase, data, Z, stepDt, dt, invDt, isTGSSolver, child, maxForceScale); } } void FeatherstoneArticulation::setupInternalSpatialTendonConstraintsRecursive( ArticulationLink* links, ArticulationAttachment* attachments, const PxU32 attachmentCount, const PxVec3& pAttachPoint, const bool fixBase, ArticulationData& data, Cm::SpatialVectorF* Z, const PxReal stepDt, const bool isTGSSolver, const PxU32 attachmentID, const PxReal stiffness, const PxReal damping, const PxReal limitStiffness, const PxReal accumLength, const PxU32 startLink, const PxVec3& startAxis, const PxVec3& startRaXn) { ArticulationAttachment& attachment = attachments[attachmentID]; ArticulationLink& cLink = links[attachment.linkInd]; const PxTransform cBody2World = cLink.bodyCore->body2World; const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset); const PxVec3 cAttachPoint = cBody2World.p + rb; const PxVec3 dif = pAttachPoint - cAttachPoint; const PxReal distanceSq = dif.magnitudeSquared(); const PxReal distance = PxSqrt(distanceSq); const PxReal u = distance * attachment.coefficient + accumLength; const PxU32 childCount = attachment.childCount; if (childCount) { for (ArticulationBitField children = attachment.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); setupInternalSpatialTendonConstraintsRecursive(links, attachments, attachmentCount, cAttachPoint, fixBase, data, Z, stepDt, isTGSSolver, child, stiffness, damping, limitStiffness, u, startLink, startAxis, startRaXn); } } else { const PxVec3 axis = distance > 0.001f ? dif / distance : PxVec3(0.f); const PxVec3 rbXn = rb.cross(axis); Cm::SpatialVectorV deltaVA, deltaVB; FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data, startLink, Cm::SpatialVector(startAxis, startRaXn), deltaVA, attachment.linkInd, Cm::SpatialVector(-axis, -rbXn), deltaVB); const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA); const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB); const PxReal r0 = deltaV0.linear.dot(startAxis) + deltaV0.angular.dot(startRaXn); const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(rbXn); const PxReal unitResponse = (r0 - r1); //const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse + cfm) : 0.0f; //const PxReal recipResponse = unitResponse > DY_ARTICULATION_MIN_RESPONSE ? 1.0f / (unitResponse) : 0.0f; const PxReal recipResponse = 1.0f / (unitResponse + cLink.cfm); const PxU32 count = data.mInternalSpatialTendonConstraints.size(); data.mInternalSpatialTendonConstraints.forceSize_Unsafe(count + 1); ArticulationInternalTendonConstraint* constraint = &data.mInternalSpatialTendonConstraints[count]; attachment.mConstraintInd = PxU16(count); constraint->row0 = Cm::SpatialVectorF(startAxis, startRaXn); constraint->row1 = Cm::SpatialVectorF(axis, rbXn); constraint->linkID0 = startLink; constraint->linkID1 = attachment.linkInd; constraint->recipResponse = recipResponse; const PxReal a = stepDt * (stepDt*stiffness + damping); const PxReal a2 = stepDt * (stepDt*limitStiffness + damping); const PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a * unitResponse) : 0.f; const PxReal x2 = unitResponse > 0.f ? 1.0f / (1.0f + a2 * unitResponse) : 0.f; constraint->velMultiplier = -x * a;// * unitResponse; //constraint->velMultiplier = -x * damping*stepDt; constraint->impulseMultiplier = isTGSSolver ? 1.f : 1.f - x; constraint->biasCoefficient = (-stiffness * x * stepDt);//*unitResponse; constraint->appliedForce = 0.f; constraint->accumulatedLength = u;// + u*0.2f; constraint->restDistance = attachment.restLength; constraint->lowLimit = attachment.lowLimit; constraint->highLimit = attachment.highLimit; constraint->limitBiasCoefficient = (-limitStiffness * x2 * stepDt);//*unitResponse; constraint->limitImpulseMultiplier = isTGSSolver ? 1.f : 1.f - x2; constraint->limitAppliedForce = 0.f; } } void FeatherstoneArticulation::updateSpatialTendonConstraintsRecursive(ArticulationAttachment* attachments, ArticulationData& data, const PxU32 attachmentID, PxReal accumLength, const PxVec3& pAttachPoint) { ArticulationAttachment& attachment = attachments[attachmentID]; //const PxReal restDist = attachment.restDistance; const PxTransform& cBody2World = data.getAccumulatedPoses()[attachment.linkInd]; const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset); const PxVec3 cAttachPoint = cBody2World.p + rb; const PxVec3 dif = pAttachPoint - cAttachPoint; const PxReal distanceSq = dif.magnitudeSquared(); const PxReal distance = PxSqrt(distanceSq); const PxReal u = distance * attachment.coefficient + accumLength; const PxU32 childCount = attachment.childCount; if (childCount) { for (ArticulationBitField children = attachment.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); updateSpatialTendonConstraintsRecursive(attachments, data, child, u, cAttachPoint); } } else { PxU32 index = attachment.mConstraintInd; ArticulationInternalTendonConstraint& constraint = data.mInternalSpatialTendonConstraints[index]; constraint.accumulatedLength = u; } } void FeatherstoneArticulation::setupInternalFixedTendonConstraintsRecursive( ArticulationLink* links, ArticulationTendonJoint* tendonJoints, const bool fixBase, ArticulationData& data, Cm::SpatialVectorF* Z, const PxReal stepDt, const bool isTGSSolver, const PxU32 tendonJointID, const PxReal stiffness, const PxReal damping, const PxReal limitStiffness, const PxU32 startLink, const PxVec3& startAxis, const PxVec3& startRaXn) { ArticulationTendonJoint& tendonJoint = tendonJoints[tendonJointID]; ArticulationLink& cLink = links[tendonJoint.linkInd]; const PxTransform& cBody2World = cLink.bodyCore->body2World; const PxReal cfm = PxMax(cLink.cfm, links[startLink].cfm); ArticulationJointCoreData& jointDatum = data.getJointData(tendonJoint.linkInd); ArticulationJointCore& joint = *cLink.inboundJoint; PxU16 tendonJointAxis = tendonJoint.axis; PX_ASSERT(joint.motion[tendonJointAxis] != PxArticulationMotion::eLOCKED); //Cm::SpatialVector cImpulse; PxU32 dofIndex = joint.invDofIds[tendonJointAxis]; tendonJoint.startJointOffset = PxTo16(jointDatum.jointOffset + dofIndex); ///*PxReal jointPose = jointPositions[jointDatum.jointOffset + dofIndex] * tendonJoint.coefficient; //jointPose += accumulatedJointPose;*/ { PxVec3 axis, rbXn; if (tendonJointAxis < PxArticulationAxis::eX) { const PxVec3 tAxis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofIndex].top; axis = PxVec3(0.f); rbXn = tAxis; } else { // PT:: tag: scalar transform*transform const PxTransform cB2w = cBody2World.transform(joint.childPose); const PxVec3 tAxis = data.mWorldMotionMatrix[jointDatum.jointOffset + dofIndex].bottom; axis = tAxis; rbXn = (cB2w.p - cBody2World.p).cross(axis); } Cm::SpatialVectorV deltaVA, deltaVB; FeatherstoneArticulation::getImpulseSelfResponse(links, Z, data, startLink, Cm::SpatialVector(startAxis, startRaXn), deltaVA, tendonJoint.linkInd, Cm::SpatialVector(-axis, -rbXn), deltaVB); const Cm::SpatialVector& deltaV0 = unsimdRef(deltaVA); const Cm::SpatialVector& deltaV1 = unsimdRef(deltaVB); /*const PxU32 pLinkInd = cLink.parent; printf("(%i, %i) deltaV1(%f, %f, %f, %f, %f, %f)\n", pLinkInd, tendonJoint.linkInd, deltaV1.linear.x, deltaV1.linear.y, deltaV1.linear.z, deltaV1.angular.x, deltaV1.angular.y, deltaV1.angular.z);*/ const PxReal r0 = deltaV0.linear.dot(startAxis) + deltaV0.angular.dot(startRaXn); const PxReal r1 = deltaV1.linear.dot(axis) + deltaV1.angular.dot(rbXn); const PxReal unitResponse = r0 - r1; const PxReal recipResponse = 1.0f / (unitResponse + cfm); const PxU32 count = data.mInternalFixedTendonConstraints.size(); data.mInternalFixedTendonConstraints.forceSize_Unsafe(count + 1); ArticulationInternalTendonConstraint* constraint = &data.mInternalFixedTendonConstraints[count]; tendonJoint.mConstraintInd = PxU16(count); constraint->row0 = Cm::UnAlignedSpatialVector(startAxis, startRaXn); constraint->row1 = Cm::UnAlignedSpatialVector(axis, rbXn); constraint->deltaVA = r0; //We only need to record the change in velocity projected onto the dof for this! constraint->deltaVB = Cm::UnAlignedSpatialVector(deltaV1.angular, deltaV1.linear); constraint->linkID0 = startLink; constraint->linkID1 = tendonJoint.linkInd; constraint->recipResponse = recipResponse; const PxReal a = stepDt * (stepDt*stiffness + damping); const PxReal a2 = stepDt * (stepDt*limitStiffness + damping); PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a * unitResponse) : 0.f; PxReal x2 = unitResponse > 0.f ? 1.0f / (1.0f + a2* unitResponse) : 0.f; constraint->velMultiplier = -x * a;// * unitResponse; constraint->impulseMultiplier = isTGSSolver ? 1.f : 1.f - x; constraint->biasCoefficient = (-stiffness * x * stepDt);//*unitResponse; constraint->appliedForce = 0.f; //constraint->accumulatedLength = jointPose; constraint->limitImpulseMultiplier = isTGSSolver ? 1.f : 1.f - x2; constraint->limitBiasCoefficient = (-limitStiffness * x2 * stepDt);//*unitResponse; constraint->limitAppliedForce = 0.f; /*printf("(%i, %i) r0 %f, r1 %f cmf %f unitResponse %f recipResponse %f a %f x %f\n", pLinkInd, tendonJoint.linkInd, r0, r1, cLink.cfm, unitResponse, recipResponse, a, x);*/ } const PxU32 childCount = tendonJoint.childCount; if (childCount) { for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); setupInternalFixedTendonConstraintsRecursive(links, tendonJoints, fixBase, data, Z, stepDt, isTGSSolver, child, stiffness, damping, limitStiffness, startLink, startAxis, startRaXn); } } } void FeatherstoneArticulation::setupInternalConstraints( ArticulationLink* links, const PxU32 linkCount, const bool fixBase, ArticulationData& data, Cm::SpatialVectorF* Z, PxReal stepDt, PxReal dt, PxReal invDt, bool isTGSSolver) { PX_UNUSED(linkCount); data.mInternalConstraints.forceSize_Unsafe(0); data.mInternalConstraints.reserve(data.getDofs()); data.mInternalLimits.forceSize_Unsafe(0); data.mInternalLimits.reserve(data.getDofs()); const PxReal maxForceScale = data.getArticulationFlags() & PxArticulationFlag::eDRIVE_LIMITS_ARE_FORCES ? dt : 1.f; const PxU32 numChildren = links[0].mNumChildren; const PxU32 offset = links[0].mChildrenStartIndex; for (PxU32 i = 0; i < numChildren; ++i) { const PxU32 child = offset + i; setupInternalConstraintsRecursive(links, linkCount, fixBase, data, Z, stepDt, dt, invDt, isTGSSolver, child, maxForceScale); } PxU32 totalNumAttachments = 0; for (PxU32 i = 0; i < data.mNumSpatialTendons; ++i) { Dy::ArticulationSpatialTendon* tendon = data.mSpatialTendons[i]; totalNumAttachments += tendon->getNumAttachments(); } data.mInternalSpatialTendonConstraints.forceSize_Unsafe(0); data.mInternalSpatialTendonConstraints.reserve(totalNumAttachments); for (PxU32 i = 0; i < data.mNumSpatialTendons; ++i) { Dy::ArticulationSpatialTendon* tendon = data.mSpatialTendons[i]; Dy::ArticulationAttachment* attachments = tendon->getAttachments(); ArticulationAttachment& pAttachment = attachments[0]; //const PxU32 childCount = pAttachment.childCount; //PxReal scale = 1.f/PxReal(childCount); const PxReal coefficient = pAttachment.coefficient; const PxU32 startLink = pAttachment.linkInd; ArticulationLink& pLink = links[startLink]; const PxTransform pBody2World = pLink.bodyCore->body2World; const PxVec3 ra = pBody2World.q.rotate(pAttachment.relativeOffset); const PxVec3 pAttachPoint = pBody2World.p + ra; for (ArticulationAttachmentBitField children = pAttachment.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); ArticulationAttachment& attachment = attachments[child]; ArticulationLink& cLink = links[attachment.linkInd]; const PxTransform cBody2World = cLink.bodyCore->body2World; const PxVec3 rb = cBody2World.q.rotate(attachment.relativeOffset); const PxVec3 cAttachPoint = cBody2World.p + rb; const PxVec3 axis = (pAttachPoint - cAttachPoint).getNormalized(); const PxVec3 raXn = ra.cross(axis); setupInternalSpatialTendonConstraintsRecursive(links, attachments, tendon->getNumAttachments(), pAttachPoint, fixBase, data, Z, stepDt, isTGSSolver, child, tendon->mStiffness, tendon->mDamping, tendon->mLimitStiffness, tendon->mOffset*coefficient, startLink, axis, raXn); } } PxU32 totalNumTendonJoints = 0; for (PxU32 i = 0; i < data.mNumFixedTendons; ++i) { Dy::ArticulationFixedTendon* tendon = data.mFixedTendons[i]; totalNumTendonJoints += tendon->getNumJoints(); } data.mInternalFixedTendonConstraints.forceSize_Unsafe(0); data.mInternalFixedTendonConstraints.reserve(totalNumTendonJoints); for (PxU32 i = 0; i < data.mNumFixedTendons; ++i) { ArticulationFixedTendon* tendon = data.mFixedTendons[i]; ArticulationTendonJoint* tendonJoints = tendon->getTendonJoints(); ArticulationTendonJoint& pTendonJoint = tendonJoints[0]; const PxU32 startLinkInd = pTendonJoint.linkInd; ArticulationLink& pLink = links[startLinkInd]; const PxTransform& pBody2World = pLink.bodyCore->body2World; for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); ArticulationTendonJoint& cTendonJoint = tendonJoints[child]; ArticulationLink& cLink = links[cTendonJoint.linkInd]; ArticulationJointCore* joint = cLink.inboundJoint; PX_ASSERT(joint != NULL); ArticulationJointCoreData* jointDatum = &data.getJointData(cTendonJoint.linkInd); PxU16 tendonJointAxis = cTendonJoint.axis; PX_ASSERT(joint->motion[tendonJointAxis] != PxArticulationMotion::eLOCKED); PxVec3 startAxis, raXn; PxU32 dofIndex = joint->invDofIds[tendonJointAxis]; if (tendonJointAxis < PxArticulationAxis::eX) { const PxVec3 axis = data.mWorldMotionMatrix[jointDatum->jointOffset + dofIndex].top; startAxis = PxVec3(0.f); raXn = axis; } else { // PT:: tag: scalar transform*transform const PxTransform cA2w = pBody2World.transform(joint->parentPose); const PxVec3 axis = data.mWorldMotionMatrix[jointDatum->jointOffset + dofIndex].bottom; const PxVec3 ang0 = (cA2w.p - pBody2World.p).cross(axis); startAxis = axis; raXn = ang0; } setupInternalFixedTendonConstraintsRecursive(links, tendonJoints, fixBase, data, Z, stepDt, isTGSSolver, child, tendon->mStiffness, tendon->mDamping, tendon->mLimitStiffness, startLinkInd, startAxis, raXn); } } } PxU32 FeatherstoneArticulation::setupSolverConstraints( ArticulationLink* links, const PxU32 linkCount, const bool fixBase, ArticulationData& data, Cm::SpatialVectorF* Z, PxU32& acCount) { acCount = 0; setupInternalConstraints(links, linkCount, fixBase, data, Z, data.getDt(), data.getDt(), 1.f / data.getDt(), false); return 0; } PxU32 FeatherstoneArticulation::setupSolverConstraintsTGS(const ArticulationSolverDesc& articDesc, PxReal dt, PxReal invDt, PxReal totalDt, PxU32& acCount, Cm::SpatialVectorF* Z) { PX_UNUSED(dt); PX_UNUSED(totalDt); acCount = 0; FeatherstoneArticulation* thisArtic = static_cast<FeatherstoneArticulation*>(articDesc.articulation); ArticulationLink* links = thisArtic->mArticulationData.getLinks(); const PxU32 linkCount = thisArtic->mArticulationData.getLinkCount(); const bool fixBase = thisArtic->mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; thisArtic->setupInternalConstraints(links, linkCount, fixBase, thisArtic->mArticulationData, Z, dt, totalDt, invDt, true); return 0; } void FeatherstoneArticulation::teleportLinks(ArticulationData& data) { ArticulationLink* links = mArticulationData.getLinks(); ArticulationJointCoreData* jointData = mArticulationData.getJointData(); const PxReal* jointPositions = data.getJointPositions(); const PxU32 linkCount = mArticulationData.getLinkCount(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; const ArticulationJointCoreData& jointDatum = jointData[linkID]; const ArticulationLink& pLink = links[link.parent]; const PxTransform pBody2World = pLink.bodyCore->body2World; const ArticulationJointCore* joint = link.inboundJoint; const PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; PxQuat newParentToChild; PxQuat newWorldQ; PxVec3 r; const PxVec3 childOffset = -joint->childPose.p; const PxVec3 parentOffset = joint->parentPose.p; const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID]; switch (joint->jointType) { case PxArticulationJointType::ePRISMATIC: { newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].bottom; r = e + d + u * jPosition[0]; break; } case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const PxVec3& u = data.mMotionMatrix[jointDatum.jointOffset].top; PxQuat jointRotation = PxQuat(-jPosition[0], u); if (jointRotation.w < 0) //shortest angle. jointRotation = -jointRotation; newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eSPHERICAL: { PxQuat jointRotation(PxIdentity); { PxVec3 axis(0.f); for (PxU32 d = 0; d < jointDatum.dof; ++d) { axis += data.mMotionMatrix[jointDatum.jointOffset + d].top * -jPosition[d]; } PxReal angle = axis.normalize(); jointRotation = angle < 1e-10f ? PxQuat(PxIdentity) : PxQuat(angle, axis); if(jointRotation.w < 0.f) jointRotation = -jointRotation; } newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; break; } case PxArticulationJointType::eFIX: { //this is fix joint so joint don't have velocity newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; break; } default: break; } PxTransform& body2World = link.bodyCore->body2World; body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized(); body2World.p = pBody2World.p + body2World.q.rotate(r); PX_ASSERT(body2World.isSane()); } } void FeatherstoneArticulation::computeLinkVelocities(ArticulationData& data) { ArticulationLink* links = data.getLinks(); const PxU32 linkCount = data.getLinkCount(); Cm::SpatialVectorF* motionVelocities = data.getMotionVelocities(); const PxReal* jointVelocities = data.mJointVelocity.begin(); // sync root motion vel: const PxsBodyCore& rootBodyCore = *links[0].bodyCore; motionVelocities[0].top = rootBodyCore.angularVelocity; motionVelocities[0].bottom = rootBodyCore.linearVelocity; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; PxsBodyCore& bodyCore = *link.bodyCore; PxTransform body2World = bodyCore.body2World; ArticulationLink& plink = links[link.parent]; const PxsBodyCore& pbodyCore = *plink.bodyCore; Cm::SpatialVectorF parentVel(pbodyCore.angularVelocity, pbodyCore.linearVelocity); PxTransform pBody2World = pbodyCore.body2World; const PxVec3 rw = body2World.p - pBody2World.p; Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-rw,parentVel); if (jointVelocities) { ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero(); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { deltaV += data.mMotionMatrix[jointDatum.jointOffset + ind] * jVelocity[ind]; } vel.top += body2World.q.rotate(deltaV.top); vel.bottom += body2World.q.rotate(deltaV.bottom); } bodyCore.linearVelocity = vel.bottom; bodyCore.angularVelocity = vel.top; motionVelocities[linkID] = vel; } } // AD: needed because we define the templated function in a CPP. template void FeatherstoneArticulation::jcalc<false>(ArticulationData& data); template void FeatherstoneArticulation::jcalc<true>(ArticulationData& data); template<bool immediateMode> void FeatherstoneArticulation::jcalc(ArticulationData& data) { const ArticulationLink* links = data.getLinks(); ArticulationJointCoreData* jointData = data.getJointData(); const PxU32 linkCount = data.getLinkCount(); PxU32 totalDof = 0; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationJointCore* joint = link.inboundJoint; ArticulationJointCoreData& jointDatum = jointData[linkID]; PX_CHECK_AND_RETURN(joint->jointType != PxArticulationJointType::eUNDEFINED, "FeatherstoneArticulation::jcalc application need to define valid joint type and motion"); //compute joint dof const PxU32 dof = jointDatum.computeJointDof(joint, data.mJointAxis.begin() + totalDof); joint->setJointFrame(&data.mMotionMatrix[totalDof], &data.mJointAxis[totalDof], mArticulationData.mRelativeQuat[linkID], dof); // AD: only used in immediate mode because we don't have the llArticulation there to write directly. if (immediateMode) { PxReal* PX_RESTRICT jointTargetPositions = data.getJointTargetPositions(); PxReal* PX_RESTRICT jointTargetVelocities = data.getJointTargetVelocities(); for (PxU32 dofId = 0; dofId < dof; ++dofId) { PxU32 id = totalDof + dofId; PxU32 llDofId = joint->dofIds[dofId]; jointTargetPositions[id] = joint->targetP[llDofId]; jointTargetVelocities[id] = joint->targetV[llDofId]; } joint->jointDirtyFlag &= ~(ArticulationJointCoreDirtyFlag::eTARGETPOSE | ArticulationJointCoreDirtyFlag::eTARGETVELOCITY); } jointDatum.setArmature(joint); jointDatum.jointOffset = totalDof; joint->jointOffset = totalDof; totalDof += dof; } if (totalDof != mArticulationData.getDofs()) { mArticulationData.resizeJointData(totalDof); } mArticulationData.setDofs(totalDof); } //compute link's spatial inertia tensor void FeatherstoneArticulation::computeSpatialInertia(ArticulationData& data) { for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID) { const ArticulationLink& link = data.getLink(linkID); //ArticulationLinkData& linkDatum = data.getLinkData(linkID); const PxsBodyCore& core = *link.bodyCore; const PxVec3& ii = core.inverseInertia; const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass; SpatialMatrix& worldArticulatedInertia = data.mWorldSpatialArticulatedInertia[linkID]; //construct inertia matrix const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z)); PxMat33 rot(data.getLink(linkID).bodyCore->body2World.q); worldArticulatedInertia.topLeft = PxMat33(PxZero); worldArticulatedInertia.topRight = PxMat33::createDiagonal(PxVec3(m)); Cm::transformInertiaTensor(inertiaTensor, rot, worldArticulatedInertia.bottomLeft); data.mWorldIsolatedSpatialArticulatedInertia[linkID] = worldArticulatedInertia.bottomLeft; data.mMasses[linkID] = m; } } void FeatherstoneArticulation::computeZ(const ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData) { const Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities; Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors; const Cm::SpatialVector* externalAccels = scratchData.externalAccels; for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID) { ArticulationLink& link = data.getLink(linkID); const PxsBodyCore& core = *link.bodyCore; //const PxTransform& body2World = core.body2World; const PxMat33& I = data.mWorldSpatialArticulatedInertia[linkID].bottomLeft; //construct spatial zero acceleration Cm::SpatialVectorF& z = spatialZAForces[linkID]; //Cm::SpatialVectorF v; //v.top = motionVelocities[linkID].top; //v.bottom = motionVelocities[linkID].bottom; //KS - limit the magnitude of the angular velocity that contributes to the geometric term. This is a //v^2 term and can become unstable if it is too large! Cm::SpatialVectorF v = motionVelocities[linkID]; PxVec3 vA = v.top; PxVec3 gravLinAccel(0.f); if(!core.disableGravity) gravLinAccel = -gravity; PX_ASSERT(core.inverseMass != 0.f); const PxReal m = 1.0f / core.inverseMass; Cm::SpatialVectorF zTmp; zTmp.top = (gravLinAccel * m); zTmp.bottom = vA.cross(I * vA); PX_ASSERT(zTmp.top.isFinite()); PX_ASSERT(zTmp.bottom.isFinite()); if (externalAccels) { const Cm::SpatialVector& externalAccel = externalAccels[linkID]; const PxVec3 exLinAccel = -externalAccel.linear; const PxVec3 exAngAccel = -externalAccel.angular; zTmp.top += (exLinAccel * m); zTmp.bottom += I * exAngAccel; } z = zTmp; } } void FeatherstoneArticulation::computeZD(const ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData) { const Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities; Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors; const Cm::SpatialVector* externalAccels = scratchData.externalAccels; const PxReal dt = data.getDt(); const PxReal invDt = dt < 1e-6f ? PX_MAX_F32 : 1.f / data.mDt; for (PxU32 linkID = 0; linkID < data.getLinkCount(); ++linkID) { ArticulationLink& link = data.getLink(linkID); const PxsBodyCore& core = *link.bodyCore; //const PxTransform& body2World = core.body2World; const PxMat33& I = data.mWorldSpatialArticulatedInertia[linkID].bottomLeft; //construct spatial zero acceleration Cm::SpatialVectorF& z = spatialZAForces[linkID]; //Cm::SpatialVectorF v; //v.top = motionVelocities[linkID].top; //v.bottom = motionVelocities[linkID].bottom; //KS - limit the magnitude of the angular velocity that contributes to the geometric term. This is a //v^2 term and can become unstable if it is too large! Cm::SpatialVectorF v = motionVelocities[linkID]; PxVec3 vA = v.top; PxVec3 gravLinAccel(0.f); if (!core.disableGravity) gravLinAccel = -gravity; PX_ASSERT(core.inverseMass != 0.f); const PxReal m = 1.0f / core.inverseMass; Cm::SpatialVectorF zTmp; zTmp.top = (gravLinAccel * m); zTmp.bottom = vA.cross(I * vA); PX_ASSERT(zTmp.top.isFinite()); PX_ASSERT(zTmp.bottom.isFinite()); if (externalAccels) { const Cm::SpatialVector& externalAccel = externalAccels[linkID]; const PxVec3 exLinAccel = -externalAccel.linear; const PxVec3 exAngAccel = -externalAccel.angular; zTmp.top += (exLinAccel * m); zTmp.bottom += I * exAngAccel; } if (core.linearDamping > 0.f || core.angularDamping > 0.f) { const PxReal linDamp = PxMin(core.linearDamping, invDt); const PxReal angDamp = PxMin(core.angularDamping, invDt); zTmp.top += (v.bottom * linDamp*m) - zTmp.top * linDamp*dt; zTmp.bottom += I * (v.top* angDamp) - zTmp.bottom * angDamp*dt; } const PxReal maxAng = core.maxAngularVelocitySq; const PxReal maxLin = core.maxLinearVelocitySq; const PxReal angMag = v.top.magnitudeSquared(); const PxReal linMag = v.bottom.magnitudeSquared(); if (angMag > maxAng || linMag > maxLin) { if (angMag > maxAng) { const PxReal scale = 1.f - PxSqrt(maxAng) / PxSqrt(angMag); const PxVec3 tmpaccelerationAng = (I * v.top)*scale; zTmp.bottom += tmpaccelerationAng*invDt; } if (linMag > maxLin) { const PxReal scale = 1.f - (PxSqrt(maxLin) / PxSqrt(linMag)); const PxVec3 tmpaccelerationLin = (v.bottom*m*scale); PX_UNUSED(tmpaccelerationLin); zTmp.top += tmpaccelerationLin*invDt; } } z = zTmp; } } //compute coriolis and centrifugal term void FeatherstoneArticulation::computeC(ArticulationData& data, ScratchData& scratchData) { const PxReal* jointVelocities = scratchData.jointVelocities; Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; const PxU32 linkCount = data.getLinkCount(); coriolisVectors[0] = Cm::SpatialVectorF::Zero(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = data.getLink(linkID); const ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; Cm::SpatialVectorF& coriolis = coriolisVectors[linkID]; //const PxTransform& body2World = link.bodyCore->body2World; //transform parent link's angular velocity into current link's body space const PxVec3 pAngular = scratchData.motionVelocities[link.parent].top; PxVec3 torque = pAngular.cross(pAngular.cross(data.getRw(linkID))); //PX_ASSERT(parentAngular.magnitude() < 100.f); PxVec3 force(0.f); if (jointDatum.dof > 0) { Cm::SpatialVectorF relVel(PxVec3(0.f), PxVec3(0.f)); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { //Clamp joint velocity used in coriolis terms to reduce chances of unstable feed-back loops const PxReal jV = jVelocity[ind]; relVel.top += data.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jV; relVel.bottom += data.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jV; } const PxVec3 aVec = relVel.top; force = pAngular.cross(aVec); //compute linear part const PxVec3 lVel = relVel.bottom; const PxVec3 temp1 = 2.f * pAngular.cross(lVel); const PxVec3 temp2 = aVec.cross(lVel); torque += temp1 + temp2; } PX_ASSERT(force.isFinite()); PX_ASSERT(torque.isFinite()); coriolis = Cm::SpatialVectorF(force, torque);//.rotateInv(body2World); } } void FeatherstoneArticulation::computeRelativeTransformC2P( const ArticulationLink* links, const PxU32 linkCount, const ArticulationJointCoreData* jointCoreDatas, const Cm::UnAlignedSpatialVector* jonitDofMotionMatrices, PxTransform* linkAccumulatedPoses, PxVec3* linkRws, Cm::UnAlignedSpatialVector* jointDofMotionMatricesW) { linkAccumulatedPoses[0] = links[0].bodyCore->body2World; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; const PxsBodyCore& bodyCore = *link.bodyCore; const PxU32 jointOffset = jointCoreDatas[linkID].jointOffset; const PxU32 dofCount = jointCoreDatas[linkID].dof; const PxTransform& body2World = bodyCore.body2World; const ArticulationLink& pLink = links[link.parent]; const PxsBodyCore& pBodyCore = *pLink.bodyCore; const PxTransform& pBody2World = pBodyCore.body2World; //const PxTransform tC2P = pBody2World.transformInv(body2World).getNormalized(); linkRws[linkID] =body2World.p - pBody2World.p; const Cm::UnAlignedSpatialVector* motionMatrix = &jonitDofMotionMatrices[jointOffset]; Cm::UnAlignedSpatialVector* worldMotionMatrix = &jointDofMotionMatricesW[jointOffset]; for (PxU32 i = 0; i < dofCount; ++i) { const Cm::UnAlignedSpatialVector worldRow = motionMatrix[i].rotate(body2World); worldMotionMatrix[i] = worldRow; } linkAccumulatedPoses[linkID] = body2World; #if FEATURESTONE_DEBUG { //debug PxMat33 pToC = c2p.getTranspose(); //parentToChild -rR PxMat33 T2 = skewMatrixPR * pToC; PX_ASSERT(SpatialMatrix::isTranspose(linkDatum.childToParent.T, T2)); } #endif } } void FeatherstoneArticulation::computeRelativeTransformC2B(ArticulationData& data) { ArticulationLink* links = data.getLinks(); ArticulationLinkData* linkData = data.getLinkData(); const PxU32 linkCount = data.getLinkCount(); const ArticulationLink& bLink = links[0]; const PxTransform& bBody2World = bLink.bodyCore->body2World; for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationLinkData& linkDatum = linkData[linkID]; const PxsBodyCore& bodyCore = *link.bodyCore; const PxTransform& body2World = bodyCore.body2World; const PxVec3 rw = body2World.p - bBody2World.p;//body space of link i //rotation matrix cToP's inverse is rotation matrix pToC linkDatum.childToBase = rw; } } void FeatherstoneArticulation::getDenseJacobian(PxArticulationCache& cache, PxU32 & nRows, PxU32 & nCols) { //make sure motionMatrix has been set //jcalc(mArticulationData); initializeCommonData(); const PxU32 linkCount = mArticulationData.getLinkCount(); ArticulationLink* links = mArticulationData.getLinks(); #if 0 //Enable this if you want to compare results of this function with results of computeLinkVelocities(). if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getDenseJacobian(): commonInit need to be called first to initialize data!"); return; } PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = mArticulationData.getJointVelocities(); computeLinkVelocities(mArticulationData, scratchData); const ArticulationLink& baseLink = links[0]; PxsBodyCore& core0 = *baseLink.bodyCore; #endif ArticulationLinkData* linkData = mArticulationData.getLinkData(); const PxU32 totalDofs = getDofs(); const PxU32 jointCount = mArticulationData.getLinkCount() - 1; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; //matrix dims is nCols = (fixBase ? 0 : 6) + totalDofs; nRows = (fixBase ? 0 : 6) + jointCount * 6; // auto jacobian = [&](PxU32 row, PxU32 col) -> PxReal & { return cache.denseJacobian[nCols * row + col]; } ; #define jacobian(row, col) cache.denseJacobian[nCols * (row) + (col)] PxU32 destRow = 0; PxU32 destCol = 0; if (!fixBase) { jacobian(0, 0) = 1.0f; jacobian(0, 1) = 0.0f; jacobian(0, 2) = 0.0f; jacobian(0, 3) = 0.0f; jacobian(0, 4) = 0.0f; jacobian(0, 5) = 0.0f; jacobian(1, 0) = 0.0f; jacobian(1, 1) = 1.0f; jacobian(1, 2) = 0.0f; jacobian(1, 3) = 0.0f; jacobian(1, 4) = 0.0f; jacobian(1, 5) = 0.0f; jacobian(2, 0) = 0.0f; jacobian(2, 1) = 0.0f; jacobian(2, 2) = 1.0f; jacobian(2, 3) = 0.0f; jacobian(2, 4) = 0.0f; jacobian(2, 5) = 0.0f; jacobian(3, 0) = 0.0f; jacobian(3, 1) = 0.0f; jacobian(3, 2) = 0.0f; jacobian(3, 3) = 1.0f; jacobian(3, 4) = 0.0f; jacobian(3, 5) = 0.0f; jacobian(4, 0) = 0.0f; jacobian(4, 1) = 0.0f; jacobian(4, 2) = 0.0f; jacobian(4, 3) = 0.0f; jacobian(4, 4) = 1.0f; jacobian(4, 5) = 0.0f; jacobian(5, 0) = 0.0f; jacobian(5, 1) = 0.0f; jacobian(5, 2) = 0.0f; jacobian(5, 3) = 0.0f; jacobian(5, 4) = 0.0f; jacobian(5, 5) = 1.0f; destRow += 6; destCol += 6; } for (PxU32 linkID = 1; linkID < linkCount; ++linkID)//each iteration of this writes 6 rows in the matrix { const ArticulationLink& link = links[linkID]; ArticulationLinkData& linkDatum = linkData[linkID]; const PxsBodyCore& bodyCore = *link.bodyCore; linkDatum.maxPenBias = bodyCore.maxPenBias; const PxTransform& body2World = bodyCore.body2World; const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); const PxU32 parentLinkID = link.parent; if (parentLinkID || !fixBase) { // VR: mArticulationData.getJointData(0) isn't initialized. parentLinkID can be 0 if fixBase is false. //const ArticulationJointCoreData& parentJointDatum = mArticulationData.getJointData(parentLinkID); //const PxU32 parentsFirstDestCol = parentJointDatum.jointOffset + (fixBase ? 0 : 6); //const PxU32 parentsLastDestCol = parentsFirstDestCol + parentJointDatum.dof; const PxU32 parentsLastDestCol = parentLinkID ? mArticulationData.getJointData(parentLinkID).jointOffset + (fixBase ? 0 : 6) + mArticulationData.getJointData(parentLinkID).dof : 6; // VR: With parentLinkID == 0 this expression has two unsigned integer overflows, but the result is still correct. const PxU32 parentsDestRow = (fixBase ? 0 : 6) + (parentLinkID - 1) * 6; for (PxU32 col = 0; col < parentsLastDestCol; col++) { //copy downward the 6 cols from parent const PxVec3 parentAng( jacobian(parentsDestRow + 3, col), jacobian(parentsDestRow + 4, col), jacobian(parentsDestRow + 5, col) ); const PxVec3 parentAngxRw = parentAng.cross(mArticulationData.getRw(linkID)); jacobian(destRow + 0, col) = jacobian(parentsDestRow + 0, col) + parentAngxRw.x; jacobian(destRow + 1, col) = jacobian(parentsDestRow + 1, col) + parentAngxRw.y; jacobian(destRow + 2, col) = jacobian(parentsDestRow + 2, col) + parentAngxRw.z; jacobian(destRow + 3, col) = parentAng.x; jacobian(destRow + 4, col) = parentAng.y; jacobian(destRow + 5, col) = parentAng.z; } for (PxU32 col = parentsLastDestCol; col < destCol; col++) { //fill with zeros. jacobian(destRow + 0, col) = 0.0f; jacobian(destRow + 1, col) = 0.0f; jacobian(destRow + 2, col) = 0.0f; jacobian(destRow + 3, col) = 0.0f; jacobian(destRow + 4, col) = 0.0f; jacobian(destRow + 5, col) = 0.0f; } } //diagonal block: for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { const Cm::UnAlignedSpatialVector& v = mArticulationData.mMotionMatrix[jointDatum.jointOffset + ind]; const PxVec3 ang = body2World.rotate(v.top); const PxVec3 lin = body2World.rotate(v.bottom); jacobian(destRow + 0, destCol) = lin.x; jacobian(destRow + 1, destCol) = lin.y; jacobian(destRow + 2, destCol) = lin.z; jacobian(destRow + 3, destCol) = ang.x; jacobian(destRow + 4, destCol) = ang.y; jacobian(destRow + 5, destCol) = ang.z; destCol++; } //above diagonal block: always zero for (PxU32 col = destCol; col < nCols; col++) { jacobian(destRow + 0, col) = 0.0f; jacobian(destRow + 1, col) = 0.0f; jacobian(destRow + 2, col) = 0.0f; jacobian(destRow + 3, col) = 0.0f; jacobian(destRow + 4, col) = 0.0f; jacobian(destRow + 5, col) = 0.0f; } destRow += 6; } #undef jacobian #if 0 //Enable this if you want to compare results of this function with results of computeLinkVelocities(). PxReal * jointVels = mArticulationData.getJointVelocities();//size is totalDofs PxReal * jointSpaceVelsVector = new PxReal[nCols]; PxReal * worldSpaceVelsVector = new PxReal[nRows]; PxU32 offset = 0; //stack input: if (!fixBase) { jointSpaceVelsVector[0] = core0.linearVelocity[0]; jointSpaceVelsVector[1] = core0.linearVelocity[1]; jointSpaceVelsVector[2] = core0.linearVelocity[2]; jointSpaceVelsVector[3] = core0.angularVelocity[0]; jointSpaceVelsVector[4] = core0.angularVelocity[1]; jointSpaceVelsVector[5] = core0.angularVelocity[2]; offset = 6; } for (PxU32 i = 0; i < totalDofs; i++) jointSpaceVelsVector[i + offset] = jointVels[i]; //multiply: for (PxU32 row = 0; row < nRows; row++) { worldSpaceVelsVector[row] = 0.0f; for (PxU32 col = 0; col < nCols; col++) { worldSpaceVelsVector[row] += jacobian(row, col)*jointSpaceVelsVector[col]; } } //worldSpaceVelsVector should now contain the same result as scratchData.motionVelocities (except for swapped linear/angular vec3 order). delete[] jointSpaceVelsVector; delete[] worldSpaceVelsVector; allocator->free(tempMemory); #endif } void FeatherstoneArticulation::computeLinkStates( const PxF32 dt, const PxReal invLengthScale, const PxVec3& gravity, const bool fixBase, const PxU32 linkCount, const PxTransform* linkAccumulatedPosesW, const Cm::SpatialVector* linkExternalAccelsW, const PxVec3* linkRsW, const Cm::UnAlignedSpatialVector* jointDofMotionMatricesW, const Dy::ArticulationJointCoreData* jointCoreData, Dy::ArticulationLinkData *linkData, Dy::ArticulationLink* links, Cm::SpatialVectorF* jointDofMotionAccelerations, Cm::SpatialVectorF* jointDofMotionVelocities, Cm::SpatialVectorF* linkZAExtForcesW, Cm::SpatialVectorF* linkZAIntForcesW, Cm::SpatialVectorF* linkCoriolisVectorsW, PxMat33* linkIsolatedSpatialArticulatedInertiasW, PxF32* linkMasses, Dy::SpatialMatrix* linkSpatialArticulatedInertiasW, const PxU32 jointDofCount, PxReal* jointDofVelocities, Cm::SpatialVectorF& rootPreMotionVelocityW, PxVec3& comW, PxF32& invSumMass) { PX_UNUSED(jointDofCount); const PxReal invDt = dt < 1e-6f ? PX_MAX_F32 : 1.f / dt; //Initialise motion velocity, motion acceleration and coriolis vector of root link. Cm::SpatialVectorF rootLinkVel; { const Dy::ArticulationLink& baseLink = links[0]; const PxsBodyCore& core0 = *baseLink.bodyCore; rootLinkVel = fixBase ? Cm::SpatialVectorF::Zero() : Cm::SpatialVectorF(core0.angularVelocity, core0.linearVelocity); jointDofMotionVelocities[0] = rootLinkVel; jointDofMotionAccelerations[0] = fixBase ? Cm::SpatialVectorF::Zero() : jointDofMotionAccelerations[0]; linkCoriolisVectorsW[0] = Cm::SpatialVectorF::Zero(); rootPreMotionVelocityW = rootLinkVel; } PxReal ratio = 1.f; if (jointDofVelocities) { for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; const ArticulationJointCoreData& jointDatum = jointCoreData[linkID]; PxReal* jVelocity = &jointDofVelocities[jointDatum.jointOffset]; const PxReal maxJVelocity = link.inboundJoint->maxJointVelocity; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { PxReal jVel = jVelocity[ind]; ratio = (jVel != 0.0f) ? PxMin(ratio, maxJVelocity / PxAbs(jVel)) : ratio; } } } PxReal sumMass = 0.f; PxVec3 COM(0.f); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; ArticulationLinkData& linkDatum = linkData[linkID]; const PxsBodyCore& bodyCore = *link.bodyCore; //Set the maxPemBias and cfm values from bodyCore linkDatum.maxPenBias = bodyCore.maxPenBias; link.cfm = (fixBase && linkID == 0) ? 0.f : bodyCore.cfmScale * invLengthScale; //Read the inertia and mass from bodyCore const PxVec3& ii = bodyCore.inverseInertia; const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z)); const PxReal invMass = bodyCore.inverseMass; const PxReal m = invMass == 0.f ? 0.f : 1.0f / invMass; //Compute the inertia matrix Iw = R * I * Rtranspose //Compute the articulated inertia. PxMat33 Iw; //R * I * Rtranspose SpatialMatrix worldArticulatedInertia; { PxMat33 rot(linkAccumulatedPosesW[linkID].q); Cm::transformInertiaTensor(inertiaTensor, rot, Iw); worldArticulatedInertia.topLeft = PxMat33(PxZero); worldArticulatedInertia.topRight = PxMat33::createDiagonal(PxVec3(m)); worldArticulatedInertia.bottomLeft = Iw; } //Set the articulated inertia, inertia and mass of the link. linkSpatialArticulatedInertiasW[linkID] = worldArticulatedInertia; linkIsolatedSpatialArticulatedInertiasW[linkID] = Iw; linkMasses[linkID] = m; //Accumulate the centre of mass. sumMass += m; COM += linkAccumulatedPosesW[linkID].p * m; Cm::SpatialVectorF vel; if (linkID != 0) { //Propagate spatial velocity of link parent to link's spatial velocity. const Cm::SpatialVectorF pVel = jointDofMotionVelocities[link.parent]; vel = FeatherstoneArticulation::translateSpatialVector(-linkRsW[linkID], pVel); //Propagate joint dof velocities to the link's spatial velocity vector. //Accumulate spatial forces that the joint applies to the link. if (jointDofVelocities) { //The coriolis vector depends on the type of joint and the joint motion matrix. //However, some terms in the coriolis vector are common to all joint types. //Write down the term that is independent of the joint. Cm::SpatialVectorF coriolisVector(PxVec3(PxZero), pVel.top.cross(pVel.top.cross(linkRsW[linkID]))); const ArticulationJointCoreData& jointDatum = jointCoreData[linkID]; if (jointDatum.dof) { //Compute the effect of the joint velocities on the link. PxReal* jVelocity = &jointDofVelocities[jointDatum.jointOffset]; Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero(); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { PxReal jVel = jVelocity[ind] * ratio; deltaV += jointDofMotionMatricesW[jointDatum.jointOffset + ind] * jVel; jVelocity[ind] = jVel; } //Add the effect of the joint velocities to the link. vel.top += deltaV.top; vel.bottom += deltaV.bottom; //Compute the coriolis vector. //mu(i) is the velocity arising from the joint motion: mu(i) = motionMatrix*qdot //where qdot is the joint velocity. //mu(i) is already computed and cached in deltaV. //For the revolute joint we have: //deltaV = {mu(i), mu(i) X d(i)} //coriolis vector += {omega(i-1) X mu(i), 2*omega(i-1) X (mu(i) X d(i)) + mu(i) X (mu(i) X d(i))} //For the prismatic joint we have: //deltaV = {0, mu(i)} //coriolis vector += {0, 2*omega(i-1) X mu(i)} coriolisVector += Cm::SpatialVectorF(pVel.top.cross(deltaV.top), 2.0f*pVel.top.cross(deltaV.bottom) + deltaV.top.cross(deltaV.bottom)); } //TODOGY - if jointVelocities is null we do not appear to set coriolisVectors[linkId] but we do set coriolisVectors[0] linkCoriolisVectorsW[linkID] = coriolisVector; } //PX_ASSERT(vel.top.isFinite() && PxAbs(vel.top.x) < 10000.f && PxAbs(vel.top.y) < 10000.f && PxAbs(vel.top.z) < 10000.f); //PX_ASSERT(vel.bottom.isFinite() && PxAbs(vel.bottom.x) < 10000.f && PxAbs(vel.bottom.y) < 10000.f && PxAbs(vel.bottom.z) < 10000.f); jointDofMotionVelocities[linkID] = vel; } else { vel = rootLinkVel; //Note: we have already set motionVelocities[0] and coriolisVectors[0] so no need to set them again. } //Account for force arising from external accelerations //Account for damping force arising from the velocity and from the velocity that will accumulate from the acceleration terms. //Account for scaling force that will bring velocity back to the maximum allowed velocity if velocity exceed the maximum allowed. //Example for the linear term: //acceleration force = m*(g + extLinAccel) //linVelNew = linVel + (g + extLinAccel)*dt //damping force = -m*linVelNew*linDamp = -m*linVel*linDamp - m*(g + extLinAccel)*linDamp*dt //scaling force = -m*linVel*linScale/dt with linScale = (1.0f - maxLinVel/linVel) //Put it all together // m*(g + extLinAccel)*(1 - linDamp*dt) - m*linVel*(linDamp + linScale/dt) //Bit more reordering: //m*[g + extLinAccel)*(1 - linDamp*dt) - linVel*(linDamp + linScale/dt)] //Zero acceleration means we need to work against change: //-m*[g + extLinAccel)*(1 - linDamp*dt) - linVel*(linDamp + linScale/dt)] Cm::SpatialVectorF zTmp; { const PxVec3 g = bodyCore.disableGravity ? PxVec3(PxZero) : gravity; const PxVec3 extLinAccel = linkExternalAccelsW ? linkExternalAccelsW[linkID].linear : PxVec3(PxZero); const PxF32 lindamp = bodyCore.linearDamping > 0.f ? PxMin(bodyCore.linearDamping, invDt) : 0.0f; const PxF32 linscale = (vel.bottom.magnitudeSquared() > bodyCore.maxLinearVelocitySq) ? (1.0f - (PxSqrt(bodyCore.maxLinearVelocitySq)/PxSqrt(vel.bottom.magnitudeSquared()))): 0.0f; zTmp.top = -(m*((g + extLinAccel)*(1.0f - lindamp*dt) - vel.bottom*(lindamp + linscale*invDt))); } { const PxVec3 extAngAccel = linkExternalAccelsW ? linkExternalAccelsW[linkID].angular : PxVec3(PxZero); const PxF32 angdamp = bodyCore.angularDamping > 0.f ? PxMin(bodyCore.angularDamping, invDt) : 0.0f; const PxF32 angscale = (vel.top.magnitudeSquared() > bodyCore.maxAngularVelocitySq) ? (1.0f - (PxSqrt(bodyCore.maxAngularVelocitySq)/PxSqrt(vel.top.magnitudeSquared()))) : 0.0f; zTmp.bottom = -(Iw*(extAngAccel*(1.0f - angdamp*dt) - vel.top*(angdamp + angscale*invDt))); } linkZAExtForcesW[linkID] = zTmp; //Account for forces arising from internal accelerations. //Note: Mirtich thesis introduces a single spatial zero acceleration force that contains an external [mass*gravity] term and the internal [omega X (Iw *omega)] term. //In Mirtich it looks like this: // [-m_i * g ] // [omega_i * (I_i * omega_i) ] //We split the spatial zero acceleration force into external (above) and internal (below). //The sum of the two (external and internal) correspoinds to Z_i^A in the Mirtich formulation. const Cm::SpatialVectorF zInternal(PxVec3(0.f), vel.top.cross(Iw*vel.top)); linkZAIntForcesW[linkID] = zInternal; } PxReal invMass = 1.f / sumMass; comW = COM * invMass; invSumMass = invMass; } //compute all links velocities void FeatherstoneArticulation::computeLinkVelocities(ArticulationData& data, ScratchData& scratchData) { Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; ArticulationLink* links = data.getLinks(); ArticulationLinkData* linkData = data.getLinkData(); const PxU32 linkCount = data.getLinkCount(); const bool fixBase = data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; //motion velocities has to be in world space to avoid numerical errors caused by space Cm::SpatialVectorF* motionVelocities = scratchData.motionVelocities; Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; PxReal* jointVelocities = scratchData.jointVelocities; const ArticulationLink& baseLink = links[0]; ArticulationLinkData& baseLinkDatum = linkData[0]; PxsBodyCore& core0 = *baseLink.bodyCore; baseLinkDatum.maxPenBias = core0.maxPenBias; if (fixBase) { motionVelocities[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); motionAccelerations[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); } else { motionVelocities[0] = Cm::SpatialVectorF(core0.angularVelocity, core0.linearVelocity); //PX_ASSERT(core0.angularVelocity.isFinite() && PxAbs(core0.angularVelocity.x) < 10000.f && PxAbs(core0.angularVelocity.y) < 10000.f && PxAbs(core0.angularVelocity.z) < 10000.f); //PX_ASSERT(core0.linearVelocity.isFinite() && PxAbs(core0.linearVelocity.x) < 10000.f && PxAbs(core0.linearVelocity.y) < 10000.f && PxAbs(core0.linearVelocity.z) < 10000.f); } coriolisVectors[0] = Cm::SpatialVectorF::Zero(); data.mRootPreMotionVelocity = motionVelocities[0]; //const PxU32 dofCount = data.mDofs; PxReal ratio = 1.f; if (jointVelocities) { for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationJointCoreData& jointDatum = data.getJointData(linkID); PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; const PxReal maxJVelocity = link.inboundJoint->maxJointVelocity; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { PxReal absJvel = PxAbs(jVelocity[ind]); ratio = ratio * absJvel > maxJVelocity ? (maxJVelocity / absJvel) : ratio; } } } for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { const ArticulationLink& link = links[linkID]; ArticulationLinkData& linkDatum = linkData[linkID]; const PxsBodyCore& bodyCore = *link.bodyCore; linkDatum.maxPenBias = bodyCore.maxPenBias; const Cm::SpatialVectorF pVel = motionVelocities[link.parent]; Cm::SpatialVectorF vel = FeatherstoneArticulation::translateSpatialVector(-mArticulationData.getRw(linkID), pVel); const PxTransform& body2World = bodyCore.body2World; if (jointVelocities) { PxVec3 torque = pVel.top.cross(pVel.top.cross(data.getRw(linkID))); ArticulationJointCoreData& jointDatum = data.getJointData(linkID); PxReal* jVelocity = &jointVelocities[jointDatum.jointOffset]; PxVec3 force(0.f); if (jointDatum.dof) { Cm::UnAlignedSpatialVector deltaV = Cm::UnAlignedSpatialVector::Zero(); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { PxReal jVel = jVelocity[ind] * ratio; //deltaV += data.mWorldMotionMatrix[jointDatum.jointOffset + ind] * jVel; deltaV += data.mMotionMatrix[jointDatum.jointOffset+ind].rotate(body2World) * jVel; jVelocity[ind] = jVel; } vel.top += deltaV.top; vel.bottom += deltaV.bottom; const PxVec3 aVec = deltaV.top; force = pVel.top.cross(aVec); //compute linear part const PxVec3 lVel = deltaV.bottom; const PxVec3 temp1 = 2.f * pVel.top.cross(lVel); const PxVec3 temp2 = aVec.cross(lVel); torque += temp1 + temp2; } coriolisVectors[linkID] = Cm::SpatialVectorF(force, torque); } //PX_ASSERT(vel.top.isFinite() && PxAbs(vel.top.x) < 10000.f && PxAbs(vel.top.y) < 10000.f && PxAbs(vel.top.z) < 10000.f); //PX_ASSERT(vel.bottom.isFinite() && PxAbs(vel.bottom.x) < 10000.f && PxAbs(vel.bottom.y) < 10000.f && PxAbs(vel.bottom.z) < 10000.f); motionVelocities[linkID] = vel; } } void solveExtContact(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool doFriction); void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& li0, Vec3V& li1, Vec3V& ai0, Vec3V& ai1); void solveExt1D(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, const Vec3V& linMotion0, const Vec3V& linMotion1, const Vec3V& angMotion0, const Vec3V& angMotion1, const QuatV& rotA, const QuatV& rotB, const PxReal elapsedTimeF32, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1); void solveExtContactStep(const PxSolverConstraintDesc& desc, Vec3V& linVel0, Vec3V& linVel1, Vec3V& angVel0, Vec3V& angVel1, Vec3V& linDelta0, Vec3V& linDelta1, Vec3V& angDelta0, Vec3V& angDelta1, Vec3V& linImpulse0, Vec3V& linImpulse1, Vec3V& angImpulse0, Vec3V& angImpulse1, bool doFriction, const PxReal minPenetration, const PxReal elapsedTimeF32); void solveStaticConstraint(const PxSolverConstraintDesc& desc, Cm::SpatialVectorF& linkV, Cm::SpatialVectorF& impulse, Cm::SpatialVectorF& deltaV, const Cm::SpatialVectorF& motion, const PxQuat& rot, bool isTGS, PxReal elapsedTime, const PxReal minPenetration) { PX_UNUSED(isTGS); PX_UNUSED(elapsedTime); PX_UNUSED(minPenetration); Vec3V linVel = V3LoadA(linkV.bottom); Vec3V angVel = V3LoadA(linkV.top); Vec3V linVel0, linVel1, angVel0, angVel1; Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); if (isTGS) { PxQuat idt(PxIdentity); Vec3V linMotion0, angMotion0, linMotion1, angMotion1; QuatV rotA, rotB; if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY) { linVel0 = linVel; angVel0 = angVel; linMotion0 = V3LoadA(motion.bottom); angMotion0 = V3LoadA(motion.top); rotA = QuatVLoadU(&rot.x); rotB = QuatVLoadU(&idt.x); linVel1 = angVel1 = linMotion1 = angMotion1 = V3Zero(); } else { linVel1 = linVel; angVel1 = angVel; linMotion1 = V3LoadA(motion.bottom); angMotion1 = V3LoadA(motion.top); rotB = QuatVLoadU(&rot.x); rotA = QuatVLoadU(&idt.x); linVel0 = angVel0 = linMotion0 = angMotion0 = V3Zero(); } if (*desc.constraint == DY_SC_TYPE_EXT_CONTACT) { Dy::solveExtContactStep(desc, linVel0, linVel1, angVel0, angVel1, linMotion0, linMotion1, angMotion0, angMotion1, li0, li1, ai0, ai1, true, minPenetration, elapsedTime); } else { Dy::solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, linMotion0, linMotion1, angMotion0, angMotion1, rotA, rotB, elapsedTime, li0, li1, ai0, ai1); } } else { if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY) { linVel0 = linVel; angVel0 = angVel; linVel1 = angVel1 = V3Zero(); } else { linVel1 = linVel; angVel1 = angVel; linVel0 = angVel0 = V3Zero(); } if (*desc.constraint == DY_SC_TYPE_EXT_CONTACT) { Dy::solveExtContact(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1, true); } else { Dy::solveExt1D(desc, linVel0, linVel1, angVel0, angVel1, li0, li1, ai0, ai1); } } Cm::SpatialVectorF newVel, newImp; if (desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY) { V4StoreA(Vec4V_From_Vec3V(linVel0), &newVel.bottom.x); V4StoreA(Vec4V_From_Vec3V(angVel0), &newVel.top.x); V4StoreA(Vec4V_From_Vec3V(li0), &newImp.top.x); V4StoreA(Vec4V_From_Vec3V(ai0), &newImp.bottom.x); } else { V4StoreA(Vec4V_From_Vec3V(linVel1), &newVel.bottom.x); V4StoreA(Vec4V_From_Vec3V(angVel1), &newVel.top.x); V4StoreA(Vec4V_From_Vec3V(li1), &newImp.top.x); V4StoreA(Vec4V_From_Vec3V(ai1), &newImp.bottom.x); } deltaV.top += (newVel.top - linkV.top); deltaV.bottom += (newVel.bottom - linkV.bottom); linkV.top = newVel.top; linkV.bottom = newVel.bottom; impulse -= newImp; } void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext& cache, PxSolverBodyData& bd0, PxSolverBodyData& bd1); void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&, PxSolverBodyData&, PxSolverBodyData&); void writeBackContact(const PxSolverConstraintDesc& desc, SolverContext* cache); void writeBack1D(const PxSolverConstraintDesc& desc); void FeatherstoneArticulation::writebackInternalConstraints(bool isTGS) { SolverContext context; PxSolverBodyData data; for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[i]; PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_1D); if (isTGS) { writeBack1D(static_cast<PxSolverConstraintDesc&>(desc)); } else { writeBack1D(desc, context, data, data); } } for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[i]; PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_CONTACT); if (isTGS) { writeBackContact(static_cast<PxSolverConstraintDesc&>(desc), NULL); } else { writeBackContact(desc, context, data, data); } } } void concludeContact(const PxSolverConstraintDesc& desc, SolverContext& cache); void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& cache); void concludeContact(const PxSolverConstraintDesc& desc); void conclude1DStep(const PxSolverConstraintDesc& desc); void FeatherstoneArticulation::concludeInternalConstraints(bool isTGS) { SolverContext context; for (PxU32 i = 0; i < mStatic1DConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[i]; PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_1D); if (isTGS) { conclude1DStep(desc); } else { conclude1D(desc, context); } } for (PxU32 i = 0; i < mStaticContactConstraints.size(); ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[i]; PX_ASSERT(*desc.constraint == DY_SC_TYPE_EXT_CONTACT); if (isTGS) { concludeContact(desc); } else { concludeContact(desc, context); } } } //Takes and updates jointV, returns deltaF static PxReal solveLimit(ArticulationInternalLimit& limit, PxReal& jointV, const PxReal jointPDelta, const PxReal response, const PxReal recipResponse, const InternalConstraintSolverData& data) { PxReal futureDeltaJointP = jointPDelta + jointV * data.dt; bool limited = false; const PxReal tolerance = 0.f; PxReal deltaF = 0.f; if ((limit.errorLow + jointPDelta) < tolerance || (limit.errorLow + futureDeltaJointP) < tolerance) { PxReal newJointV = jointV; limited = true; if ((limit.errorLow + jointPDelta) < tolerance) { if (!data.isVelIter) newJointV = -(limit.errorLow + jointPDelta) * data.invDt*data.erp; } else newJointV = -(limit.errorLow + jointPDelta) * data.invDt; PxReal deltaV = newJointV - jointV; const PxReal lowImpulse = limit.lowImpulse; deltaF = PxMax(lowImpulse + deltaV * recipResponse, 0.f) - lowImpulse; limit.lowImpulse = lowImpulse + deltaF; } else if ((limit.errorHigh - jointPDelta) < tolerance || (limit.errorHigh - futureDeltaJointP) < tolerance) { PxReal newJointV = jointV; limited = true; if ((limit.errorHigh - jointPDelta) < tolerance) { if (!data.isVelIter) newJointV = (limit.errorHigh - jointPDelta) * data.invDt*data.erp; } else newJointV = (limit.errorHigh - jointPDelta) * data.invDt; PxReal deltaV = newJointV - jointV; const PxReal highImpulse = limit.highImpulse; deltaF = PxMin(highImpulse + deltaV * recipResponse, 0.f) - highImpulse; limit.highImpulse = highImpulse + deltaF; } if (!limited) { const PxReal forceLimit = -jointV*recipResponse; if (jointV > 0.f) { deltaF = PxMax(forceLimit, -limit.lowImpulse); limit.lowImpulse += deltaF; } else { deltaF = PxMin(forceLimit, -limit.highImpulse); limit.highImpulse += deltaF; } } jointV += deltaF * response; return deltaF; } Cm::SpatialVectorF FeatherstoneArticulation::solveInternalJointConstraintRecursive(InternalConstraintSolverData& data, const PxU32 linkID, const Cm::SpatialVectorF& parentDeltaV, const bool isTGS, const bool isVelIter) { //PxU32 linkID = stack[stackSize]; const ArticulationLink* links = mArticulationData.mLinks; const ArticulationLink& link = links[linkID]; //const ArticulationLink& plink = links[link.parent]; ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID); //PxTransform* transforms = mArticulationData.mPreTransform.begin(); PX_UNUSED(linkDatum); const ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); Cm::SpatialVectorF i1(PxVec3(0.f), PxVec3(0.f)); //We know the absolute parentDeltaV from the call to this function so no need to modify it. Cm::SpatialVectorF parentV = parentDeltaV + mArticulationData.mMotionVelocities[link.parent]; Cm::SpatialVectorF parentVelContrib = propagateAccelerationW(mArticulationData.getRw(linkID), mArticulationData.mInvStIs[linkID], &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], parentDeltaV, jointDatum.dof, &mArticulationData.mIsW[jointDatum.jointOffset], &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]); Cm::SpatialVectorF childV = mArticulationData.mMotionVelocities[linkID] + parentVelContrib; Cm::UnAlignedSpatialVector i0(PxVec3(0.f), PxVec3(0.f)); Cm::SpatialVectorF dv1 = parentVelContrib; const PxReal maxJointVel = link.inboundJoint->maxJointVelocity; //If we have any internal constraints to process (parent/child limits/locks/drives) if (jointDatum.dofInternalConstraintMask) { for (PxU32 dof = 0; dof < jointDatum.dof; ++dof) { PxReal deltaF = 0.f; PxReal clampedForce = 0.f; PxU32 internalConstraint = jointDatum.dofInternalConstraintMask & (1 << dof); if (internalConstraint) { ArticulationInternalConstraint& constraint = mArticulationData.mInternalConstraints[data.dofId++]; const PxReal jointPDelta = constraint.row1.innerProduct(mArticulationData.mDeltaMotionVector[linkID]) - constraint.row0.innerProduct(mArticulationData.mDeltaMotionVector[link.parent]); const PxReal frictionForceCoefficient = constraint.frictionForceCoefficient; PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV); const PxReal appliedFriction = constraint.frictionForce * frictionForceCoefficient; PxReal frictionForce = PxClamp(-jointV *constraint.recipResponse + appliedFriction, -constraint.frictionMaxForce, constraint.frictionMaxForce); PxReal frictionDeltaF = frictionForce - appliedFriction; constraint.frictionForce += frictionDeltaF; jointV += frictionDeltaF * constraint.response; PxReal unclampedForce = (isTGS && isVelIter) ? constraint.driveForce : computeDriveImpulse(constraint.driveForce, jointV, jointPDelta, constraint.getImplicitDriveDesc()); clampedForce = PxClamp(unclampedForce, -constraint.driveMaxForce, constraint.driveMaxForce); PxReal driveDeltaF = (clampedForce - constraint.driveForce); //Where we will be next frame - we use this to compute error bias terms to correct limits and drives... jointV += driveDeltaF * constraint.response; driveDeltaF += frictionDeltaF; //printf("LinkID %i driveDeltaV = %f, jointV = %f\n", linkID, driveDeltaF, jointV); if (jointDatum.limitMask & (1 << dof)) { ArticulationInternalLimit& limit = mArticulationData.mInternalLimits[data.limitId++]; deltaF = solveLimit(limit, jointV, jointPDelta, constraint.response, constraint.recipResponse, data); } if (PxAbs(jointV) > maxJointVel) { PxReal newJointV = PxClamp(jointV, -maxJointVel, maxJointVel); deltaF += (newJointV - jointV) * constraint.recipResponse; jointV = newJointV; } deltaF += driveDeltaF; if (deltaF != 0.f) { //impulse = true; constraint.driveForce = clampedForce; i0 += constraint.row0 * deltaF; i1.top -= constraint.row1.top * deltaF; i1.bottom -= constraint.row1.bottom * deltaF; const Cm::UnAlignedSpatialVector deltaVP = constraint.deltaVA * (-deltaF); const Cm::UnAlignedSpatialVector deltaVC = constraint.deltaVB * (-deltaF); parentV += Cm::SpatialVectorF(deltaVP.top, deltaVP.bottom); childV += Cm::SpatialVectorF(deltaVC.top, deltaVC.bottom); dv1.top += deltaVC.top; dv1.bottom += deltaVC.bottom; } } } } //Cache the impulse arising from internal constraints. //We'll subtract this from the total impulse applied later in this function. const Cm::SpatialVectorF i1Internal = i1; const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(linkID); const PxQuat& deltaQ = getDeltaQ(linkID); const PxU32 nbStatic1DConstraints = mArticulationData.mNbStatic1DConstraints[linkID]; PxU32 start1DIdx = mArticulationData.mStatic1DConstraintStartIndex[linkID]; for (PxU32 i = 0; i < nbStatic1DConstraints; ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[start1DIdx++]; solveStaticConstraint( desc, childV, i1, dv1, deltaMotion, deltaQ, data.isTGS, data.elapsedTime, data.isVelIter ? 0.f : -PX_MAX_F32); } const PxU32 nbStaticContactConstraints = mArticulationData.mNbStaticContactConstraints[linkID]; PxU32 startContactIdx = mArticulationData.mStaticContactConstraintStartIndex[linkID]; for (PxU32 i = 0; i < nbStaticContactConstraints; ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[startContactIdx++]; solveStaticConstraint( desc, childV, i1, dv1, deltaMotion, deltaQ, data.isTGS, data.elapsedTime, data.isVelIter ? 0.f : -PX_MAX_F32); } PxU32 numChildren = link.mNumChildren; PxU32 offset = link.mChildrenStartIndex; for(PxU32 i = 0; i < numChildren; ++i) { const PxU32 child = offset+i; Cm::SpatialVectorF childImp = solveInternalJointConstraintRecursive(data, child, dv1, isTGS, isVelIter); i1 += childImp; if ((numChildren-i) > 1) { //Propagate the childImp to my dv1 so that the next constraint gets to see an updated velocity state based //on the propagation of the child velocities Cm::SpatialVectorF deltaV = mArticulationData.mResponseMatrixW[linkID].getResponse(-childImp); dv1 += deltaV; childV += deltaV; } } Cm::SpatialVectorF propagatedImpulseAtParentW; { //const inputs const PxVec3& r = mArticulationData.getRw(linkID); const Cm::SpatialVectorF* jointDofISInvStISW = &mArticulationData.mISInvStIS[jointDatum.jointOffset]; const Cm::UnAlignedSpatialVector* jointDofMotionMatrixW = &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset]; const PxU8 nbDofs = jointDatum.dof; //output PxReal* jointDofDeferredQstZ = &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]; propagatedImpulseAtParentW = propagateImpulseW( r, i1, jointDofISInvStISW, jointDofMotionMatrixW, nbDofs, jointDofDeferredQstZ); } //Accumulate the propagated impulse at the link. //Don't forget to subtract the impulse arising from internal constraints. //This can be used to compute the link's incoming joint force. mArticulationData.mSolverLinkSpatialImpulses[linkID] += (i1 - i1Internal); return Cm::SpatialVectorF(i0.top, i0.bottom) + propagatedImpulseAtParentW; } void FeatherstoneArticulation::solveInternalJointConstraints(const PxReal dt, const PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, bool isVelIter, bool isTGS, const PxReal elapsedTime, const PxReal biasCoefficient) { //const PxU32 count = mArticulationData.getLinkCount(); if (mArticulationData.mInternalConstraints.size() == 0 && mStatic1DConstraints.size() == 0 && mStaticContactConstraints.size() == 0) return; //const PxReal erp = isTGS ? 0.5f*biasCoefficient : biasCoefficient; const PxReal erp = biasCoefficient; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; PxU32* static1DConstraintCounts = mArticulationData.mNbStatic1DConstraints.begin(); PxU32* static1DConstraintStarts = mArticulationData.mStatic1DConstraintStartIndex.begin(); PxU32* staticContactConstraintCounts = mArticulationData.mNbStaticContactConstraints.begin(); PxU32* staticContactConstraintStarts = mArticulationData.mStaticContactConstraintStartIndex.begin(); ArticulationLink* links = mArticulationData.getLinks(); Cm::SpatialVectorF* baseVelocities = mArticulationData.getMotionVelocities(); //PxTransform* transforms = mArticulationData.mPreTransform.begin(); //Cm::SpatialVectorF* deferredZ = mArticulationData.getSpatialZAVectors(); const PxReal minPenetration = isVelIter ? 0.f : -PX_MAX_F32; Cm::SpatialVectorF rootLinkV; { Cm::SpatialVectorF rootLinkDeltaV(PxVec3(0.f), PxVec3(0.f)); if (!fixBase) { //Cm::SpatialVectorF temp = mArticulationData.getBaseInvSpatialArticulatedInertia() * (-deferredZ[0]); //const PxTransform& body2World0 = transforms[0]; //rootLinkDeltaV = temp.rotate(body2World0); //temp is now in world space! rootLinkDeltaV = mArticulationData.getBaseInvSpatialArticulatedInertiaW() * -mArticulationData.mRootDeferredZ; } rootLinkV = rootLinkDeltaV + baseVelocities[0]; Cm::SpatialVectorF im0 = Cm::SpatialVectorF::Zero(); { const PxU32 nbStatic1DConstraints = static1DConstraintCounts[0]; if (nbStatic1DConstraints) { const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(0); const PxQuat& deltaQ = getDeltaQ(0); PxU32 startIdx = static1DConstraintStarts[0]; for (PxU32 i = 0; i < nbStatic1DConstraints; ++i) { PxSolverConstraintDesc& desc = mStatic1DConstraints[startIdx++]; solveStaticConstraint(desc, rootLinkV, im0, rootLinkDeltaV, deltaMotion, deltaQ, isTGS, elapsedTime, minPenetration); } //Impulses and deferredZ are now in world space, not link space! /*im0.top = transforms[0].rotateInv(im0.top); im0.bottom = transforms[0].rotateInv(im0.bottom);*/ } const PxU32 nbStaticContactConstraints = staticContactConstraintCounts[0]; if (nbStaticContactConstraints) { const Cm::SpatialVectorF& deltaMotion = mArticulationData.getDeltaMotionVector(0); const PxQuat& deltaQ = getDeltaQ(0); PxU32 startIdx = staticContactConstraintStarts[0]; for (PxU32 i = 0; i < nbStaticContactConstraints; ++i) { PxSolverConstraintDesc& desc = mStaticContactConstraints[startIdx++]; solveStaticConstraint(desc, rootLinkV, im0, rootLinkDeltaV, deltaMotion, deltaQ, isTGS, elapsedTime, minPenetration); } //Impulses and deferredZ are now in world space, not link space! /*im0.top = transforms[0].rotateInv(im0.top); im0.bottom = transforms[0].rotateInv(im0.bottom);*/ } } InternalConstraintSolverData data(dt, invDt, elapsedTime, erp, impulses, DeltaV, isVelIter, isTGS); data.articId = mArticulationIndex; const PxU32 numChildren = links[0].mNumChildren; const PxU32 offset = links[0].mChildrenStartIndex; for (PxU32 i = 0; i < numChildren; ++i) { const PxU32 child = offset + i; Cm::SpatialVectorF imp = solveInternalJointConstraintRecursive(data, child, rootLinkDeltaV, isTGS, isVelIter); im0 += imp; //There's an impulse, we have to work out how it impacts our velocity (only if required (we have more children to traverse))! if (!fixBase && (numChildren - 1) != 0) { //Impulses and deltaVs are all now in world space rootLinkDeltaV += mArticulationData.getBaseInvSpatialArticulatedInertiaW() * (-imp); } } mArticulationData.mRootDeferredZ += im0; mArticulationData.mJointDirty = true; } } void FeatherstoneArticulation::solveInternalSpatialTendonConstraints(bool isTGS) { if (mArticulationData.mInternalSpatialTendonConstraints.size() == 0) return; if (isTGS) { //Update the error terms in the tendons recursively... const PxU32 nbTendons = mArticulationData.mNumSpatialTendons; for (PxU32 i = 0; i < nbTendons; ++i) { Dy::ArticulationSpatialTendon* tendon = mArticulationData.mSpatialTendons[i]; Dy::ArticulationAttachment& attachment = tendon->getAttachment(0); //const PxU32 childCount = attachment.childCount; //PxReal scale = 1.f / PxReal(childCount); PxReal coefficient = attachment.coefficient; const PxU32 startLink = tendon->getAttachment(0).linkInd; const PxTransform pBody2World = mArticulationData.getAccumulatedPoses()[startLink]; const PxVec3 pAttachPoint = pBody2World.transform(tendon->getAttachment(0).relativeOffset); Dy::ArticulationAttachment* attachments = tendon->getAttachments(); for (ArticulationAttachmentBitField children = attachments[0].children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); updateSpatialTendonConstraintsRecursive(attachments, mArticulationData, child, tendon->mOffset*coefficient, pAttachPoint); } } } for (PxU32 i = 0; i < mArticulationData.mInternalSpatialTendonConstraints.size(); ++i) { ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalSpatialTendonConstraints[i]; const PxU32 parentID = constraint.linkID0; const PxU32 linkID = constraint.linkID1; //Cm::SpatialVectorF childDeltaP = mArticulationData.mDeltaMotionVector[linkID]; //Cm::SpatialVectorF parentDeltaP = mArticulationData.mDeltaMotionVector[parentID]; //PxReal deltaP = constraint.row1.innerProduct(childDeltaP) - constraint.row0.innerProduct(parentDeltaP);// + deltaErr; Cm::SpatialVectorV childVel = pxcFsGetVelocity(linkID); Cm::SpatialVectorV parentVel = pxcFsGetVelocity(parentID); Cm::UnAlignedSpatialVector childV; V3StoreU(childVel.angular, childV.top); V3StoreU(childVel.linear, childV.bottom); Cm::UnAlignedSpatialVector parentV; V3StoreU(parentVel.angular, parentV.top); V3StoreU(parentVel.linear, parentV.bottom); PxReal error = constraint.restDistance - constraint.accumulatedLength;// + deltaP; PxReal error2 = 0.f; if (constraint.accumulatedLength > constraint.highLimit) error2 = constraint.highLimit - constraint.accumulatedLength; if (constraint.accumulatedLength < constraint.lowLimit) error2 = constraint.lowLimit - constraint.accumulatedLength; PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV); PX_ASSERT(PxIsFinite(jointV)); PxReal unclampedForce = (jointV * constraint.velMultiplier + error * constraint.biasCoefficient) /** constraint.recipResponse*/ + constraint.appliedForce * constraint.impulseMultiplier; PxReal unclampedForce2 = (error2 * constraint.limitBiasCoefficient) + constraint.limitAppliedForce * constraint.limitImpulseMultiplier; const PxReal deltaF = (unclampedForce - constraint.appliedForce) + (unclampedForce2 - constraint.limitAppliedForce); constraint.appliedForce = unclampedForce; constraint.limitAppliedForce = unclampedForce2; if (deltaF != 0.f) { Cm::UnAlignedSpatialVector i0 = constraint.row0 * -deltaF; Cm::UnAlignedSpatialVector i1 = constraint.row1 * deltaF; pxcFsApplyImpulses(parentID, V3LoadU(i0.top), V3LoadU(i0.bottom), linkID, V3LoadU(i1.top), V3LoadU(i1.bottom), NULL, NULL); } } } PxVec3 FeatherstoneArticulation::calculateFixedTendonVelocityAndPositionRecursive(FixedTendonSolveData& solveData, const Cm::SpatialVectorF& parentV, const Cm::SpatialVectorF& parentDeltaV, const PxU32 tendonJointID) { ArticulationTendonJoint& tendonJoint = solveData.tendonJoints[tendonJointID]; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(tendonJoint.linkInd); Cm::SpatialVectorF deltaV = propagateAccelerationW(mArticulationData.getRw(tendonJoint.linkInd), mArticulationData.mInvStIs[tendonJoint.linkInd], &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], parentDeltaV, jointDatum.dof, &mArticulationData.mIsW[jointDatum.jointOffset], &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]); Cm::SpatialVectorF childV = mArticulationData.mMotionVelocities[tendonJoint.linkInd] + deltaV; PxU32 index = tendonJoint.mConstraintInd; ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[index]; const PxU32 childCount = tendonJoint.childCount; PxVec3 jointVError; const PxReal jointV = constraint.row1.innerProduct(childV) - constraint.row0.innerProduct(parentV); const PxReal jointP = mArticulationData.mJointPosition[tendonJoint.startJointOffset]; jointVError.x = jointV * tendonJoint.coefficient; jointVError.y = jointP * tendonJoint.coefficient; //printf("%i: jointPose = %f, jointV = %f, coefficient = %f\n", tendonJoint.linkInd, jointP, jointV, tendonJoint.coefficient); jointVError.z = 1.f; if (childCount) { for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); jointVError += calculateFixedTendonVelocityAndPositionRecursive(solveData, childV, deltaV, child); } } return jointVError; } Cm::SpatialVectorF FeatherstoneArticulation::solveFixedTendonConstraintsRecursive(FixedTendonSolveData& solveData, const PxU32 tendonJointID) { ArticulationTendonJoint& tendonJoint = solveData.tendonJoints[tendonJointID]; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(tendonJoint.linkInd); PxU32 index = tendonJoint.mConstraintInd; ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[index]; const PxU32 childCount = tendonJoint.childCount; PxReal jointV = solveData.rootVel; // calculate current accumulated tendon length from parent accumulated length const PxReal lengthError = solveData.error; PxReal limitError = solveData.limitError; // the constraint bias coefficients need to flip signs together with the tendon joint's coefficient // in order for the constraint force to point into the correct direction: const PxReal coefficientSign = tendonJoint.recipCoefficient;// PxSign(tendonJoint.coefficient); const PxReal biasCoefficient = constraint.biasCoefficient; const PxReal limitBiasCoefficient = constraint.limitBiasCoefficient; PxReal unclampedForce = ((jointV * constraint.velMultiplier + lengthError * biasCoefficient)*coefficientSign) + constraint.appliedForce * constraint.impulseMultiplier; PxReal unclampedForce2 = (limitError * limitBiasCoefficient * coefficientSign) + constraint.limitAppliedForce * constraint.limitImpulseMultiplier; const PxReal deltaF = ((unclampedForce - constraint.appliedForce) + (unclampedForce2 - constraint.limitAppliedForce)); constraint.appliedForce = unclampedForce; constraint.limitAppliedForce = unclampedForce2; solveData.rootImp += deltaF; Cm::SpatialVectorF impulse(constraint.row1.top * -deltaF, constraint.row1.bottom * -deltaF); const Cm::SpatialVectorF YInt = impulse; if (childCount) { for (ArticulationBitField children = tendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); Cm::SpatialVectorF propagatedImpulse = solveFixedTendonConstraintsRecursive(solveData, child); impulse.top += propagatedImpulse.top; impulse.bottom += propagatedImpulse.bottom; } } mArticulationData.mSolverLinkSpatialImpulses[tendonJoint.linkInd] += impulse - YInt; return propagateImpulseW( mArticulationData.mRw[tendonJoint.linkInd], impulse, &mArticulationData.mISInvStIS[jointDatum.jointOffset], &mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset], jointDatum.dof, &mArticulationData.mDeferredQstZ[jointDatum.jointOffset]); } void FeatherstoneArticulation::solveInternalFixedTendonConstraints(bool isTGS) { PX_UNUSED(isTGS); if (mArticulationData.mInternalFixedTendonConstraints.size() == 0) return; { //Update the error terms in the tendons recursively... const PxU32 nbTendons = mArticulationData.mNumFixedTendons; ArticulationLink* links = mArticulationData.getLinks(); for (PxU32 i = 0; i < nbTendons; ++i) { Dy::ArticulationFixedTendon* tendon = mArticulationData.mFixedTendons[i]; ArticulationTendonJoint* tendonJoints = tendon->getTendonJoints(); Dy::ArticulationTendonJoint& pTendonJoint = tendonJoints[0]; //const PxU32 childCount = pTendonJoint.childCount; const PxU32 startLink = pTendonJoint.linkInd; Cm::SpatialVectorV parentVel = pxcFsGetVelocity(startLink); Cm::SpatialVectorF parentV; V3StoreU(parentVel.angular, parentV.top); V3StoreU(parentVel.linear, parentV.bottom); Cm::SpatialVectorF Z(PxVec3(0.f), PxVec3(0.f)); Cm::SpatialVectorF parentDeltaV = parentV - mArticulationData.mMotionVelocities[startLink]; PxVec3 velError(0.f); for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); FixedTendonSolveData solveData; solveData.links = links; solveData.erp = 1.f; solveData.rootImp = 0.f; solveData.error = tendon->mError; solveData.tendonJoints = tendonJoints; velError += calculateFixedTendonVelocityAndPositionRecursive(solveData, parentV, parentDeltaV, child); } const PxReal recipScale = velError.z == 0.f ? 0.f : 1.f / velError.z; for (ArticulationAttachmentBitField children = pTendonJoint.children; children != 0; children &= (children - 1)) { //index of child of link h on path to link linkID const PxU32 child = ArticulationLowestSetBit(children); ArticulationTendonJoint& tendonJoint = tendonJoints[child]; ArticulationInternalTendonConstraint& constraint = mArticulationData.mInternalFixedTendonConstraints[tendonJoint.mConstraintInd]; const PxReal length = (velError.y + tendon->mOffset); FixedTendonSolveData solveData; solveData.links = links; solveData.erp = 1.f; solveData.rootImp = 0.f; solveData.error = (length - tendon->mRestLength) * recipScale; solveData.rootVel = velError.x*recipScale; PxReal limitError = 0.f; if (length < tendon->mLowLimit) limitError = length - tendon->mLowLimit; else if (length > tendon->mHighLimit) limitError = length - tendon->mHighLimit; solveData.limitError = limitError * recipScale; solveData.tendonJoints = tendonJoints; //KS - TODO - hook up offsets Cm::SpatialVectorF propagatedImpulse = solveFixedTendonConstraintsRecursive(solveData, child); propagatedImpulse.top += constraint.row0.top * solveData.rootImp; propagatedImpulse.bottom += constraint.row0.bottom * solveData.rootImp; Z += propagatedImpulse; } for (PxU32 linkID = pTendonJoint.linkInd; linkID; linkID = links[linkID].parent) { const PxU32 jointOffset = mArticulationData.getJointData(linkID).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID).dof; Z = propagateImpulseW( mArticulationData.getRw(linkID), Z, &mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount, &mArticulationData.mDeferredQstZ[jointOffset]); } mArticulationData.mRootDeferredZ += Z; mArticulationData.mJointDirty = true; } } } void FeatherstoneArticulation::solveInternalConstraints(const PxReal dt, const PxReal invDt, Cm::SpatialVectorF* impulses, Cm::SpatialVectorF* DeltaV, bool velocityIteration, bool isTGS, const PxReal elapsedTime, const PxReal biasCoefficient) { solveInternalSpatialTendonConstraints(isTGS); solveInternalFixedTendonConstraints(isTGS); solveInternalJointConstraints(dt, invDt, impulses, DeltaV, velocityIteration, isTGS, elapsedTime, biasCoefficient); } bool FeatherstoneArticulation::storeStaticConstraint(const PxSolverConstraintDesc& desc) { if (DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER) { if (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT) mStaticContactConstraints.pushBack(desc); else mStatic1DConstraints.pushBack(desc); } return DY_STATIC_CONTACTS_IN_INTERNAL_SOLVER; } void FeatherstoneArticulation::setRootLinearVelocity(const PxVec3& velocity) { ArticulationLink& rLink = mArticulationData.getLink(0); rLink.bodyCore->linearVelocity = velocity; mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES; computeLinkVelocities(mArticulationData); } void FeatherstoneArticulation::setRootAngularVelocity(const PxVec3& velocity) { ArticulationLink& rLink = mArticulationData.getLink(0); rLink.bodyCore->angularVelocity = velocity; mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES; computeLinkVelocities(mArticulationData); } //This method is for user update the root link transform so we need to //fix up other link's position. In this case, we should assume all joint //velocity/pose is to be zero void FeatherstoneArticulation::teleportRootLink() { //make sure motionMatrix has been set //jcalc(mArticulationData); const PxU32 linkCount = mArticulationData.getLinkCount(); ArticulationLink* links = mArticulationData.getLinks(); PxReal* jointPositions = mArticulationData.getJointPositions(); Cm::SpatialVectorF* motionVelocities = mArticulationData.getMotionVelocities(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; const PxTransform oldTransform = link.bodyCore->body2World; ArticulationLink& pLink = links[link.parent]; const PxTransform pBody2World = pLink.bodyCore->body2World; ArticulationJointCore* joint = link.inboundJoint; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); PxReal* jPosition = &jointPositions[jointDatum.jointOffset]; PxQuat newParentToChild; PxQuat newWorldQ; PxVec3 r; const PxVec3 childOffset = -joint->childPose.p; const PxVec3 parentOffset = joint->parentPose.p; const PxQuat relativeQuat = mArticulationData.mRelativeQuat[linkID]; switch (joint->jointType) { case PxArticulationJointType::ePRISMATIC: { newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; const PxVec3& u = mArticulationData.mMotionMatrix[jointDatum.jointOffset].bottom; r = e + d + u * jPosition[0]; break; } case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { const PxVec3& u = mArticulationData.mMotionMatrix[jointDatum.jointOffset].top; PxQuat jointRotation = PxQuat(-jPosition[0], u); if (jointRotation.w < 0) //shortest angle. jointRotation = -jointRotation; newParentToChild = (jointRotation * relativeQuat).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; /*PxVec3 worldAngVel = oldTransform.rotate(link.motionVelocity.top); newWorldQ = PxExp(worldAngVel*dt) * oldTransform.q; PxQuat newParentToChild2 = (newWorldQ.getConjugate() * joint->relativeQuat * pBody2World.q).getNormalized(); const PxVec3 e2 = newParentToChild2.rotate(parentOffset); const PxVec3 d2 = childOffset; r = e2 + d2;*/ PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eSPHERICAL: { //PxVec3 angVel(joint->jointVelocity[0], joint->jointVelocity[1], joint->jointVelocity[2]); //PxVec3 worldAngVel = pLink.bodyCore->angularVelocity + oldTransform.rotate(angVel); PxVec3 worldAngVel = motionVelocities[linkID].top; /*const PxReal eps = 0.001f; const PxVec3 dif = worldAngVel - worldAngVel2; PX_ASSERT(PxAbs(dif.x) < eps && PxAbs(dif.y) < eps && PxAbs(dif.z) < eps);*/ newWorldQ = PxExp(worldAngVel) * oldTransform.q; newParentToChild = (newWorldQ.getConjugate() * relativeQuat * pBody2World.q).getNormalized(); const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; PX_ASSERT(r.isFinite()); break; } case PxArticulationJointType::eFIX: { //this is fix joint so joint don't have velocity newParentToChild = relativeQuat; const PxVec3 e = newParentToChild.rotate(parentOffset); const PxVec3 d = childOffset; r = e + d; break; } default: break; } PxTransform& body2World = link.bodyCore->body2World; body2World.q = (pBody2World.q * newParentToChild.getConjugate()).getNormalized(); body2World.p = pBody2World.p + body2World.q.rotate(r); PX_ASSERT(body2World.isSane()); } } PxU8* FeatherstoneArticulation::allocateScratchSpatialData(PxcScratchAllocator* allocator, const PxU32 linkCount, ScratchData& scratchData, bool fallBackToHeap) { const PxU32 size = sizeof(Cm::SpatialVectorF) * linkCount; const PxU32 totalSize = size * 4 + sizeof(Dy::SpatialMatrix) * linkCount; PxU8* tempMemory = reinterpret_cast<PxU8*>(allocator->alloc(totalSize, fallBackToHeap)); scratchData.motionVelocities = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory); PxU32 offset = size; scratchData.motionAccelerations = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.coriolisVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.spatialZAVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.compositeSpatialInertias = reinterpret_cast<Dy::SpatialMatrix*>(tempMemory + offset); return tempMemory; } /* void FeatherstoneArticulation::allocateScratchSpatialData(DyScratchAllocator& allocator, const PxU32 linkCount, ScratchData& scratchData) { const PxU32 size = sizeof(Cm::SpatialVectorF) * linkCount; const PxU32 totalSize = size * 5 + sizeof(Dy::SpatialMatrix) * linkCount; PxU8* tempMemory = allocator.alloc<PxU8>(totalSize); scratchData.motionVelocities = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory); PxU32 offset = size; scratchData.motionAccelerations = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.coriolisVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.spatialZAVectors = reinterpret_cast<Cm::SpatialVectorF*>(tempMemory + offset); offset += size; scratchData.externalAccels = reinterpret_cast<Cm::SpatialVector*>(tempMemory + offset); offset += size; scratchData.compositeSpatialInertias = reinterpret_cast<Dy::SpatialMatrix*>(tempMemory + offset); }*/ }//namespace Dy }
204,611
C++
35.394877
219
0.730093
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverControl.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DyArticulationCpuGpu.h" namespace physx { namespace Dy { void solve1DBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveExtContactBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveExt1DBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContact_BStaticBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock_Static (DY_PGS_SOLVE_METHOD_PARAMS); void solve1D4_Block (DY_PGS_SOLVE_METHOD_PARAMS); void solve1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveExtContactConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveExt1DConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContact_BStaticConcludeBlock (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock_Conclude (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock_ConcludeStatic(DY_PGS_SOLVE_METHOD_PARAMS); void solve1D4Block_Conclude (DY_PGS_SOLVE_METHOD_PARAMS); void solve1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveExtContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveExt1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveContact_BStaticBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS); void solveContactPreBlock_WriteBackStatic(DY_PGS_SOLVE_METHOD_PARAMS); void solve1D4Block_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS); // PT: not sure what happened, these ones were declared but not actually used //void writeBack1DBlock (DY_PGS_SOLVE_METHOD_PARAMS); //void contactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); //void extContactBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); //void ext1DBlockWriteBack (DY_PGS_SOLVE_METHOD_PARAMS); //void contactPreBlock_WriteBack (DY_PGS_SOLVE_METHOD_PARAMS); //void writeBack1D4Block (DY_PGS_SOLVE_METHOD_PARAMS); static SolveBlockMethod gVTableSolveBlock[] PX_UNUSED_ATTRIBUTE = { 0, solveContactBlock, // DY_SC_TYPE_RB_CONTACT solve1DBlock, // DY_SC_TYPE_RB_1D solveExtContactBlock, // DY_SC_TYPE_EXT_CONTACT solveExt1DBlock, // DY_SC_TYPE_EXT_1D solveContact_BStaticBlock, // DY_SC_TYPE_STATIC_CONTACT solveContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT solveContactPreBlock, // DY_SC_TYPE_BLOCK_RB_CONTACT solveContactPreBlock_Static, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT solve1D4_Block, // DY_SC_TYPE_BLOCK_1D, }; static SolveWriteBackBlockMethod gVTableSolveWriteBackBlock[] PX_UNUSED_ATTRIBUTE = { 0, solveContactBlockWriteBack, // DY_SC_TYPE_RB_CONTACT solve1DBlockWriteBack, // DY_SC_TYPE_RB_1D solveExtContactBlockWriteBack, // DY_SC_TYPE_EXT_CONTACT solveExt1DBlockWriteBack, // DY_SC_TYPE_EXT_1D solveContact_BStaticBlockWriteBack, // DY_SC_TYPE_STATIC_CONTACT solveContactBlockWriteBack, // DY_SC_TYPE_NOFRICTION_RB_CONTACT solveContactPreBlock_WriteBack, // DY_SC_TYPE_BLOCK_RB_CONTACT solveContactPreBlock_WriteBackStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT solve1D4Block_WriteBack, // DY_SC_TYPE_BLOCK_1D, }; static SolveBlockMethod gVTableSolveConcludeBlock[] PX_UNUSED_ATTRIBUTE = { 0, solveContactConcludeBlock, // DY_SC_TYPE_RB_CONTACT solve1DConcludeBlock, // DY_SC_TYPE_RB_1D solveExtContactConcludeBlock, // DY_SC_TYPE_EXT_CONTACT solveExt1DConcludeBlock, // DY_SC_TYPE_EXT_1D solveContact_BStaticConcludeBlock, // DY_SC_TYPE_STATIC_CONTACT solveContactConcludeBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT solveContactPreBlock_Conclude, // DY_SC_TYPE_BLOCK_RB_CONTACT solveContactPreBlock_ConcludeStatic, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT solve1D4Block_Conclude, // DY_SC_TYPE_BLOCK_1D, }; SolveBlockMethod* getSolveBlockTable() { return gVTableSolveBlock; } SolveBlockMethod* getSolverConcludeBlockTable() { return gVTableSolveConcludeBlock; } SolveWriteBackBlockMethod* getSolveWritebackBlockTable() { return gVTableSolveWriteBackBlock; } // PT: TODO: ideally we could reuse this in immediate mode as well, but the code currently uses separate arrays of PxVec3s instead of // spatial vectors so the SIMD code won't work there. Switching to spatial vectors requires a change in the immediate mode API (PxSolveConstraints). void saveMotionVelocities(PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray) { for(PxU32 i=0; i<nbBodies; i++) { Cm::SpatialVector& motionVel = motionVelocityArray[i]; const PxSolverBody& atom = solverBodies[i]; V4StoreA(V4LoadA(&atom.linearVelocity.x), &motionVel.linear.x); V4StoreA(V4LoadA(&atom.angularState.x), &motionVel.angular.x); } } // PT: this case is reached when e.g. a lot of objects falling but not touching yet. So there are no contacts but potentially a lot of bodies. // See LegacyBenchmark/falling_spheres for example. void solveNoContactsCase( PxU32 nbBodies, PxSolverBody* PX_RESTRICT solverBodies, Cm::SpatialVector* PX_RESTRICT motionVelocityArray, PxU32 nbArticulations, ArticulationSolverDesc* PX_RESTRICT articulationListStart, Cm::SpatialVectorF* PX_RESTRICT Z, Cm::SpatialVectorF* PX_RESTRICT deltaV, PxU32 nbPosIter, PxU32 nbVelIter, PxF32 dt, PxF32 invDt) { saveMotionVelocities(nbBodies, solverBodies, motionVelocityArray); if(!nbArticulations) return; const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT; // PT: TODO: unify this number with immediate mode (it's not 0.8 there!) const bool isTGS = false; //Even thought there are no external constraints, there may still be internal constraints in the articulations... for(PxU32 i=0; i<nbPosIter; i++) for(PxU32 j=0; j<nbArticulations; j++) articulationListStart[j].articulation->solveInternalConstraints(dt, invDt, Z, deltaV, false, isTGS, 0.0f, biasCoefficient); for(PxU32 i=0; i<nbArticulations; i++) ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, deltaV); for(PxU32 i=0; i<nbVelIter; i++) for(PxU32 j=0; j<nbArticulations; j++) articulationListStart[j].articulation->solveInternalConstraints(dt, invDt, Z, deltaV, true, isTGS, 0.0f, biasCoefficient); for(PxU32 j=0; j<nbArticulations; j++) articulationListStart[j].articulation->writebackInternalConstraints(isTGS); } void SolverCoreGeneral::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.Z = params.Z; cache.deltaV = params.deltaV; 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(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); PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList; //0-(n-1) iterations PxI32 normalIter = 0; for (PxU32 iteration = positionIterations; iteration > 0; iteration--) //decreasing positive numbers == position iters { cache.doFriction = mFrictionEveryIteration ? true : iteration <= 3; SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount, cache, contactIterator, iteration == 1 ? gVTableSolveConcludeBlock : gVTableSolveBlock, 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; } saveMotionVelocities(bodyListSize, bodyListStart, motionVelocityArray); for (PxU32 i = 0; i < articulationListSize; i++) ArticulationPImpl::saveVelocity(articulationListStart[i].articulation, cache.deltaV); const PxI32 velItersMinOne = (PxI32(velocityIterations)) - 1; PxI32 iteration = 0; for(; iteration < velItersMinOne; ++iteration) { SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount, cache, contactIterator, gVTableSolveBlock, 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; } PxI32* outThresholdPairs = params.outThresholdPairs; ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream; PxU32 thresholdStreamLength = params.thresholdStreamLength; cache.writeBackIteration = true; cache.mSharedThresholdStream = thresholdStream; cache.mSharedThresholdStreamLength = thresholdStreamLength; cache.mSharedOutThresholdPairs = outThresholdPairs; //PGS solver always runs at least one velocity iteration (otherwise writeback won't happen) { SolveBlockParallel(constraintList, batchCount, normalIter * batchCount, batchCount, cache, contactIterator, gVTableSolveWriteBackBlock, 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); } ++normalIter; } //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 SolverCoreGeneral::solveVParallelAndWriteBack(SolverIslandParams& params, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) const { #if PX_PROFILE_SOLVE_STALLS PxU64 startTime = readTimer(); PxU64 stallCount = 0; #endif const PxF32 biasCoefficient = DY_ARTICULATION_PGS_BIAS_COEFFICIENT; const bool isTGS = false; SolverContext cache; cache.solverBodyArray = params.bodyDataList; const PxU32 batchSize = params.batchSize; const PxI32 UnrollCount = PxI32(batchSize); const PxI32 ArticCount = 2; const PxI32 SaveUnrollCount = 32; const PxI32 TempThresholdStreamSize = 32; ThresholdStreamElement tempThresholdStream[TempThresholdStreamSize]; const PxI32 bodyListSize = PxI32(params.bodyListSize); const PxI32 articulationListSize = PxI32(params.articulationListSize); const PxI32 batchCount = PxI32(params.numConstraintHeaders); cache.mThresholdStream = tempThresholdStream; cache.mThresholdStreamLength = TempThresholdStreamSize; cache.mThresholdStreamIndex = 0; cache.writeBackIteration = false; cache.Z = Z; cache.deltaV = deltaV; const PxReal dt = params.dt; const PxReal invDt = params.invDt; const PxI32 positionIterations = PxI32(params.positionIterations); const PxI32 velocityIterations = PxI32(params.velocityIterations); PxI32* constraintIndex = &params.constraintIndex; // counter for distributing constraints to tasks, incremented before they're solved PxI32* constraintIndexCompleted = &params.constraintIndexCompleted; // counter for completed constraints, incremented after they're solved PxI32* articIndex = &params.articSolveIndex; PxI32* articIndexCompleted = &params.articSolveIndexCompleted; PxSolverConstraintDesc* PX_RESTRICT constraintList = params.constraintList; ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart; const PxU32 nbPartitions = params.nbPartitions; PxU32* headersPerPartition = params.headersPerPartition; PX_UNUSED(velocityIterations); PX_ASSERT(velocityIterations >= 1); PX_ASSERT(positionIterations >= 1); PxI32 endIndexCount = UnrollCount; PxI32 index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount; PxI32 articSolveStart = 0; PxI32 articSolveEnd = 0; PxI32 maxArticIndex = 0; PxI32 articIndexCounter = 0; BatchIterator contactIter(params.constraintBatchHeaders, params.numConstraintHeaders); PxI32 maxNormalIndex = 0; PxI32 normalIteration = 0; PxU32 a = 0; PxI32 targetConstraintIndex = 0; PxI32 targetArticIndex = 0; for(PxU32 i = 0; i < 2; ++i) { SolveBlockMethod* solveTable = i == 0 ? gVTableSolveBlock : gVTableSolveConcludeBlock; for(; a < positionIterations - 1 + i; ++a) { WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti solve of previous iteration cache.doFriction = mFrictionEveryIteration ? true : (positionIterations - a) <= 3; for(PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid solve of previous partition maxNormalIndex += 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); } targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count } WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partitions to be done 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; } } PxI32* bodyListIndex = &params.bodyListIndex; PxI32* bodyListIndexCompleted = &params.bodyListIndexCompleted; PxSolverBody* PX_RESTRICT bodyListStart = params.bodyListStart; Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray; //Save velocity - articulated PxI32 endIndexCount2 = SaveUnrollCount; PxI32 index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount; { WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for all articulation solves before saving velocity WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partition solves before saving velocity 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); } if(endIndexCount2 == 0) { index2 = PxAtomicAdd(bodyListIndex, SaveUnrollCount) - SaveUnrollCount; endIndexCount2 = SaveUnrollCount; } nbConcluded += remainder; } 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)); // wait for all velocity saves to be done a = 1; for(; a < params.velocityIterations; ++a) { WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti solve of previous iteration for(PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid solve of previous partition maxNormalIndex += headersPerPartition[b]; PxI32 nbSolved = 0; while(index < maxNormalIndex) { const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount); SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveBlock, normalIteration); index += remainder; endIndexCount -= remainder; nbSolved += remainder; if(endIndexCount == 0) { endIndexCount = UnrollCount; index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount; } } if(nbSolved) { PxMemoryBarrier(); PxAtomicAdd(constraintIndexCompleted, nbSolved); } targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count } WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for all rigid partitions to be done 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; } } ++normalIteration; articIndexCounter += articulationListSize; } ThresholdStreamElement* PX_RESTRICT thresholdStream = params.thresholdStream; PxU32 thresholdStreamLength = params.thresholdStreamLength; PxI32* outThresholdPairs = params.outThresholdPairs; cache.mSharedOutThresholdPairs = outThresholdPairs; cache.mSharedThresholdStream = thresholdStream; cache.mSharedThresholdStreamLength = thresholdStreamLength; //Last iteration - do writeback as well! cache.writeBackIteration = true; { WAIT_FOR_PROGRESS(articIndexCompleted, targetArticIndex); // wait for arti velocity iterations to be done for(PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid partition velocity iterations to be done resp. previous partition writeback iteration maxNormalIndex += headersPerPartition[b]; PxI32 nbSolved = 0; while(index < maxNormalIndex) { const PxI32 remainder = PxMin(maxNormalIndex - index, endIndexCount); SolveBlockParallel(constraintList, remainder, index, batchCount, cache, contactIter, gVTableSolveWriteBackBlock, normalIteration); index += remainder; endIndexCount -= remainder; nbSolved += remainder; if(endIndexCount == 0) { endIndexCount = UnrollCount; index = PxAtomicAdd(constraintIndex, UnrollCount) - UnrollCount; } } if(nbSolved) { PxMemoryBarrier(); PxAtomicAdd(constraintIndexCompleted, nbSolved); } targetConstraintIndex += headersPerPartition[b]; //Increment target constraint index by batch count } { WAIT_FOR_PROGRESS(constraintIndexCompleted, targetConstraintIndex); // wait for rigid partitions writeback iterations to be done 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); // wait for arti solve+writeback to be done } // 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; } ++normalIteration; } #if PX_PROFILE_SOLVE_STALLS PxU64 endTime = readTimer(); PxReal totalTime = (PxReal)(endTime - startTime); PxReal stallTime = (PxReal)stallCount; PxReal stallRatio = stallTime/totalTime; if(0)//stallRatio > 0.2f) { LARGE_INTEGER frequency; QueryPerformanceFrequency( &frequency ); printf("Warning -- percentage time stalled = %f; stalled for %f seconds; total Time took %f seconds\n", stallRatio * 100.f, stallTime/(PxReal)frequency.QuadPart, totalTime/(PxReal)frequency.QuadPart); } #endif } } }
26,054
C++
36.221429
174
0.759231
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrep.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_CONTACT_PREP_H #define DY_CONTACT_PREP_H #include "DySolverConstraintDesc.h" #include "PxSceneDesc.h" #include "DySolverContact4.h" namespace physx { struct PxcNpWorkUnit; class PxsConstraintBlockManager; class PxcConstraintBlockStream; struct PxsContactManagerOutput; class FrictionPatchStreamPair; struct PxSolverBody; struct PxSolverBodyData; struct PxSolverConstraintDesc; class PxsContactManager; namespace Dy { class ThreadContext; struct CorrelationBuffer; #define CREATE_FINALIZE_SOLVER_CONTACT_METHOD_ARGS \ PxSolverContactDesc& contactDesc, \ PxsContactManagerOutput& output, \ ThreadContext& threadContext, \ const PxReal invDtF32, \ const PxReal dtF32, \ PxReal bounceThresholdF32, \ PxReal frictionOffsetThreshold, \ PxReal correlationDistance, \ PxConstraintAllocator& constraintAllocator, \ Cm::SpatialVectorF* Z #define CREATE_FINALIZE_SOVLER_CONTACT_METHOD_ARGS_4 \ PxsContactManagerOutput** outputs, \ ThreadContext& threadContext, \ PxSolverContactDesc* blockDescs, \ const PxReal invDtF32, \ const PxReal dtF32, \ PxReal bounceThresholdF32, \ PxReal frictionThresholdF32, \ PxReal correlationDistanceF32, \ PxConstraintAllocator& constraintAllocator /*! Method prototype for create finalize solver contact */ typedef bool (*PxcCreateFinalizeSolverContactMethod)(CREATE_FINALIZE_SOLVER_CONTACT_METHOD_ARGS); extern PxcCreateFinalizeSolverContactMethod createFinalizeMethods[3]; typedef SolverConstraintPrepState::Enum (*PxcCreateFinalizeSolverContactMethod4)(CREATE_FINALIZE_SOVLER_CONTACT_METHOD_ARGS_4); extern PxcCreateFinalizeSolverContactMethod4 createFinalizeMethods4[3]; 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); bool createFinalizeSolverContacts( PxSolverContactDesc& contactDesc, CorrelationBuffer& c, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, Cm::SpatialVectorF* Z); SolverConstraintPrepState::Enum createFinalizeSolverContacts4( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator); SolverConstraintPrepState::Enum createFinalizeSolverContacts4( Dy::CorrelationBuffer& c, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator); bool createFinalizeSolverContactsCoulomb1D(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, Cm::SpatialVectorF* Z); bool createFinalizeSolverContactsCoulomb2D(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, Cm::SpatialVectorF* Z); SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb1D( PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator); SolverConstraintPrepState::Enum createFinalizeSolverContacts4Coulomb2D(PxsContactManagerOutput** outputs, ThreadContext& threadContext, PxSolverContactDesc* blockDescs, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator); PxU32 getContactManagerConstraintDesc(const PxsContactManagerOutput& cmOutput, const PxsContactManager& cm, PxSolverConstraintDesc& desc); class BlockAllocator : public PxConstraintAllocator { PxsConstraintBlockManager& mConstraintBlockManager; PxcConstraintBlockStream& mConstraintBlockStream; FrictionPatchStreamPair& mFrictionPatchStreamPair; PxU32& mTotalConstraintByteSize; public: BlockAllocator(PxsConstraintBlockManager& constraintBlockManager, PxcConstraintBlockStream& constraintBlockStream, FrictionPatchStreamPair& frictionPatchStreamPair, PxU32& totalConstraintByteSize) : mConstraintBlockManager(constraintBlockManager), mConstraintBlockStream(constraintBlockStream), mFrictionPatchStreamPair(frictionPatchStreamPair), mTotalConstraintByteSize(totalConstraintByteSize) { } virtual PxU8* reserveConstraintData(const PxU32 size); virtual PxU8* reserveFrictionData(const PxU32 size); virtual PxU8* findInputPatches(PxU8* frictionCookie) { return frictionCookie; } PX_NOCOPY(BlockAllocator) }; } } #endif
8,113
C
37.273585
165
0.719586
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneArticulationLink.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_FEATHERSTONE_ARTICULATION_LINK_H #define DY_FEATHERSTONE_ARTICULATION_LINK_H #include "foundation/PxVec3.h" #include "foundation/PxQuat.h" #include "foundation/PxTransform.h" #include "foundation/PxVecMath.h" #include "CmUtils.h" #include "CmSpatialVector.h" #include "DyVArticulation.h" #include "DyFeatherstoneArticulationUtils.h" namespace physx { namespace Dy { class ArticulationLinkData { const static PxU32 MaxJointRows = 3; public: ArticulationLinkData() { maxPenBias = 0.f; } PxVec3 childToBase; PxReal maxPenBias; }; }//namespace Dy } #endif
2,313
C
35.156249
74
0.754431
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyDynamics.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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/PxTime.h" #include "foundation/PxAtomic.h" #include "PxvDynamics.h" #include "common/PxProfileZone.h" #include "PxsRigidBody.h" #include "PxsContactManager.h" #include "DyDynamics.h" #include "DyBodyCoreIntegrator.h" #include "DySolverCore.h" #include "DySolverControl.h" #include "DySolverContact.h" #include "DySolverContactPF.h" #include "DyArticulationContactPrep.h" #include "DySolverBody.h" #include "DyConstraintPrep.h" #include "DyConstraintPartition.h" #include "DySoftBody.h" #include "CmFlushPool.h" #include "DyArticulationPImpl.h" #include "DyFeatherstoneArticulation.h" #include "PxsMaterialManager.h" #include "DySolverContactPF4.h" #include "DyContactReduction.h" #include "PxcNpContactPrepShared.h" #include "DyContactPrep.h" #include "DySolverControlPF.h" #include "PxSceneDesc.h" #include "PxsSimpleIslandManager.h" #include "PxvNphaseImplementationContext.h" #include "PxvSimStats.h" #include "PxsContactManagerState.h" #include "DyContactPrepShared.h" #include "DySleep.h" //KS - used to turn on/off batched SIMD constraints. #define DY_BATCH_CONSTRAINTS 1 //KS - used to specifically turn on/off batches 1D SIMD constraints. #define DY_BATCH_1D 1 namespace physx { namespace Dy { struct SolverIslandObjects { PxsRigidBody** bodies; FeatherstoneArticulation** articulations; PxsIndexedContactManager* contactManagers; //PxsIndexedConstraint* constraints; const IG::IslandId* islandIds; PxU32 numIslands; PxU32* bodyRemapTable; PxU32* nodeIndexArray; PxSolverConstraintDesc* constraintDescs; PxSolverConstraintDesc* orderedConstraintDescs; PxSolverConstraintDesc* tempConstraintDescs; PxConstraintBatchHeader* constraintBatchHeaders; Cm::SpatialVector* motionVelocities; PxsBodyCore** bodyCoreArray; SolverIslandObjects() : bodies(NULL), articulations(NULL), contactManagers(NULL), islandIds(NULL), numIslands(0), nodeIndexArray(NULL), constraintDescs(NULL), orderedConstraintDescs(NULL), tempConstraintDescs(NULL), constraintBatchHeaders(NULL), motionVelocities(NULL), bodyCoreArray(NULL) { } }; Context* createDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool, PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism, PxReal maxBiasCoefficient, bool frictionEveryIteration, PxReal lengthScale) { return PX_NEW(DynamicsContext)( memBlockPool, scratchAllocator, taskPool, simStats, taskManager, allocatorCallback, materialManager, islandManager, contextID, enableStabilization, useEnhancedDeterminism, maxBiasCoefficient, frictionEveryIteration, lengthScale); } void DynamicsContext::destroy() { this->~DynamicsContext(); PX_FREE_THIS; } void DynamicsContext::resetThreadContexts() { PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool); ThreadContext* threadContext = threadContextIt.getNext(); while(threadContext != NULL) { threadContext->reset(); threadContext = threadContextIt.getNext(); } } // =========================== Basic methods DynamicsContext::DynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool, PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism, PxReal maxBiasCoefficient, bool frictionEveryIteration, PxReal lengthScale) : Dy::Context (islandManager, allocatorCallback, simStats, enableStabilization, useEnhancedDeterminism, maxBiasCoefficient, lengthScale, contextID), // PT: TODO: would make sense to move all the following members to the base class but include paths get in the way atm mThreadContextPool (memBlockPool), mMaterialManager (materialManager), mScratchAllocator (scratchAllocator), mTaskPool (taskPool), mTaskManager (taskManager) { createThresholdStream(*allocatorCallback); createForceChangeThresholdStream(*allocatorCallback); mExceededForceThresholdStream[0] = PX_NEW(ThresholdStream)(*allocatorCallback); mExceededForceThresholdStream[1] = PX_NEW(ThresholdStream)(*allocatorCallback); mThresholdStreamOut = 0; mCurrentIndex = 0; mWorldSolverBody.linearVelocity = PxVec3(0); mWorldSolverBody.angularState = PxVec3(0); mWorldSolverBodyData.invMass = 0; mWorldSolverBodyData.sqrtInvInertia = PxMat33(PxZero); mWorldSolverBodyData.nodeIndex = PX_INVALID_NODE; mWorldSolverBodyData.reportThreshold = PX_MAX_REAL; mWorldSolverBodyData.penBiasClamp = -PX_MAX_REAL; mWorldSolverBodyData.maxContactImpulse = PX_MAX_REAL; mWorldSolverBody.solverProgress=MAX_PERMITTED_SOLVER_PROGRESS; mWorldSolverBody.maxSolverNormalProgress=MAX_PERMITTED_SOLVER_PROGRESS; mWorldSolverBody.maxSolverFrictionProgress=MAX_PERMITTED_SOLVER_PROGRESS; mWorldSolverBodyData.linearVelocity = mWorldSolverBodyData.angularVelocity = PxVec3(0.f); mWorldSolverBodyData.body2World = PxTransform(PxIdentity); mSolverCore[PxFrictionType::ePATCH] = PX_NEW(SolverCoreGeneral)(frictionEveryIteration); mSolverCore[PxFrictionType::eONE_DIRECTIONAL] = PX_NEW(SolverCoreGeneralPF); mSolverCore[PxFrictionType::eTWO_DIRECTIONAL] = PX_NEW(SolverCoreGeneralPF); } DynamicsContext::~DynamicsContext() { for(PxU32 i = 0; i < PxFrictionType::eFRICTION_COUNT; ++i) { PX_DELETE(mSolverCore[i]); } PX_DELETE(mExceededForceThresholdStream[1]); PX_DELETE(mExceededForceThresholdStream[0]); } #if PX_ENABLE_SIM_STATS void DynamicsContext::addThreadStats(const ThreadContext::ThreadSimStats& stats) { mSimStats.mNbActiveConstraints += stats.numActiveConstraints; mSimStats.mNbActiveDynamicBodies += stats.numActiveDynamicBodies; mSimStats.mNbActiveKinematicBodies += stats.numActiveKinematicBodies; mSimStats.mNbAxisSolverConstraints += stats.numAxisSolverConstraints; } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif // =========================== Solve methods! void DynamicsContext::setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim, const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset) { PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1); const PxU32 offsetMap[] = {solverBodyOffset, 0}; //const PxU32 offsetMap[] = {mKinematicCount, 0}; if(constraint.indexType0 == PxsIndexedInteraction::eARTICULATION) { const PxNodeIndex& nodeIndex0 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation0); const IG::Node& node0 = islandSim.getNode(nodeIndex0); desc.articulationA = node0.getArticulation(); desc.linkIndexA = nodeIndex0.articulationLinkId(); } else { desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; //desc.articulationALength = 0; //this is unioned with bodyADataIndex /*desc.bodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody : &mSolverBodyPool[(PxU32)constraint.solverBody0 + offsetMap[constraint.indexType0]]; desc.bodyADataIndex = PxU16(constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0 : (PxU16)constraint.solverBody0 + 1 + offsetMap[constraint.indexType0]);*/ desc.bodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody : &mSolverBodyPool[PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0]]; desc.bodyADataIndex = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0 : PxU32(constraint.solverBody0) + 1 + offsetMap[constraint.indexType0]; } if(constraint.indexType1 == PxsIndexedInteraction::eARTICULATION) { const PxNodeIndex& nodeIndex1 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation1); const IG::Node& node1 = islandSim.getNode(nodeIndex1); desc.articulationB = node1.getArticulation(); desc.linkIndexB = nodeIndex1.articulationLinkId();// PxTo8(getLinkIndex(constraint.articulation1)); } else { desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; //desc.articulationBLength = 0; //this is unioned with bodyBDataIndex desc.bodyB = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBody : &mSolverBodyPool[PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1]]; desc.bodyBDataIndex = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? 0 : PxU32(constraint.solverBody1) + 1 + offsetMap[constraint.indexType1]; } } void DynamicsContext::setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex, const IG::SimpleIslandManager& islandManager, PxU32* bodyRemap, PxU32 solverBodyOffset) { PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1); const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim(); PxNodeIndex node1 = islandSim.getNodeIndex1(edgeIndex); if (node1.isStaticBody()) { desc.bodyA = &mWorldSolverBody; desc.bodyADataIndex = 0; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } else { const IG::Node& node = islandSim.getNode(node1); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { Dy::FeatherstoneArticulation* a = islandSim.getLLArticulation(node1); PxU8 type; a->fillIndexType(node1.articulationLinkId(), type); if (type == PxsIndexedInteraction::eARTICULATION) { desc.articulationA = a; desc.linkIndexA = node1.articulationLinkId(); } else { desc.bodyA = &mWorldSolverBody; desc.bodyADataIndex = 0; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } } else { PxU32 activeIndex = islandSim.getActiveNodeIndex(node1); PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset; desc.bodyA = &mSolverBodyPool[index]; desc.bodyADataIndex = index + 1; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } } PxNodeIndex node2 = islandSim.getNodeIndex2(edgeIndex); if (node2.isStaticBody()) { desc.bodyB = &mWorldSolverBody; desc.bodyBDataIndex = 0; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } else { const IG::Node& node = islandSim.getNode(node2); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { Dy::FeatherstoneArticulation* b = islandSim.getLLArticulation(node2); PxU8 type; b->fillIndexType(node2.articulationLinkId(), type); if (type == PxsIndexedInteraction::eARTICULATION) { desc.articulationB = b; desc.linkIndexB = node2.articulationLinkId(); } else { desc.bodyB = &mWorldSolverBody; desc.bodyBDataIndex = 0; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } else { PxU32 activeIndex = islandSim.getActiveNodeIndex(node2); PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset; desc.bodyB = &mSolverBodyPool[index]; desc.bodyBDataIndex = index + 1; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } } class PxsPreIntegrateTask : public Cm::Task { PxsPreIntegrateTask& operator=(const PxsPreIntegrateTask&); public: PxsPreIntegrateTask( DynamicsContext& context, PxsBodyCore*const* bodyArray, PxsRigidBody*const* originalBodyArray, PxU32 const* nodeIndexArray, PxSolverBodyData* solverBodyDataPool, PxF32 dt, PxU32 numBodies, volatile PxU32* maxSolverPositionIterations, volatile PxU32* maxSolverVelocityIterations, PxU32 startIndex, PxU32 numToIntegrate, const PxVec3& gravity) : Cm::Task (context.getContextId()), mContext (context), mBodyArray (bodyArray), mOriginalBodyArray (originalBodyArray), mNodeIndexArray (nodeIndexArray), mSolverBodyDataPool (solverBodyDataPool), mDt (dt), mNumBodies (numBodies), mMaxSolverPositionIterations(maxSolverPositionIterations), mMaxSolverVelocityIterations(maxSolverVelocityIterations), mStartIndex (startIndex), mNumToIntegrate (numToIntegrate), mGravity (gravity) {} virtual void runInternal(); virtual const char* getName() const { return "PxsDynamics.preIntegrate"; } public: DynamicsContext& mContext; PxsBodyCore*const* mBodyArray; PxsRigidBody*const* mOriginalBodyArray; PxU32 const* mNodeIndexArray; PxSolverBody* mSolverBodies; PxSolverBodyData* mSolverBodyDataPool; PxF32 mDt; PxU32 mNumBodies; volatile PxU32* mMaxSolverPositionIterations; volatile PxU32* mMaxSolverVelocityIterations; PxU32 mStartIndex; PxU32 mNumToIntegrate; PxVec3 mGravity; }; class PxsParallelSolverTask : public Cm::Task { PxsParallelSolverTask& operator=(PxsParallelSolverTask&); public: PxsParallelSolverTask(SolverIslandParams& params, DynamicsContext& context, IG::IslandSim& islandSim) : Cm::Task(context.getContextId()), mParams(params), mContext(context), mIslandSim(islandSim) { } virtual void runInternal() { solveParallel(mContext, mParams, mIslandSim); } virtual const char* getName() const { return "PxsDynamics.parallelSolver"; } SolverIslandParams& mParams; DynamicsContext& mContext; IG::IslandSim& mIslandSim; }; #define PX_CONTACT_REDUCTION 1 class PxsSolverConstraintPostProcessTask : public Cm::Task { PxsSolverConstraintPostProcessTask& operator=(const PxsSolverConstraintPostProcessTask&); public: PxsSolverConstraintPostProcessTask(DynamicsContext& context, ThreadContext& threadContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, PxU32 startIndex, PxU32 stride, PxsMaterialManager* materialManager, PxsContactManagerOutputIterator& iterator) : Cm::Task (context.getContextId()), mContext (context), mThreadContext (threadContext), mObjects (objects), mSolverBodyOffset (solverBodyOffset), mStartIndex (startIndex), mStride (stride), mMaterialManager (materialManager), mOutputs (iterator) {} void mergeContacts(CompoundContactManager& header, ThreadContext& threadContext) { PxContactBuffer& buffer = threadContext.mContactBuffer; PxsMaterialInfo materialInfo[PxContactBuffer::MAX_CONTACTS]; PxU32 size = 0; for(PxU32 a = 0; a < header.mStride; ++a) { PxsContactManager* manager = mThreadContext.orderedContactList[a+header.mStartIndex]->contactManager; PxcNpWorkUnit& unit = manager->getWorkUnit(); PxsContactManagerOutput& output = mOutputs.getContactManager(unit.mNpIndex); PxContactStreamIterator iter(output.contactPatches, output.contactPoints, output.getInternalFaceIndice(), output.nbPatches, output.nbContacts); PxU32 origSize = size; PX_UNUSED(origSize); if(!iter.forceNoResponse) { while(iter.hasNextPatch()) { iter.nextPatch(); while(iter.hasNextContact()) { PX_ASSERT(size < PxContactBuffer::MAX_CONTACTS); iter.nextContact(); PxsMaterialInfo& info = materialInfo[size]; PxContactPoint& point = buffer.contacts[size++]; point.dynamicFriction = iter.getDynamicFriction(); point.staticFriction = iter.getStaticFriction(); point.restitution = iter.getRestitution(); point.internalFaceIndex1 = iter.getFaceIndex1(); point.materialFlags = PxU8(iter.getMaterialFlags()); point.maxImpulse = iter.getMaxImpulse(); point.targetVel = iter.getTargetVel(); point.normal = iter.getContactNormal(); point.point = iter.getContactPoint(); point.separation = iter.getSeparation(); info.mMaterialIndex0 = iter.getMaterialIndex0(); info.mMaterialIndex1 = iter.getMaterialIndex1(); } } PX_ASSERT(output.nbContacts == (size - origSize)); } } PxU32 origSize = size; #if PX_CONTACT_REDUCTION ContactReduction<6> reduction(buffer.contacts, materialInfo, size); reduction.reduceContacts(); //OK, now we write back the contacts... PxU8 histo[PxContactBuffer::MAX_CONTACTS]; PxMemZero(histo, sizeof(histo)); size = 0; for(PxU32 a = 0; a < reduction.mNumPatches; ++a) { ReducedContactPatch& patch = reduction.mPatches[a]; for(PxU32 b = 0; b < patch.numContactPoints; ++b) { histo[patch.contactPoints[b]] = 1; ++size; } } #endif PxU16* PX_RESTRICT data = reinterpret_cast<PxU16*>(threadContext.mConstraintBlockStream.reserve(size * sizeof(PxU16), mThreadContext.mConstraintBlockManager)); header.forceBufferList = data; #if PX_CONTACT_REDUCTION const PxU32 reservedSize = size; PX_UNUSED(reservedSize); size = 0; for(PxU32 a = 0; a < origSize; ++a) { if(histo[a]) { if(size != a) { buffer.contacts[size] = buffer.contacts[a]; materialInfo[size] = materialInfo[a]; } data[size] = PxTo16(a); size++; } } PX_ASSERT(reservedSize >= size); #else for(PxU32 a = 0; a < size; ++a) data[a] = a; #endif PxU32 contactForceByteSize = size * sizeof(PxReal); PxsContactManagerOutput& output = mOutputs.getContactManager(header.unit->mNpIndex); PxU16 compressedContactSize; physx::writeCompressedContact(buffer.contacts, size, NULL, output.nbContacts, output.contactPatches, output.contactPoints, compressedContactSize, reinterpret_cast<PxReal*&>(output.contactForces), contactForceByteSize, mMaterialManager, false, false, materialInfo, output.nbPatches, 0, &mThreadContext.mConstraintBlockManager, &threadContext.mConstraintBlockStream, false); } virtual void runInternal() { PX_PROFILE_ZONE("ConstraintPostProcess", mContext.getContextId()); PxU32 endIndex = mStartIndex + mStride; ThreadContext* threadContext = mContext.getThreadContext(); //TODO - we need to do this somewhere else //threadContext->mContactBlockStream.reset(); threadContext->mConstraintBlockStream.reset(); for(PxU32 a = mStartIndex; a < endIndex; ++a) { mergeContacts(mThreadContext.compoundConstraints[a], *threadContext); } mContext.putThreadContext(threadContext); } virtual const char* getName() const { return "PxsDynamics.solverConstraintPostProcess"; } DynamicsContext& mContext; ThreadContext& mThreadContext; const SolverIslandObjects mObjects; const PxU32 mSolverBodyOffset; const PxU32 mStartIndex; const PxU32 mStride; PxsMaterialManager* mMaterialManager; PxsContactManagerOutputIterator& mOutputs; }; class PxsForceThresholdTask : public Cm::Task { DynamicsContext& mDynamicsContext; PxsForceThresholdTask& operator=(const PxsForceThresholdTask&); public: PxsForceThresholdTask(DynamicsContext& context): Cm::Task(context.getContextId()), mDynamicsContext(context) { } void createForceChangeThresholdStream() { ThresholdStream& thresholdStream = mDynamicsContext.getThresholdStream(); //bool haveThresholding = thresholdStream.size()!=0; ThresholdTable& thresholdTable = mDynamicsContext.getThresholdTable(); thresholdTable.build(thresholdStream); //generate current force exceeded threshold stream ThresholdStream& curExceededForceThresholdStream = *mDynamicsContext.mExceededForceThresholdStream[mDynamicsContext.mCurrentIndex]; ThresholdStream& preExceededForceThresholdStream = *mDynamicsContext.mExceededForceThresholdStream[1 - mDynamicsContext.mCurrentIndex]; curExceededForceThresholdStream.forceSize_Unsafe(0); //fill in the currrent exceeded force threshold stream for(PxU32 i=0; i<thresholdTable.mPairsSize; ++i) { ThresholdTable::Pair& pair = thresholdTable.mPairs[i]; ThresholdStreamElement& elem = thresholdStream[pair.thresholdStreamIndex]; if(pair.accumulatedForce > elem.threshold * mDynamicsContext.mDt) { elem.accumulatedForce = pair.accumulatedForce; curExceededForceThresholdStream.pushBack(elem); } } ThresholdStream& forceChangeThresholdStream = mDynamicsContext.getForceChangedThresholdStream(); forceChangeThresholdStream.forceSize_Unsafe(0); PxArray<PxU32>& forceChangeMask = mDynamicsContext.mExceededForceThresholdStreamMask; const PxU32 nbPreExceededForce = preExceededForceThresholdStream.size(); const PxU32 nbCurExceededForce = curExceededForceThresholdStream.size(); //generate force change thresholdStream if(nbPreExceededForce) { thresholdTable.build(preExceededForceThresholdStream); //set force change mask const PxU32 nbTotalExceededForce = nbPreExceededForce + nbCurExceededForce; forceChangeMask.reserve(nbTotalExceededForce); forceChangeMask.forceSize_Unsafe(nbTotalExceededForce); //initialize the forceChangeMask for (PxU32 i = 0; i < nbTotalExceededForce; ++i) forceChangeMask[i] = 1; for(PxU32 i=0; i< nbCurExceededForce; ++i) { ThresholdStreamElement& curElem = curExceededForceThresholdStream[i]; PxU32 pos; if(thresholdTable.check(preExceededForceThresholdStream, curElem, pos)) { forceChangeMask[pos] = 0; forceChangeMask[i + nbPreExceededForce] = 0; } } //create force change threshold stream for(PxU32 i=0; i<nbTotalExceededForce; ++i) { const PxU32 hasForceChange = forceChangeMask[i]; if(hasForceChange) { bool lostPair = (i < nbPreExceededForce); ThresholdStreamElement& elem = lostPair ? preExceededForceThresholdStream[i] : curExceededForceThresholdStream[i - nbPreExceededForce]; ThresholdStreamElement elt; elt = elem; elt.accumulatedForce = lostPair ? 0.f : elem.accumulatedForce; forceChangeThresholdStream.pushBack(elt); } else { //persistent pair if (i < nbPreExceededForce) { ThresholdStreamElement& elem = preExceededForceThresholdStream[i]; ThresholdStreamElement elt; elt = elem; elt.accumulatedForce = elem.accumulatedForce; forceChangeThresholdStream.pushBack(elt); } } } } else { forceChangeThresholdStream.reserve(nbCurExceededForce); forceChangeThresholdStream.forceSize_Unsafe(nbCurExceededForce); PxMemCopy(forceChangeThresholdStream.begin(), curExceededForceThresholdStream.begin(), sizeof(ThresholdStreamElement) * nbCurExceededForce); } } virtual void runInternal() { mDynamicsContext.getThresholdStream().forceSize_Unsafe(PxU32(mDynamicsContext.mThresholdStreamOut)); createForceChangeThresholdStream(); } virtual const char* getName() const { return "PxsDynamics.createForceChangeThresholdStream"; } }; struct ConstraintLess { bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const { return reinterpret_cast<Constraint*>(left.constraint)->index > reinterpret_cast<Constraint*>(right.constraint)->index; } }; struct ArticulationSortPredicate { bool operator()(const PxsIndexedContactManager*& left, const PxsIndexedContactManager*& right) const { return left->contactManager->getWorkUnit().index < right->contactManager->getWorkUnit().index; } }; class SolverArticulationUpdateTask : public Cm::Task { ThreadContext& mIslandThreadContext; FeatherstoneArticulation** mArticulations; ArticulationSolverDesc* mArticulationDescArray; PxU32 mNbToProcess; Dy::DynamicsContext& mContext; public: static const PxU32 NbArticulationsPerTask = 32; SolverArticulationUpdateTask(ThreadContext& islandThreadContext, FeatherstoneArticulation** articulations, ArticulationSolverDesc* articulationDescArray, PxU32 nbToProcess, Dy::DynamicsContext& context) : Cm::Task(context.getContextId()), mIslandThreadContext(islandThreadContext), mArticulations(articulations), mArticulationDescArray(articulationDescArray), mNbToProcess(nbToProcess), mContext(context) { } virtual const char* getName() const { return "SolverArticulationUpdateTask"; } virtual void runInternal() { ThreadContext& threadContext = *mContext.getThreadContext(); threadContext.mConstraintBlockStream.reset(); //Clear in case there's some left-over memory in this context, for which the block has already been freed PxU32 maxVelIters = 0; PxU32 maxPosIters = 0; PxU32 maxLinks = 0; for (PxU32 i = 0; i < mNbToProcess; i++) { FeatherstoneArticulation& a = *(mArticulations[i]); a.getSolverDesc(mArticulationDescArray[i]); maxLinks = PxMax(maxLinks, PxU32(mArticulationDescArray[i].linkCount)); } threadContext.mZVector.forceSize_Unsafe(0); threadContext.mZVector.reserve(maxLinks); threadContext.mZVector.forceSize_Unsafe(maxLinks); threadContext.mDeltaV.forceSize_Unsafe(0); threadContext.mDeltaV.reserve(maxLinks); threadContext.mDeltaV.forceSize_Unsafe(maxLinks); BlockAllocator blockAllocator(mIslandThreadContext.mConstraintBlockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize); const PxReal invLengthScale = 1.f/mContext.getLengthScale(); for(PxU32 i=0;i<mNbToProcess; i++) { FeatherstoneArticulation& a = *(mArticulations[i]); PxU32 acCount, descCount; descCount = ArticulationPImpl::computeUnconstrainedVelocities(mArticulationDescArray[i], mContext.mDt, acCount, mContext.getGravity(), threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), invLengthScale); mArticulationDescArray[i].numInternalConstraints = PxTo8(descCount); const PxU16 iterWord = a.getIterationCounts(); maxVelIters = PxMax<PxU32>(PxU32(iterWord >> 8), maxVelIters); maxPosIters = PxMax<PxU32>(PxU32(iterWord & 0xff), maxPosIters); } PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxSolverPositionIterations), PxI32(maxPosIters)); PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxSolverVelocityIterations), PxI32(maxVelIters)); PxAtomicMax(reinterpret_cast<PxI32*>(&mIslandThreadContext.mMaxArticulationLinks), PxI32(maxLinks)); mContext.putThreadContext(&threadContext); } private: PX_NOCOPY(SolverArticulationUpdateTask) }; struct EnhancedSortPredicate { bool operator()(const PxsIndexedContactManager& left, const PxsIndexedContactManager& right) const { PxcNpWorkUnit& unit0 = left.contactManager->getWorkUnit(); PxcNpWorkUnit& unit1 = right.contactManager->getWorkUnit(); return (unit0.mTransformCache0 < unit1.mTransformCache0) || ((unit0.mTransformCache0 == unit1.mTransformCache0) && (unit0.mTransformCache1 < unit1.mTransformCache1)); } }; class PxsSolverStartTask : public Cm::Task { PxsSolverStartTask& operator=(const PxsSolverStartTask&); public: PxsSolverStartTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, PxU32 kinematicCount, IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxsMaterialManager* materialManager, PxsContactManagerOutputIterator& iterator, bool enhancedDeterminism ) : Cm::Task (context.getContextId()), mContext (context), mIslandContext (islandContext), mObjects (objects), mSolverBodyOffset (solverBodyOffset), mKinematicCount (kinematicCount), mIslandManager (islandManager), mBodyRemapTable (bodyRemapTable), mMaterialManager (materialManager), mOutputs (iterator), mEnhancedDeterminism (enhancedDeterminism) {} void startTasks() { PX_PROFILE_ZONE("Dynamics.solveGroup", mContext.getContextId()); { ThreadContext& mThreadContext = *mContext.getThreadContext(); mIslandContext.mThreadContext = &mThreadContext; mThreadContext.mMaxSolverPositionIterations = 0; mThreadContext.mMaxSolverVelocityIterations = 0; mThreadContext.mAxisConstraintCount = 0; mThreadContext.mContactDescPtr = mThreadContext.contactConstraintDescArray; mThreadContext.mFrictionDescPtr = mThreadContext.frictionConstraintDescArray.begin(); mThreadContext.mNumDifferentBodyConstraints = 0; mThreadContext.mNumStaticConstraints = 0; mThreadContext.mNumSelfConstraints = 0; mThreadContext.mNumDifferentBodyFrictionConstraints = 0; mThreadContext.mNumSelfConstraintFrictionBlocks = 0; mThreadContext.mNumSelfFrictionConstraints = 0; mThreadContext.numContactConstraintBatches = 0; mThreadContext.contactDescArraySize = 0; mThreadContext.mMaxArticulationLinks = 0; mThreadContext.contactConstraintDescArray = mObjects.constraintDescs; mThreadContext.orderedContactConstraints = mObjects.orderedConstraintDescs; mThreadContext.mContactDescPtr = mObjects.constraintDescs; mThreadContext.tempConstraintDescArray = mObjects.tempConstraintDescs; mThreadContext.contactConstraintBatchHeaders = mObjects.constraintBatchHeaders; mThreadContext.motionVelocityArray = mObjects.motionVelocities; mThreadContext.mBodyCoreArray = mObjects.bodyCoreArray; mThreadContext.mRigidBodyArray = mObjects.bodies; mThreadContext.mArticulationArray = mObjects.articulations; mThreadContext.bodyRemapTable = mObjects.bodyRemapTable; mThreadContext.mNodeIndexArray = mObjects.nodeIndexArray; const PxU32 frictionConstraintCount = mContext.getFrictionType() == PxFrictionType::ePATCH ? 0 : PxU32(mIslandContext.mCounts.contactManagers); mThreadContext.resizeArrays(frictionConstraintCount, mIslandContext.mCounts.articulations); PxsBodyCore** PX_RESTRICT bodyArrayPtr = mThreadContext.mBodyCoreArray; PxsRigidBody** PX_RESTRICT rigidBodyPtr = mThreadContext.mRigidBodyArray; FeatherstoneArticulation** PX_RESTRICT articulationPtr = mThreadContext.mArticulationArray; PxU32* PX_RESTRICT bodyRemapTable = mThreadContext.bodyRemapTable; PxU32* PX_RESTRICT nodeIndexArray = mThreadContext.mNodeIndexArray; PxU32 nbIslands = mObjects.numIslands; const IG::IslandId* const islandIds = mObjects.islandIds; const IG::IslandSim& islandSim = mIslandManager.getAccurateIslandSim(); PxU32 bodyIndex = 0, articIndex = 0; for (PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); PxNodeIndex currentIndex = island.mRootNode; while (currentIndex.isValid()) { const IG::Node& node = islandSim.getNode(currentIndex); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { articulationPtr[articIndex++] = node.getArticulation(); } else { PX_ASSERT(bodyIndex < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1)); nodeIndexArray[bodyIndex++] = currentIndex.index(); } currentIndex = node.mNextNode; } } //Bodies can come in a slightly jumbled order from islandGen. It's deterministic if the scene is //identical but can vary if there are additional bodies in the scene in a different island. if (mEnhancedDeterminism) PxSort(nodeIndexArray, bodyIndex); for (PxU32 a = 0; a < bodyIndex; ++a) { PxNodeIndex currentIndex(nodeIndexArray[a]); const IG::Node& node = islandSim.getNode(currentIndex); PxsRigidBody* rigid = node.getRigidBody(); rigidBodyPtr[a] = rigid; bodyArrayPtr[a] = &rigid->getCore(); bodyRemapTable[islandSim.getActiveNodeIndex(currentIndex)] = a; } PxsIndexedContactManager* indexedManagers = mObjects.contactManagers; PxU32 currentContactIndex = 0; for(PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); IG::EdgeIndex contactEdgeIndex = island.mFirstEdge[IG::Edge::eCONTACT_MANAGER]; while(contactEdgeIndex != IG_INVALID_EDGE) { const IG::Edge& edge = islandSim.getEdge(contactEdgeIndex); PxsContactManager* contactManager = mIslandManager.getContactManager(contactEdgeIndex); if(contactManager) { const PxNodeIndex nodeIndex1 = islandSim.getNodeIndex1(contactEdgeIndex); const PxNodeIndex nodeIndex2 = islandSim.getNodeIndex2(contactEdgeIndex); PxsIndexedContactManager& indexedManager = indexedManagers[currentContactIndex++]; indexedManager.contactManager = contactManager; PX_ASSERT(!nodeIndex1.isStaticBody()); { const IG::Node& node1 = islandSim.getNode(nodeIndex1); //Is it an articulation or not??? if(node1.getNodeType() == IG::Node::eARTICULATION_TYPE) { indexedManager.articulation0 = nodeIndex1.getInd(); const PxU32 linkId = nodeIndex1.articulationLinkId(); node1.getArticulation()->fillIndexType(linkId, indexedManager.indexType0); } else { if(node1.isKinematic()) { indexedManager.indexType0 = PxsIndexedInteraction::eKINEMATIC; indexedManager.solverBody0 = islandSim.getActiveNodeIndex(nodeIndex1); } else { indexedManager.indexType0 = PxsIndexedInteraction::eBODY; indexedManager.solverBody0 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex1)]; } PX_ASSERT(indexedManager.solverBody0 < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1)); } } if(nodeIndex2.isStaticBody()) { indexedManager.indexType1 = PxsIndexedInteraction::eWORLD; } else { const IG::Node& node2 = islandSim.getNode(nodeIndex2); //Is it an articulation or not??? if(node2.getNodeType() == IG::Node::eARTICULATION_TYPE) { indexedManager.articulation1 = nodeIndex2.getInd(); const PxU32 linkId = nodeIndex2.articulationLinkId(); node2.getArticulation()->fillIndexType(linkId, indexedManager.indexType1); } else { if(node2.isKinematic()) { indexedManager.indexType1 = PxsIndexedInteraction::eKINEMATIC; indexedManager.solverBody1 = islandSim.getActiveNodeIndex(nodeIndex2); } else { indexedManager.indexType1 = PxsIndexedInteraction::eBODY; indexedManager.solverBody1 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex2)]; } PX_ASSERT(indexedManager.solverBody1 < (mIslandContext.mCounts.bodies + mContext.mKinematicCount + 1)); } } } contactEdgeIndex = edge.mNextIslandEdge; } } if (mEnhancedDeterminism) PxSort(indexedManagers, currentContactIndex, EnhancedSortPredicate()); mIslandContext.mCounts.contactManagers = currentContactIndex; } } void integrate() { ThreadContext& mThreadContext = *mIslandContext.mThreadContext; PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset; PxSolverBodyData* solverBodyData = mContext.mSolverBodyDataPool.begin() + mSolverBodyOffset; { PX_PROFILE_ZONE("Dynamics.updateVelocities", mContext.getContextId()); mContext.preIntegrationParallel( mContext.mDt, mThreadContext.mBodyCoreArray, mObjects.bodies, mThreadContext.mNodeIndexArray, mIslandContext.mCounts.bodies, solverBodies, solverBodyData, mThreadContext.motionVelocityArray, mThreadContext.mMaxSolverPositionIterations, mThreadContext.mMaxSolverVelocityIterations, *mCont ); } } void articulationTask() { ThreadContext& mThreadContext = *mIslandContext.mThreadContext; ArticulationSolverDesc* articulationDescArray = mThreadContext.getArticulations().begin(); for(PxU32 i=0;i<mIslandContext.mCounts.articulations; i+= SolverArticulationUpdateTask::NbArticulationsPerTask) { SolverArticulationUpdateTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(SolverArticulationUpdateTask)), SolverArticulationUpdateTask)(mThreadContext, &mObjects.articulations[i], &articulationDescArray[i], PxMin(SolverArticulationUpdateTask::NbArticulationsPerTask, mIslandContext.mCounts.articulations - i), mContext); task->setContinuation(mCont); task->removeReference(); } } void setupDescTask() { PX_PROFILE_ZONE("SetupDescs", mContext.getContextId()); ThreadContext& mThreadContext = *mIslandContext.mThreadContext; PxSolverConstraintDesc* contactDescPtr = mThreadContext.mContactDescPtr; //PxU32 constraintCount = mCounts.constraints + mCounts.contactManagers; PxU32 nbIslands = mObjects.numIslands; const IG::IslandId* const islandIds = mObjects.islandIds; const IG::IslandSim& islandSim = mIslandManager.getAccurateIslandSim(); for(PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); IG::EdgeIndex edgeId = island.mFirstEdge[IG::Edge::eCONSTRAINT]; while(edgeId != IG_INVALID_EDGE) { PxSolverConstraintDesc& desc = *contactDescPtr; const IG::Edge& edge = islandSim.getEdge(edgeId); Dy::Constraint* constraint = mIslandManager.getConstraint(edgeId); mContext.setDescFromIndices(desc, edgeId, mIslandManager, mBodyRemapTable, mSolverBodyOffset); desc.constraint = reinterpret_cast<PxU8*>(constraint); desc.constraintLengthOver16 = DY_SC_TYPE_RB_1D; contactDescPtr++; edgeId = edge.mNextIslandEdge; } } #if 1 PxSort(mThreadContext.mContactDescPtr, PxU32(contactDescPtr - mThreadContext.mContactDescPtr), ConstraintLess()); #endif mThreadContext.orderedContactList.forceSize_Unsafe(0); mThreadContext.orderedContactList.reserve(mIslandContext.mCounts.contactManagers); mThreadContext.orderedContactList.forceSize_Unsafe(mIslandContext.mCounts.contactManagers); mThreadContext.tempContactList.forceSize_Unsafe(0); mThreadContext.tempContactList.reserve(mIslandContext.mCounts.contactManagers); mThreadContext.tempContactList.forceSize_Unsafe(mIslandContext.mCounts.contactManagers); const PxsIndexedContactManager** constraints = mThreadContext.orderedContactList.begin(); //OK, we sort the orderedContactList mThreadContext.compoundConstraints.forceSize_Unsafe(0); if(mIslandContext.mCounts.contactManagers) { { mThreadContext.sortIndexArray.forceSize_Unsafe(0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1); const PxI32 offsetMap[] = {PxI32(mContext.mKinematicCount), 0}; const PxU32 totalBodies = mContext.mKinematicCount + mIslandContext.mCounts.bodies+1; mThreadContext.sortIndexArray.reserve(totalBodies); mThreadContext.sortIndexArray.forceSize_Unsafe(totalBodies); PxMemZero(mThreadContext.sortIndexArray.begin(), totalBodies * 4); //Iterate over the array based on solverBodyDatapool, creating a list of sorted constraints (in order of body pair) //We only do this with contacts. It's important that this is done this way because we don't want to break our rules that all joints //appear before all contacts in the constraint list otherwise we will lose all guarantees about sorting joints. for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a) { PX_ASSERT(mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eWORLD); //Index first body... PxU8 indexType = mObjects.contactManagers[a].indexType0; if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType1 != PxsIndexedInteraction::eARTICULATION) { PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC)); PxI32 index = PxI32(mObjects.contactManagers[a].solverBody0 + offsetMap[indexType]); PX_ASSERT(index >= 0); mThreadContext.sortIndexArray[PxU32(index)]++; } } PxU32 accumulatedCount = 0; for(PxU32 a = mThreadContext.sortIndexArray.size(); a > 0; --a) { PxU32 ind = a - 1; PxU32 val = mThreadContext.sortIndexArray[ind]; mThreadContext.sortIndexArray[ind] = accumulatedCount; accumulatedCount += val; } //OK, now copy across data to orderedConstraintDescs, pushing articulations to the end... for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a) { //Index first body... PxU8 indexType = mObjects.contactManagers[a].indexType0; if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType1 != PxsIndexedInteraction::eARTICULATION) { PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC)); PxI32 index = PxI32(mObjects.contactManagers[a].solverBody0 + offsetMap[indexType]); PX_ASSERT(index >= 0); mThreadContext.tempContactList[mThreadContext.sortIndexArray[PxU32(index)]++] = &mObjects.contactManagers[a]; } else { mThreadContext.tempContactList[accumulatedCount++] = &mObjects.contactManagers[a]; } } //Now do the same again with bodyB, being careful not to overwrite the joints PxMemZero(mThreadContext.sortIndexArray.begin(), totalBodies * 4); for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a) { //Index first body... PxU8 indexType = mThreadContext.tempContactList[a]->indexType1; if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eARTICULATION) { PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC) || (indexType == PxsIndexedInteraction::eWORLD)); PxI32 index = (indexType == PxsIndexedInteraction::eWORLD) ? 0 : PxI32(mThreadContext.tempContactList[a]->solverBody1 + offsetMap[indexType]); PX_ASSERT(index >= 0); mThreadContext.sortIndexArray[PxU32(index)]++; } } accumulatedCount = 0; for(PxU32 a = mThreadContext.sortIndexArray.size(); a > 0; --a) { PxU32 ind = a - 1; PxU32 val = mThreadContext.sortIndexArray[ind]; mThreadContext.sortIndexArray[ind] = accumulatedCount; accumulatedCount += val; } PxU32 articulationStartIndex = accumulatedCount; //OK, now copy across data to orderedConstraintDescs, pushing articulations to the end... for(PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a) { //Index first body... PxU8 indexType = mThreadContext.tempContactList[a]->indexType1; if(indexType != PxsIndexedInteraction::eARTICULATION && mObjects.contactManagers[a].indexType0 != PxsIndexedInteraction::eARTICULATION) { PX_ASSERT((indexType == PxsIndexedInteraction::eBODY) || (indexType == PxsIndexedInteraction::eKINEMATIC) || (indexType == PxsIndexedInteraction::eWORLD)); PxI32 index = (indexType == PxsIndexedInteraction::eWORLD) ? 0 : PxI32(mThreadContext.tempContactList[a]->solverBody1 + offsetMap[indexType]); PX_ASSERT(index >= 0); constraints[mThreadContext.sortIndexArray[PxU32(index)]++] = mThreadContext.tempContactList[a]; } else { constraints[accumulatedCount++] = mThreadContext.tempContactList[a]; } } #if 1 PxSort(constraints + articulationStartIndex, accumulatedCount - articulationStartIndex, ArticulationSortPredicate()); #endif } mThreadContext.mStartContactDescPtr = contactDescPtr; mThreadContext.compoundConstraints.reserve(1024); mThreadContext.compoundConstraints.forceSize_Unsafe(0); //mThreadContext.compoundConstraints.forceSize_Unsafe(mCounts.contactManagers); PxSolverConstraintDesc* startDesc = contactDescPtr; mContext.setDescFromIndices(*startDesc, islandSim, *constraints[0], mSolverBodyOffset); startDesc->constraint = reinterpret_cast<PxU8*>(constraints[0]->contactManager); startDesc->constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT; PxsContactManagerOutput* startManagerOutput = &mOutputs.getContactManager(constraints[0]->contactManager->getWorkUnit().mNpIndex); PxU32 contactCount = startManagerOutput->nbContacts; PxU32 startIndex = 0; PxU32 numHeaders = 0; const bool gDisableConstraintWelding = false; for(PxU32 a = 1; a < mIslandContext.mCounts.contactManagers; ++a) { PxSolverConstraintDesc& desc = *(contactDescPtr+1); mContext.setDescFromIndices(desc, islandSim, *constraints[a], mSolverBodyOffset); PxsContactManager* manager = constraints[a]->contactManager; PxsContactManagerOutput& output = mOutputs.getContactManager(manager->getWorkUnit().mNpIndex); desc.constraint = reinterpret_cast<PxU8*>(constraints[a]->contactManager); desc.constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT; if (contactCount == 0) { //This is the first object in the pair *startDesc = *(contactDescPtr + 1); startIndex = a; startManagerOutput = &output; } if(startDesc->bodyA != desc.bodyA || startDesc->bodyB != desc.bodyB || startDesc->linkIndexA != PxSolverConstraintDesc::RIGID_BODY || startDesc->linkIndexB != PxSolverConstraintDesc::RIGID_BODY || contactCount + output.nbContacts > PxContactBuffer::MAX_CONTACTS || manager->isChangeable() || gDisableConstraintWelding ) //If this is the first thing and no contacts...then we skip { const PxU32 stride = a - startIndex; if(contactCount > 0) { if(stride > 1) { ++numHeaders; CompoundContactManager& header = mThreadContext.compoundConstraints.insert(); header.mStartIndex = startIndex; header.mStride = PxTo16(stride); header.mReducedContactCount = PxTo16(contactCount); PxsContactManager* manager1 = constraints[startIndex]->contactManager; PxcNpWorkUnit& unit = manager1->getWorkUnit(); PX_ASSERT(startManagerOutput == &mOutputs.getContactManager(unit.mNpIndex)); header.unit = &unit; header.cmOutput = startManagerOutput; header.originalContactPatches = startManagerOutput->contactPatches; header.originalContactPoints = startManagerOutput->contactPoints; header.originalContactCount = startManagerOutput->nbContacts; header.originalPatchCount = startManagerOutput->nbPatches; header.originalForceBuffer = reinterpret_cast<PxReal*>(startManagerOutput->contactForces); header.originalStatusFlags = startManagerOutput->statusFlag; } startDesc = ++contactDescPtr; } else { //Copy back next contactDescPtr *startDesc = *(contactDescPtr+1); } contactCount = 0; startIndex = a; startManagerOutput = &output; } contactCount += output.nbContacts; } const PxU32 stride = mIslandContext.mCounts.contactManagers - startIndex; if(contactCount > 0) { if(stride > 1) { ++numHeaders; CompoundContactManager& header = mThreadContext.compoundConstraints.insert(); header.mStartIndex = startIndex; header.mStride = PxTo16(stride); header.mReducedContactCount = PxTo16(contactCount); PxsContactManager* manager = constraints[startIndex]->contactManager; PxcNpWorkUnit& unit = manager->getWorkUnit(); header.unit = &unit; header.cmOutput = startManagerOutput; header.originalContactPatches = startManagerOutput->contactPatches; header.originalContactPoints = startManagerOutput->contactPoints; header.originalContactCount = startManagerOutput->nbContacts; header.originalPatchCount = startManagerOutput->nbPatches; header.originalForceBuffer = reinterpret_cast<PxReal*>(startManagerOutput->contactForces); header.originalStatusFlags = startManagerOutput->statusFlag; } contactDescPtr++; } if(numHeaders) { const PxU32 unrollSize = 8; for(PxU32 a = 0; a < numHeaders; a+= unrollSize) { PxsSolverConstraintPostProcessTask* postProcessTask = PX_PLACEMENT_NEW( mContext.getTaskPool().allocate(sizeof(PxsSolverConstraintPostProcessTask)), PxsSolverConstraintPostProcessTask)(mContext, mThreadContext, mObjects, mSolverBodyOffset, a, PxMin(unrollSize, numHeaders - a), mMaterialManager, mOutputs); postProcessTask->setContinuation(mCont); postProcessTask->removeReference(); } } } mThreadContext.contactDescArraySize = PxU32(contactDescPtr - mThreadContext.contactConstraintDescArray); mThreadContext.mContactDescPtr = contactDescPtr; } virtual void runInternal() { startTasks(); integrate(); setupDescTask(); articulationTask(); } virtual const char* getName() const { return "PxsDynamics.solverStart"; } private: DynamicsContext& mContext; IslandContext& mIslandContext; const SolverIslandObjects mObjects; const PxU32 mSolverBodyOffset; const PxU32 mKinematicCount; IG::SimpleIslandManager& mIslandManager; PxU32* mBodyRemapTable; PxsMaterialManager* mMaterialManager; PxsContactManagerOutputIterator& mOutputs; const bool mEnhancedDeterminism; }; class PxsSolverConstraintPartitionTask : public Cm::Task { PxsSolverConstraintPartitionTask& operator=(const PxsSolverConstraintPartitionTask&); public: PxsSolverConstraintPartitionTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, bool enhancedDeterminism) : Cm::Task (context.getContextId()), mContext (context), mIslandContext (islandContext), mObjects (objects), mSolverBodyOffset (solverBodyOffset), mEnhancedDeterminism(enhancedDeterminism) {} virtual void runInternal() { PX_PROFILE_ZONE("PartitionConstraints", mContext.getContextId()); ThreadContext& mThreadContext = *mIslandContext.mThreadContext; //Compact articulation pairs... const ArticulationSolverDesc* artics = mThreadContext.getArticulations().begin(); const PxSolverConstraintDesc* descBegin = mThreadContext.contactConstraintDescArray; const PxU32 descCount = mThreadContext.contactDescArraySize; PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset; mThreadContext.mNumDifferentBodyConstraints = descCount; { mThreadContext.mNumDifferentBodyConstraints = 0; mThreadContext.mNumSelfConstraints = 0; mThreadContext.mNumStaticConstraints = 0; mThreadContext.mNumDifferentBodyFrictionConstraints = 0; mThreadContext.mNumSelfConstraintFrictionBlocks = 0; mThreadContext.mNumSelfFrictionConstraints = 0; if(descCount > 0) { ConstraintPartitionArgs args; args.mBodies = reinterpret_cast<PxU8*>(solverBodies); args.mStride = sizeof(PxSolverBody); args.mArticulationPtrs = artics; args.mContactConstraintDescriptors = descBegin; args.mNumArticulationPtrs = mThreadContext.getArticulations().size(); args.mNumBodies = mIslandContext.mCounts.bodies; args.mNumContactConstraintDescriptors = descCount; args.mOrderedContactConstraintDescriptors = mThreadContext.orderedContactConstraints; args.mOverflowConstraintDescriptors = mThreadContext.tempConstraintDescArray; args.mNumDifferentBodyConstraints = args.mNumSelfConstraints = args.mNumStaticConstraints = 0; args.mConstraintsPerPartition = &mThreadContext.mConstraintsPerPartition; args.mNumOverflowConstraints = 0; //args.mBitField = &mThreadContext.mPartitionNormalizationBitmap; // PT: removed, unused args.mEnhancedDeterminism = mEnhancedDeterminism; args.mForceStaticConstraintsToSolver = mContext.getFrictionType() != PxFrictionType::ePATCH; args.mMaxPartitions = PX_MAX_U32; mThreadContext.mMaxPartitions = partitionContactConstraints(args); mThreadContext.mNumDifferentBodyConstraints = args.mNumDifferentBodyConstraints; mThreadContext.mNumSelfConstraints = args.mNumSelfConstraints; mThreadContext.mNumStaticConstraints = args.mNumStaticConstraints; } else { PxMemZero(mThreadContext.mConstraintsPerPartition.begin(), sizeof(PxU32)*mThreadContext.mConstraintsPerPartition.capacity()); } PX_ASSERT((mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumSelfConstraints + mThreadContext.mNumStaticConstraints) == descCount); } } virtual const char* getName() const { return "PxsDynamics.solverConstraintPartition"; } DynamicsContext& mContext; IslandContext& mIslandContext; const SolverIslandObjects mObjects; const PxU32 mSolverBodyOffset; const bool mEnhancedDeterminism; }; class PxsSolverSetupSolveTask : public Cm::Task { PxsSolverSetupSolveTask& operator=(const PxsSolverSetupSolveTask&); public: PxsSolverSetupSolveTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, IG::IslandSim& islandSim) : Cm::Task (context.getContextId()), mContext (context), mIslandContext (islandContext), mObjects (objects), mSolverBodyOffset (solverBodyOffset), mIslandSim (islandSim) {} virtual void runInternal() { ThreadContext& mThreadContext = *mIslandContext.mThreadContext; PxSolverConstraintDesc* contactDescBegin = mThreadContext.orderedContactConstraints; PxSolverConstraintDesc* contactDescPtr = mThreadContext.orderedContactConstraints; PxSolverBody* solverBodies = mContext.mSolverBodyPool.begin() + mSolverBodyOffset; PxSolverBodyData* solverBodyDatas = mContext.mSolverBodyDataPool.begin(); PxU32 frictionDescCount = mThreadContext.mNumDifferentBodyFrictionConstraints; PxU32 j = 0, i = 0; //On PS3, self-constraints will be bumped to the end of the constraint list //and processed separately. On PC/360, they will be mixed in the array and //classed as "different body" constraints regardless of the fact that they're self-constraints. //PxU32 numBatches = mThreadContext.numDifferentBodyBatchHeaders; // TODO: maybe replace with non-null joints from end of the array PxU32 numBatches = 0; PxU32 currIndex = 0; for(PxU32 a = 0; a < mThreadContext.mConstraintsPerPartition.size(); ++a) { PxU32 endIndex = currIndex + mThreadContext.mConstraintsPerPartition[a]; PxU32 numBatchesInPartition = 0; for(PxU32 b = currIndex; b < endIndex; ++b) { PxConstraintBatchHeader& _header = mThreadContext.contactConstraintBatchHeaders[b]; PxU16 stride = _header.stride, newStride = _header.stride; PxU32 startIndex = j; for(PxU16 c = 0; c < stride; ++c) { if(getConstraintLength(contactDescBegin[i]) == 0) { newStride--; i++; } else { if(i!=j) contactDescBegin[j] = contactDescBegin[i]; i++; j++; contactDescPtr++; } } if(newStride != 0) { mThreadContext.contactConstraintBatchHeaders[numBatches].startIndex = startIndex; mThreadContext.contactConstraintBatchHeaders[numBatches].stride = newStride; PxU8 type = *contactDescBegin[startIndex].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 < newStride; ++c) { if(*contactDescBegin[startIndex+c].constraint == DY_SC_TYPE_RB_CONTACT) { type = DY_SC_TYPE_RB_CONTACT; } } } mThreadContext.contactConstraintBatchHeaders[numBatches].constraintType = type; numBatches++; numBatchesInPartition++; } } PxU32 numHeaders = numBatchesInPartition; currIndex += mThreadContext.mConstraintsPerPartition[a]; mThreadContext.mConstraintsPerPartition[a] = numHeaders; } PxU32 contactDescCount = PxU32(contactDescPtr - contactDescBegin); mThreadContext.mNumDifferentBodyConstraints = contactDescCount; mThreadContext.numContactConstraintBatches = numBatches; mThreadContext.mNumSelfConstraints = j - contactDescCount; //self constraint count contactDescCount = j; mThreadContext.mOrderedContactDescCount = j; //Now do the friction constraints if we're not using the sticky model if(mContext.getFrictionType() != PxFrictionType::ePATCH) { PxSolverConstraintDesc* frictionDescBegin = mThreadContext.frictionConstraintDescArray.begin(); PxSolverConstraintDesc* frictionDescPtr = frictionDescBegin; PxArray<PxConstraintBatchHeader>& frictionHeaderArray = mThreadContext.frictionConstraintBatchHeaders; frictionHeaderArray.forceSize_Unsafe(0); frictionHeaderArray.reserve(mThreadContext.numContactConstraintBatches); PxConstraintBatchHeader* headers = frictionHeaderArray.begin(); PxArray<PxU32>& constraintsPerPartition = mThreadContext.mConstraintsPerPartition; PxArray<PxU32>& frictionConstraintsPerPartition = mThreadContext.mFrictionConstraintsPerPartition; frictionConstraintsPerPartition.forceSize_Unsafe(0); frictionConstraintsPerPartition.reserve(constraintsPerPartition.capacity()); PxU32 fricI = 0; PxU32 startIndex = 0; PxU32 fricHeaders = 0; for(PxU32 k = 0; k < constraintsPerPartition.size(); ++k) { PxU32 numBatchesInK = constraintsPerPartition[k]; PxU32 endIndex = startIndex + numBatchesInK; PxU32 startFricH = fricHeaders; for(PxU32 a = startIndex; a < endIndex; ++a) { PxConstraintBatchHeader& _header = mThreadContext.contactConstraintBatchHeaders[a]; PxU16 stride = _header.stride; if(_header.constraintType == DY_SC_TYPE_RB_CONTACT || _header.constraintType == DY_SC_TYPE_EXT_CONTACT || _header.constraintType == DY_SC_TYPE_STATIC_CONTACT) { PxU8 type = 0; //Extract friction from this constraint for(PxU16 b = 0; b < stride; ++b) { //create the headers... PxSolverConstraintDesc& desc = contactDescBegin[_header.startIndex + b]; PX_ASSERT(desc.constraint); SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint); PxU32 frictionOffset = header->frictionOffset; PxU8* PX_RESTRICT constraint = reinterpret_cast<PxU8*>(header) + frictionOffset; const PxU32 origLength = getConstraintLength(desc); const PxU32 length = (origLength - frictionOffset); setConstraintLength(*frictionDescPtr, length); frictionDescPtr->constraint = constraint; frictionDescPtr->bodyA = desc.bodyA; frictionDescPtr->bodyB = desc.bodyB; frictionDescPtr->bodyADataIndex = desc.bodyADataIndex; frictionDescPtr->bodyBDataIndex = desc.bodyBDataIndex; frictionDescPtr->linkIndexA = desc.linkIndexA; frictionDescPtr->linkIndexB = desc.linkIndexB; frictionDescPtr->writeBack = NULL; type = *constraint; frictionDescPtr++; } headers->startIndex = fricI; headers->stride = stride; headers->constraintType = type; headers++; fricHeaders++; fricI += stride; } else if(_header.constraintType == DY_SC_TYPE_BLOCK_RB_CONTACT || _header.constraintType == DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT) { //KS - TODO - Extract block of 4 contacts from this constraint. This isn't implemented yet for coulomb friction model PX_ASSERT(contactDescBegin[_header.startIndex].constraint); SolverContactCoulombHeader4* head = reinterpret_cast<SolverContactCoulombHeader4*>(contactDescBegin[_header.startIndex].constraint); PxU32 frictionOffset = head->frictionOffset; PxU8* PX_RESTRICT constraint = reinterpret_cast<PxU8*>(head) + frictionOffset; const PxU32 origLength = getConstraintLength(contactDescBegin[_header.startIndex]); const PxU32 length = (origLength - frictionOffset); PxU8 type = *constraint; PX_ASSERT(type == DY_SC_TYPE_BLOCK_FRICTION || type == DY_SC_TYPE_BLOCK_STATIC_FRICTION); for(PxU32 b = 0; b < 4; ++b) { PxSolverConstraintDesc& desc = contactDescBegin[_header.startIndex+b]; setConstraintLength(*frictionDescPtr, length); frictionDescPtr->constraint = constraint; frictionDescPtr->bodyA = desc.bodyA; frictionDescPtr->bodyB = desc.bodyB; frictionDescPtr->bodyADataIndex = desc.bodyADataIndex; frictionDescPtr->bodyBDataIndex = desc.bodyBDataIndex; frictionDescPtr->linkIndexA = desc.linkIndexA; frictionDescPtr->linkIndexB = desc.linkIndexB; frictionDescPtr->writeBack = NULL; frictionDescPtr++; } headers->startIndex = fricI; headers->stride = stride; headers->constraintType = type; headers++; fricHeaders++; fricI += stride; } } startIndex += numBatchesInK; if(startFricH < fricHeaders) { frictionConstraintsPerPartition.pushBack(fricHeaders - startFricH); } } frictionDescCount = PxU32(frictionDescPtr - frictionDescBegin); mThreadContext.mNumDifferentBodyFrictionConstraints = frictionDescCount; frictionHeaderArray.forceSize_Unsafe(PxU32(headers - frictionHeaderArray.begin())); mThreadContext.mNumSelfFrictionConstraints = fricI - frictionDescCount; //self constraint count mThreadContext.mNumDifferentBodyFrictionConstraints = frictionDescCount; frictionDescCount = fricI; mThreadContext.mOrderedFrictionDescCount = frictionDescCount; } { { PX_PROFILE_ZONE("Dynamics.solver", mContext.getContextId()); PxSolverConstraintDesc* contactDescs = mThreadContext.orderedContactConstraints; PxSolverConstraintDesc* frictionDescs = mThreadContext.frictionConstraintDescArray.begin(); PxI32* thresholdPairsOut = &mContext.mThresholdStreamOut; SolverIslandParams& params = *reinterpret_cast<SolverIslandParams*>(mContext.getTaskPool().allocate(sizeof(SolverIslandParams))); params.positionIterations = mThreadContext.mMaxSolverPositionIterations; params.velocityIterations = mThreadContext.mMaxSolverVelocityIterations; params.bodyListStart = solverBodies; params.bodyDataList = solverBodyDatas; params.solverBodyOffset = mSolverBodyOffset; params.bodyListSize = mIslandContext.mCounts.bodies; params.articulationListStart = mThreadContext.getArticulations().begin(); params.articulationListSize = mThreadContext.getArticulations().size(); params.constraintList = contactDescs; params.constraintIndex = 0; params.constraintIndexCompleted = 0; params.bodyListIndex = 0; params.bodyListIndexCompleted = 0; params.articSolveIndex = 0; params.articSolveIndexCompleted = 0; params.bodyIntegrationListIndex = 0; params.thresholdStream = mContext.getThresholdStream().begin(); params.thresholdStreamLength = mContext.getThresholdStream().size(); params.outThresholdPairs = thresholdPairsOut; params.motionVelocityArray = mThreadContext.motionVelocityArray; params.bodyArray = mThreadContext.mBodyCoreArray; params.numObjectsIntegrated = 0; params.constraintBatchHeaders = mThreadContext.contactConstraintBatchHeaders; params.numConstraintHeaders = mThreadContext.numContactConstraintBatches; params.headersPerPartition = mThreadContext.mConstraintsPerPartition.begin(); params.nbPartitions = mThreadContext.mConstraintsPerPartition.size(); params.rigidBodies = const_cast<PxsRigidBody**>(mObjects.bodies); params.frictionHeadersPerPartition = mThreadContext.mFrictionConstraintsPerPartition.begin(); params.nbFrictionPartitions = mThreadContext.mFrictionConstraintsPerPartition.size(); params.frictionConstraintBatches = mThreadContext.frictionConstraintBatchHeaders.begin(); params.numFrictionConstraintHeaders = mThreadContext.frictionConstraintBatchHeaders.size(); params.frictionConstraintIndex = 0; params.frictionConstraintList = frictionDescs; params.mMaxArticulationLinks = mThreadContext.mMaxArticulationLinks; params.dt = mContext.mDt; params.invDt = mContext.mInvDt; const PxU32 unrollSize = 8; const PxU32 denom = PxMax(1u, (mThreadContext.mMaxPartitions*unrollSize)); const PxU32 MaxTasks = getTaskManager()->getCpuDispatcher()->getWorkerCount(); // PT: small improvement: if there's no contacts, use the number of bodies instead. // That way the integration work still benefits from multiple tasks. const PxU32 numWorkItems = mThreadContext.numContactConstraintBatches ? mThreadContext.numContactConstraintBatches : mIslandContext.mCounts.bodies; const PxU32 idealThreads = (numWorkItems+denom-1)/denom; const PxU32 numTasks = PxMax(1u, PxMin(idealThreads, MaxTasks)); if(numTasks > 1) { const PxU32 idealBatchSize = PxMax(unrollSize, idealThreads*unrollSize/(numTasks*2)); params.batchSize = idealBatchSize; //assigning ideal batch size for the solver to grab work at. Only needed by the multi-threaded island solver. for(PxU32 a = 1; a < numTasks; ++a) { void* tsk = mContext.getTaskPool().allocate(sizeof(PxsParallelSolverTask)); PxsParallelSolverTask* pTask = PX_PLACEMENT_NEW(tsk, PxsParallelSolverTask)( params, mContext, mIslandSim); //Force to complete before merge task! pTask->setContinuation(mCont); pTask->removeReference(); } //Avoid kicking off one parallel task when we can do the work inline in this function { PX_PROFILE_ZONE("Dynamics.parallelSolve", mContext.getContextId()); solveParallel(mContext, params, mIslandSim); } const PxI32 numBodiesPlusArtics = PxI32( mIslandContext.mCounts.bodies + mIslandContext.mCounts.articulations ); PxI32* numObjectsIntegrated = &params.numObjectsIntegrated; WAIT_FOR_PROGRESS_NO_TIMER(numObjectsIntegrated, numBodiesPlusArtics); } else { mThreadContext.mZVector.forceSize_Unsafe(0); mThreadContext.mZVector.reserve(mThreadContext.mMaxArticulationLinks); mThreadContext.mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks); mThreadContext.mDeltaV.forceSize_Unsafe(0); mThreadContext.mDeltaV.reserve(mThreadContext.mMaxArticulationLinks); mThreadContext.mDeltaV.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks); params.Z = mThreadContext.mZVector.begin(); params.deltaV = mThreadContext.mDeltaV.begin(); //Only one task - a small island so do a sequential solve (avoid the atomic overheads) mContext.mSolverCore[mContext.getFrictionType()]->solveV_Blocks(params); const PxU32 bodyCountMin1 = mIslandContext.mCounts.bodies - 1u; PxSolverBodyData* solverBodyData2 = solverBodyDatas + mSolverBodyOffset + 1; for(PxU32 k=0; k < mIslandContext.mCounts.bodies; k++) { const PxU32 prefetchAddress = PxMin(k+4, bodyCountMin1); PxPrefetchLine(mThreadContext.mBodyCoreArray[prefetchAddress]); PxPrefetchLine(&mThreadContext.motionVelocityArray[k], 128); PxPrefetchLine(&mThreadContext.mBodyCoreArray[prefetchAddress], 128); PxPrefetchLine(&mObjects.bodies[prefetchAddress]); PxSolverBodyData& solverBodyData = solverBodyData2[k]; PxsRigidBody& rBody = *mObjects.bodies[k]; PxsBodyCore& core = rBody.getCore(); integrateCore(mThreadContext.motionVelocityArray[k].linear, mThreadContext.motionVelocityArray[k].angular, solverBodies[k], solverBodyData, mContext.mDt, core.lockFlags); rBody.mLastTransform = core.body2World; core.body2World = solverBodyData.body2World; core.linearVelocity = solverBodyData.linearVelocity; core.angularVelocity = solverBodyData.angularVelocity; const bool hasStaticTouch = mIslandSim.getIslandStaticTouchCount(PxNodeIndex(solverBodyData.nodeIndex)) != 0; sleepCheck(mObjects.bodies[k], mContext.mDt, mContext.mEnableStabilization, mThreadContext.motionVelocityArray[k], hasStaticTouch); } for(PxU32 cnt=0;cnt<mIslandContext.mCounts.articulations;cnt++) { ArticulationSolverDesc &d = mThreadContext.getArticulations()[cnt]; //PX_PROFILE_ZONE("Articulations.integrate", mContext.getContextId()); ArticulationPImpl::updateBodies(d, mThreadContext.mDeltaV.begin(), mContext.getDt()); } } } } } virtual const char* getName() const { return "PxsDynamics.solverSetupSolve"; } DynamicsContext& mContext; IslandContext& mIslandContext; const SolverIslandObjects mObjects; const PxU32 mSolverBodyOffset; IG::IslandSim& mIslandSim; }; class PxsSolverEndTask : public Cm::Task { PxsSolverEndTask& operator=(const PxsSolverEndTask&); public: PxsSolverEndTask(DynamicsContext& context, IslandContext& islandContext, const SolverIslandObjects& objects, PxU32 solverBodyOffset, PxsContactManagerOutputIterator& cmOutputs) : Cm::Task (context.getContextId()), mContext (context), mIslandContext (islandContext), mObjects (objects), mSolverBodyOffset (solverBodyOffset), mOutputs (cmOutputs) {} virtual void runInternal() { PX_PROFILE_ZONE("Dynamics.endTask", getContextId()); ThreadContext& mThreadContext = *mIslandContext.mThreadContext; #if PX_ENABLE_SIM_STATS mThreadContext.getSimStats().numAxisSolverConstraints += mThreadContext.mAxisConstraintCount; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif //Patch up the contact managers (TODO - fix up force writeback) PxU32 numCompoundConstraints = mThreadContext.compoundConstraints.size(); for(PxU32 i = 0; i < numCompoundConstraints; ++i) { CompoundContactManager& manager = mThreadContext.compoundConstraints[i]; PxsContactManagerOutput* cmOutput = manager.cmOutput; PxReal* contactForces = reinterpret_cast<PxReal*>(cmOutput->contactForces); PxU32 contactCount = cmOutput->nbContacts; cmOutput->contactPatches = manager.originalContactPatches; cmOutput->contactPoints = manager.originalContactPoints; cmOutput->nbContacts = manager.originalContactCount; cmOutput->nbPatches = manager.originalPatchCount; cmOutput->statusFlag = manager.originalStatusFlags; cmOutput->contactForces = manager.originalForceBuffer; for(PxU32 a = 1; a < manager.mStride; ++a) { PxsContactManager* pManager = mThreadContext.orderedContactList[manager.mStartIndex + a]->contactManager; pManager->getWorkUnit().frictionDataPtr = manager.unit->frictionDataPtr; pManager->getWorkUnit().frictionPatchCount = manager.unit->frictionPatchCount; //pManager->getWorkUnit().prevFrictionPatchCount = manager.unit->prevFrictionPatchCount; } //This is a stride-based contact force writer. The assumption is that we may have skipped certain unimportant contacts reported by the //discrete narrow phase if(contactForces) { PxU32 currentContactIndex = 0; PxU32 currentManagerIndex = manager.mStartIndex; PxU32 currentManagerContactIndex = 0; for(PxU32 a = 0; a < contactCount; ++a) { PxU32 index = manager.forceBufferList[a]; PxsContactManager* pManager = mThreadContext.orderedContactList[currentManagerIndex]->contactManager; PxsContactManagerOutput* output = &mOutputs.getContactManager(pManager->getWorkUnit().mNpIndex); while(currentContactIndex < index || output->nbContacts == 0) { //Step forwards...first in this manager... PxU32 numToStep = PxMin(index - currentContactIndex, PxU32(output->nbContacts) - currentManagerContactIndex); currentContactIndex += numToStep; currentManagerContactIndex += numToStep; if(currentManagerContactIndex == output->nbContacts) { currentManagerIndex++; currentManagerContactIndex = 0; pManager = mThreadContext.orderedContactList[currentManagerIndex]->contactManager; output = &mOutputs.getContactManager(pManager->getWorkUnit().mNpIndex); } } if(output->nbContacts > 0 && output->contactForces) output->contactForces[currentManagerContactIndex] = contactForces[a]; } } } mThreadContext.compoundConstraints.forceSize_Unsafe(0); mThreadContext.mConstraintBlockManager.reset(); mContext.putThreadContext(&mThreadContext); } virtual const char* getName() const { return "PxsDynamics.solverEnd"; } DynamicsContext& mContext; IslandContext& mIslandContext; const SolverIslandObjects mObjects; const PxU32 mSolverBodyOffset; PxsContactManagerOutputIterator& mOutputs; }; class PxsSolverCreateFinalizeConstraintsTask : public Cm::Task { PxsSolverCreateFinalizeConstraintsTask& operator=(const PxsSolverCreateFinalizeConstraintsTask&); public: PxsSolverCreateFinalizeConstraintsTask(DynamicsContext& context, IslandContext& islandContext, PxU32 solverDataOffset, PxsContactManagerOutputIterator& outputs, bool enhancedDeterminism) : Cm::Task (context.getContextId()), mContext (context), mIslandContext (islandContext), mSolverDataOffset (solverDataOffset), mOutputs (outputs), mEnhancedDeterminism (enhancedDeterminism) { } virtual void runInternal(); virtual const char* getName() const { return "PxsDynamics.solverCreateFinalizeConstraints"; } DynamicsContext& mContext; IslandContext& mIslandContext; const PxU32 mSolverDataOffset; PxsContactManagerOutputIterator& mOutputs; const bool mEnhancedDeterminism; }; // helper function to join two tasks together and ensure ref counts are correct static void chainTasks(PxLightCpuTask* first, PxLightCpuTask* next) { first->setContinuation(next); next->removeReference(); } static void createSolverTaskChain( DynamicsContext& dynamicContext, const SolverIslandObjects& objects, const PxsIslandIndices& counts, PxU32 solverBodyOffset, IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxsMaterialManager* materialManager, PxBaseTask* continuation, PxsContactManagerOutputIterator& iterator, bool useEnhancedDeterminism) { Cm::FlushPool& taskPool = dynamicContext.getTaskPool(); taskPool.lock(); IslandContext* islandContext = reinterpret_cast<IslandContext*>(taskPool.allocate(sizeof(IslandContext))); islandContext->mThreadContext = NULL; islandContext->mCounts = counts; // create lead task PxsSolverStartTask* startTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverStartTask)), PxsSolverStartTask)(dynamicContext, *islandContext, objects, solverBodyOffset, dynamicContext.getKinematicCount(), islandManager, bodyRemapTable, materialManager, iterator, useEnhancedDeterminism); PxsSolverEndTask* endTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverEndTask)), PxsSolverEndTask)(dynamicContext, *islandContext, objects, solverBodyOffset, iterator); PxsSolverCreateFinalizeConstraintsTask* createFinalizeConstraintsTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverCreateFinalizeConstraintsTask)), PxsSolverCreateFinalizeConstraintsTask)(dynamicContext, *islandContext, solverBodyOffset, iterator, useEnhancedDeterminism); PxsSolverSetupSolveTask* setupSolveTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverSetupSolveTask)), PxsSolverSetupSolveTask)(dynamicContext, *islandContext, objects, solverBodyOffset, islandManager.getAccurateIslandSim()); PxsSolverConstraintPartitionTask* partitionConstraintsTask = PX_PLACEMENT_NEW(taskPool.allocateNotThreadSafe(sizeof(PxsSolverConstraintPartitionTask)), PxsSolverConstraintPartitionTask)(dynamicContext, *islandContext, objects, solverBodyOffset, useEnhancedDeterminism); taskPool.unlock(); endTask->setContinuation(continuation); // set up task chain in reverse order chainTasks(setupSolveTask, endTask); chainTasks(createFinalizeConstraintsTask, setupSolveTask); chainTasks(partitionConstraintsTask, createFinalizeConstraintsTask); chainTasks(startTask, partitionConstraintsTask); startTask->removeReference(); } namespace { class UpdateContinuationTask : public Cm::Task { DynamicsContext& mContext; IG::SimpleIslandManager& mSimpleIslandManager; PxBaseTask* mLostTouchTask; PxU32 mMaxArticulationLinks; PX_NOCOPY(UpdateContinuationTask) public: UpdateContinuationTask(DynamicsContext& context, IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* lostTouchTask, PxU64 contextID, PxU32 maxLinks) : Cm::Task(contextID), mContext(context), mSimpleIslandManager(simpleIslandManager), mLostTouchTask(lostTouchTask), mMaxArticulationLinks(maxLinks) { } virtual const char* getName() const { return "UpdateContinuationTask"; } virtual void runInternal() { mContext.updatePostKinematic(mSimpleIslandManager, mCont, mLostTouchTask, mMaxArticulationLinks); //Allow lost touch task to run once all tasks have be scheduled mLostTouchTask->removeReference(); } }; class KinematicCopyTask : public Cm::Task { const PxNodeIndex* const mKinematicIndices; const PxU32 mNbKinematics; const IG::IslandSim& mIslandSim; PxSolverBodyData* mBodyData; PX_NOCOPY(KinematicCopyTask) public: static const PxU32 NbKinematicsPerTask = 1024; KinematicCopyTask(const PxNodeIndex* const kinematicIndices, PxU32 nbKinematics, const IG::IslandSim& islandSim, PxSolverBodyData* datas, PxU64 contextID) : Cm::Task(contextID), mKinematicIndices(kinematicIndices), mNbKinematics(nbKinematics), mIslandSim(islandSim), mBodyData(datas) { } virtual const char* getName() const { return "KinematicCopyTask"; } virtual void runInternal() { for (PxU32 i = 0; i<mNbKinematics; i++) { PxsRigidBody* rigidBody = mIslandSim.getRigidBody(mKinematicIndices[i]); const PxsBodyCore& core = rigidBody->getCore(); copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, mKinematicIndices[i].index(), core.contactReportThreshold, mBodyData[i + 1], core.lockFlags, 0.f, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES); rigidBody->saveLastCCDTransform(); } } }; } void DynamicsContext::update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxvNphaseImplementationContext* nphase, PxU32 /*maxPatches*/, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& /*changedHandleMap*/) { PX_PROFILE_ZONE("Dynamics.solverQueueTasks", mContextID); mOutputIterator = nphase->getContactManagerOutputs(); mDt = dt; mInvDt = dt == 0.0f ? 0.0f : 1.0f / dt; mGravity = gravity; const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim(); const PxU32 islandCount = islandSim.getNbActiveIslands(); const PxU32 activatedContactCount = islandSim.getNbActivatedEdges(IG::Edge::eCONTACT_MANAGER); const IG::EdgeIndex* const activatingEdges = islandSim.getActivatedEdges(IG::Edge::eCONTACT_MANAGER); for (PxU32 a = 0; a < activatedContactCount; ++a) { PxsContactManager* cm = simpleIslandManager.getContactManager(activatingEdges[a]); if (cm) cm->getWorkUnit().frictionPatchCount = 0; //KS - zero the friction patch count on any activating edges } #if PX_ENABLE_SIM_STATS if (islandCount > 0) { mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics(); mSimStats.mNbActiveDynamicBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); mSimStats.mNbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT); } else { mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics(); mSimStats.mNbActiveDynamicBodies = 0; mSimStats.mNbActiveConstraints = 0; } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif mThresholdStreamOut = 0; resetThreadContexts(); //If there is no work to do then we can do nothing at all. if(!islandCount) return; //Block to make sure it doesn't run before stage2 of update! lostTouchTask->addReference(); UpdateContinuationTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateContinuationTask)), UpdateContinuationTask) (*this, simpleIslandManager, lostTouchTask, mContextID, maxArticulationLinks); task->setContinuation(continuation); //KS - test that world solver body's velocities are finite and 0, then set it to 0. //Technically, the velocity should always be 0 but can be stomped if a NAN creeps into the simulation. PX_ASSERT(mWorldSolverBody.linearVelocity == PxVec3(0.0f)); PX_ASSERT(mWorldSolverBody.angularState == PxVec3(0.0f)); PX_ASSERT(mWorldSolverBody.linearVelocity.isFinite()); PX_ASSERT(mWorldSolverBody.angularState.isFinite()); mWorldSolverBody.linearVelocity = mWorldSolverBody.angularState = PxVec3(0.f); const PxU32 kinematicCount = islandSim.getNbActiveKinematics(); const PxNodeIndex* const kinematicIndices = islandSim.getActiveKinematics(); mKinematicCount = kinematicCount; const PxU32 bodyCount = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); const PxU32 numArtics = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE); { if (kinematicCount + bodyCount > mSolverBodyPool.capacity()) { mSolverBodyPool.reserve((kinematicCount + bodyCount + 31) & ~31); // pad out to 32 * 128 = 4k to prevent alloc churn mSolverBodyDataPool.reserve((kinematicCount + bodyCount + 31 + 1) & ~31); // pad out to 32 * 128 = 4k to prevent alloc churn mSolverBodyRemapTable.reserve((kinematicCount + bodyCount + 31 + 1) & ~31); } { PxSolverBody emptySolverBody; PxMemZero(&emptySolverBody, sizeof(PxSolverBody)); mSolverBodyPool.resize(kinematicCount + bodyCount, emptySolverBody); PxSolverBodyData emptySolverBodyData; PxMemZero(&emptySolverBodyData, sizeof(PxSolverBodyData)); mSolverBodyDataPool.resize(kinematicCount + bodyCount + 1, emptySolverBodyData); mSolverBodyRemapTable.resize(bodyCount); } // integrate and copy all the kinematics - overkill, since not all kinematics // need solver bodies mSolverBodyDataPool[0] = mWorldSolverBodyData; if(kinematicCount) { PX_PROFILE_ZONE("Dynamics.updateKinematics", mContextID); PxMemZero(mSolverBodyPool.begin(), kinematicCount * sizeof(PxSolverBody)); for (PxU32 i = 0; i < kinematicCount; i+= KinematicCopyTask::NbKinematicsPerTask) { const PxU32 nbToProcess = PxMin(KinematicCopyTask::NbKinematicsPerTask, kinematicCount - i); KinematicCopyTask* copyTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(KinematicCopyTask)), KinematicCopyTask) (&kinematicIndices[i], nbToProcess, islandSim, &mSolverBodyDataPool[i], mContextID); copyTask->setContinuation(task); copyTask->removeReference(); } } } //Resize arrays of solver constraints... const PxU32 numArticulationConstraints = numArtics* maxArticulationLinks; //Just allocate enough memory to fit worst-case maximum size articulations... const PxU32 nbActiveContactManagers = islandSim.getNbActiveEdges(IG::Edge::eCONTACT_MANAGER); const PxU32 nbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT); const PxU32 totalConstraintCount = nbActiveConstraints + nbActiveContactManagers + numArticulationConstraints; mSolverConstraintDescPool.forceSize_Unsafe(0); mSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mOrderedSolverConstraintDescPool.forceSize_Unsafe(0); mOrderedSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mOrderedSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mTempSolverConstraintDescPool.forceSize_Unsafe(0); mTempSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mTempSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mContactConstraintBatchHeaders.forceSize_Unsafe(0); mContactConstraintBatchHeaders.reserve((totalConstraintCount + 63) & (~63)); mContactConstraintBatchHeaders.forceSize_Unsafe(totalConstraintCount); mContactList.forceSize_Unsafe(0); mContactList.reserve((nbActiveContactManagers + 63u) & (~63u)); mContactList.forceSize_Unsafe(nbActiveContactManagers); mMotionVelocityArray.forceSize_Unsafe(0); mMotionVelocityArray.reserve((bodyCount + 63u) & (~63u)); mMotionVelocityArray.forceSize_Unsafe(bodyCount); mBodyCoreArray.forceSize_Unsafe(0); mBodyCoreArray.reserve((bodyCount + 63u) & (~63u)); mBodyCoreArray.forceSize_Unsafe(bodyCount); mRigidBodyArray.forceSize_Unsafe(0); mRigidBodyArray.reserve((bodyCount + 63u) & (~63u)); mRigidBodyArray.forceSize_Unsafe(bodyCount); mArticulationArray.forceSize_Unsafe(0); mArticulationArray.reserve((numArtics + 63u) & (~63u)); mArticulationArray.forceSize_Unsafe(numArtics); mNodeIndexArray.forceSize_Unsafe(0); mNodeIndexArray.reserve((bodyCount + 63u) & (~63u)); mNodeIndexArray.forceSize_Unsafe(bodyCount); ThresholdStream& stream = getThresholdStream(); stream.forceSize_Unsafe(0); stream.reserve(PxNextPowerOfTwo(nbActiveContactManagers != 0 ? nbActiveContactManagers - 1 : nbActiveContactManagers)); //flip exceeded force threshold buffer mCurrentIndex = 1 - mCurrentIndex; task->removeReference(); } void DynamicsContext::updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* /*continuation*/, PxBaseTask* lostTouchTask, PxU32 maxLinks) { const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim(); const PxU32 islandCount = islandSim.getNbActiveIslands(); PxU32 constraintIndex = 0; PxU32 solverBatchMax = mSolverBatchSize; PxU32 articulationBatchMax = mSolverArticBatchSize; PxU32 minimumConstraintCount = 1; //create force threshold tasks to produce force change events PxsForceThresholdTask* forceThresholdTask = PX_PLACEMENT_NEW(getTaskPool().allocate(sizeof(PxsForceThresholdTask)), PxsForceThresholdTask)(*this); forceThresholdTask->setContinuation(lostTouchTask); const IG::IslandId*const islandIds = islandSim.getActiveIslands(); PxU32 currentIsland = 0; PxU32 currentBodyIndex = 0; PxU32 currentArticulation = 0; PxU32 currentContact = 0; //while(start<sentinel) while(currentIsland < islandCount) { SolverIslandObjects objectStarts; objectStarts.articulations = mArticulationArray.begin()+ currentArticulation; objectStarts.bodies = mRigidBodyArray.begin() + currentBodyIndex; objectStarts.contactManagers = mContactList.begin() + currentContact; objectStarts.constraintDescs = mSolverConstraintDescPool.begin() + constraintIndex; objectStarts.orderedConstraintDescs = mOrderedSolverConstraintDescPool.begin() + constraintIndex; objectStarts.tempConstraintDescs = mTempSolverConstraintDescPool.begin() + constraintIndex; objectStarts.constraintBatchHeaders = mContactConstraintBatchHeaders.begin() + constraintIndex; objectStarts.motionVelocities = mMotionVelocityArray.begin() + currentBodyIndex; objectStarts.bodyCoreArray = mBodyCoreArray.begin() + currentBodyIndex; objectStarts.islandIds = islandIds + currentIsland; objectStarts.bodyRemapTable = mSolverBodyRemapTable.begin(); objectStarts.nodeIndexArray = mNodeIndexArray.begin() + currentBodyIndex; PxU32 startIsland = currentIsland; PxU32 constraintCount = 0; PxU32 nbArticulations = 0; PxU32 nbBodies = 0; PxU32 nbConstraints = 0; PxU32 nbContactManagers =0; // islandSim.checkInternalConsistency(); //KS - logic is a bit funky here. We will keep rolling the island together provided currentIsland < islandCount AND either we haven't exceeded the max number of bodies or we have //zero constraints AND we haven't exceeded articulation batch counts (it's still currently beneficial to keep articulations in separate islands but this is only temporary). while((currentIsland < islandCount && (nbBodies < solverBatchMax || constraintCount < minimumConstraintCount)) && nbArticulations < articulationBatchMax) { const IG::Island& island = islandSim.getIsland(islandIds[currentIsland]); nbBodies += island.mNodeCount[IG::Node::eRIGID_BODY_TYPE]; nbArticulations += island.mNodeCount[IG::Node::eARTICULATION_TYPE]; nbConstraints += island.mEdgeCount[IG::Edge::eCONSTRAINT]; nbContactManagers += island.mEdgeCount[IG::Edge::eCONTACT_MANAGER]; constraintCount = nbConstraints + nbContactManagers; currentIsland++; } objectStarts.numIslands = currentIsland - startIsland; constraintIndex += nbArticulations* maxLinks; PxsIslandIndices counts; counts.articulations = nbArticulations; counts.bodies = nbBodies; counts.constraints = nbConstraints; counts.contactManagers = nbContactManagers; if(counts.articulations + counts.bodies > 0) { createSolverTaskChain(*this, objectStarts, counts, mKinematicCount + currentBodyIndex, simpleIslandManager, mSolverBodyRemapTable.begin(), mMaterialManager, forceThresholdTask, mOutputIterator, mUseEnhancedDeterminism); } currentBodyIndex += nbBodies; currentArticulation += nbArticulations; currentContact += nbContactManagers; constraintIndex += constraintCount; } //kick off forceThresholdTask forceThresholdTask->removeReference(); } void DynamicsContext::mergeResults() { PX_PROFILE_ZONE("Dynamics.solverMergeResults", mContextID); //OK. Sum up sim stats here... #if PX_ENABLE_SIM_STATS PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool); ThreadContext* threadContext = threadContextIt.getNext(); while(threadContext != NULL) { ThreadContext::ThreadSimStats& threadStats = threadContext->getSimStats(); addThreadStats(threadStats); threadStats.clear(); threadContext = threadContextIt.getNext(); } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif } static void preIntegrationParallel( PxF32 dt, PxsBodyCore*const* bodyArray, // INOUT: core body attributes PxsRigidBody*const* originalBodyArray, // IN: original bodies (LEGACY - DON'T deref the ptrs!!) PxU32 const* nodeIndexArray, // IN: island node index PxU32 bodyCount, // IN: body count PxSolverBodyData* solverBodyDataPool, // IN: solver body data pool (space preallocated) volatile PxU32* maxSolverPositionIterations, volatile PxU32* maxSolverVelocityIterations, const PxVec3& gravity) { PxU32 localMaxPosIter = 0; PxU32 localMaxVelIter = 0; for(PxU32 a = 1; a < bodyCount; ++a) { PxU32 i = a-1; PxPrefetchLine(bodyArray[a]); PxPrefetchLine(bodyArray[a],128); PxPrefetchLine(&solverBodyDataPool[a]); PxPrefetchLine(&solverBodyDataPool[a],128); PxsBodyCore& core = *bodyArray[i]; const PxsRigidBody& rBody = *originalBodyArray[i]; const PxU16 iterWord = core.solverIterationCounts; localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter); localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter); //const Cm::SpatialVector& accel = originalBodyArray[i]->getAccelerationV(); bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq, core.linearVelocity, core.angularVelocity, core.disableGravity!=0); copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i], core.contactReportThreshold, solverBodyDataPool[i + 1], core.lockFlags, dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES); } const PxU32 i = bodyCount - 1; PxsBodyCore& core = *bodyArray[i]; const PxsRigidBody& rBody = *originalBodyArray[i]; PxU16 iterWord = core.solverIterationCounts; localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter); localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter); bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq, core.linearVelocity, core.angularVelocity, core.disableGravity!=0); copyToSolverBodyData(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i], core.contactReportThreshold, solverBodyDataPool[i + 1], core.lockFlags, dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES); physx::PxAtomicMax(reinterpret_cast<volatile PxI32*>(maxSolverPositionIterations), PxI32(localMaxPosIter)); physx::PxAtomicMax(reinterpret_cast<volatile PxI32*>(maxSolverVelocityIterations), PxI32(localMaxVelIter)); } void PxsPreIntegrateTask::runInternal() { PX_PROFILE_ZONE("PreIntegration", mContext.getContextId()); preIntegrationParallel(mDt, mBodyArray + mStartIndex, mOriginalBodyArray + mStartIndex, mNodeIndexArray + mStartIndex, mNumToIntegrate, mSolverBodyDataPool + mStartIndex, mMaxSolverPositionIterations, mMaxSolverVelocityIterations, mGravity); } void DynamicsContext::preIntegrationParallel( PxF32 dt, PxsBodyCore*const* bodyArray, // INOUT: core body attributes PxsRigidBody*const* originalBodyArray, // IN: original bodies (LEGACY - DON'T deref the ptrs!!) PxU32 const* nodeIndexArray, // IN: island node index PxU32 bodyCount, // IN: body count PxSolverBody* solverBodyPool, // IN: solver body pool (space preallocated) PxSolverBodyData* solverBodyDataPool, // IN: solver body data pool (space preallocated) Cm::SpatialVector* /*motionVelocityArray*/, // OUT: motion velocities PxU32& maxSolverPositionIterations, PxU32& maxSolverVelocityIterations, PxBaseTask& task ) { //TODO - make this based on some variables so we can try different configurations const PxU32 IntegrationPerThread = 256; const PxU32 numTasks = ((bodyCount + IntegrationPerThread-1)/IntegrationPerThread); const PxU32 taskBatchSize = 64; for(PxU32 i = 0; i < numTasks; i+=taskBatchSize) { const PxU32 nbTasks = PxMin(numTasks - i, taskBatchSize); PxsPreIntegrateTask* tasks = reinterpret_cast<PxsPreIntegrateTask*>(getTaskPool().allocate(sizeof(PxsPreIntegrateTask)*nbTasks)); for(PxU32 a = 0; a < nbTasks; ++a) { PxU32 startIndex = (i+a)*IntegrationPerThread; PxU32 nbToIntegrate = PxMin((bodyCount-startIndex), IntegrationPerThread); PxsPreIntegrateTask* pTask = PX_PLACEMENT_NEW(&tasks[a], PxsPreIntegrateTask)(*this, bodyArray, originalBodyArray, nodeIndexArray, solverBodyDataPool, dt, bodyCount, &maxSolverPositionIterations, &maxSolverVelocityIterations, startIndex, nbToIntegrate, mGravity); pTask->setContinuation(&task); pTask->removeReference(); } } PxMemZero(solverBodyPool, bodyCount * sizeof(PxSolverBody)); } void solveParallel(SOLVER_PARALLEL_METHOD_ARGS) { Dy::ThreadContext& threadContext = *context.getThreadContext(); threadContext.mZVector.forceSize_Unsafe(0); threadContext.mZVector.reserve(params.mMaxArticulationLinks); threadContext.mZVector.forceSize_Unsafe(params.mMaxArticulationLinks); threadContext.mDeltaV.forceSize_Unsafe(0); threadContext.mDeltaV.reserve(params.mMaxArticulationLinks); threadContext.mDeltaV.forceSize_Unsafe(params.mMaxArticulationLinks); context.solveParallel(params, islandSim, threadContext.mZVector.begin(), threadContext.mDeltaV.begin()); context.putThreadContext(&threadContext); } void DynamicsContext::solveParallel(SolverIslandParams& params, IG::IslandSim& islandSim, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV) { mSolverCore[mFrictionType]->solveVParallelAndWriteBack(params, Z, deltaV); integrateCoreParallel(params, deltaV, islandSim); } void DynamicsContext::integrateCoreParallel(SolverIslandParams& params, Cm::SpatialVectorF* deltaV, IG::IslandSim& islandSim) { const PxI32 unrollCount = 128; PxI32* bodyIntegrationListIndex = &params.bodyIntegrationListIndex; PxI32 index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollCount; const PxI32 numBodies = PxI32(params.bodyListSize); const PxI32 numArtics = PxI32(params.articulationListSize); Cm::SpatialVector* PX_RESTRICT motionVelocityArray = params.motionVelocityArray; PxsBodyCore*const* bodyArray = params.bodyArray; PxsRigidBody** PX_RESTRICT rigidBodies = params.rigidBodies; ArticulationSolverDesc* PX_RESTRICT articulationListStart = params.articulationListStart; PxI32 numIntegrated = 0; PxI32 bodyRemainder = unrollCount; while(index < numArtics) { const PxI32 remainder = PxMin(numArtics - index, unrollCount); bodyRemainder -= remainder; for(PxI32 a = 0; a < remainder; ++a, index++) { const PxI32 i = index; { //PX_PROFILE_ZONE("Articulations.integrate", mContextID); ArticulationPImpl::updateBodies(articulationListStart[i], deltaV, mDt); } ++numIntegrated; } if(bodyRemainder == 0) { index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollCount; bodyRemainder = unrollCount; } } index -= numArtics; const PxI32 unrollPlusArtics = unrollCount + numArtics; PxSolverBody* PX_RESTRICT solverBodies = params.bodyListStart; PxSolverBodyData* PX_RESTRICT solverBodyData = params.bodyDataList + params.solverBodyOffset+1; while(index < numBodies) { const PxI32 remainder = PxMin(numBodies - index, bodyRemainder); bodyRemainder -= remainder; for(PxI32 a = 0; a < remainder; ++a, index++) { const PxI32 prefetch = PxMin(index+4, numBodies - 1); PxPrefetchLine(bodyArray[prefetch]); PxPrefetchLine(bodyArray[prefetch],128); PxPrefetchLine(&solverBodies[index],128); PxPrefetchLine(&motionVelocityArray[index],128); PxPrefetchLine(&bodyArray[index+32]); PxPrefetchLine(&rigidBodies[prefetch]); PxSolverBodyData& data = solverBodyData[index]; PxsRigidBody& rBody = *rigidBodies[index]; PxsBodyCore& core = rBody.getCore(); integrateCore(motionVelocityArray[index].linear, motionVelocityArray[index].angular, solverBodies[index], data, mDt, core.lockFlags); rBody.mLastTransform = core.body2World; core.body2World = data.body2World; core.linearVelocity = data.linearVelocity; core.angularVelocity = data.angularVelocity; const bool hasStaticTouch = islandSim.getIslandStaticTouchCount(PxNodeIndex(data.nodeIndex)) != 0; sleepCheck(rigidBodies[index], mDt, mEnableStabilization, motionVelocityArray[index], hasStaticTouch); ++numIntegrated; } { index = physx::PxAtomicAdd(bodyIntegrationListIndex, unrollCount) - unrollPlusArtics; bodyRemainder = unrollCount; } } PxMemoryBarrier(); physx::PxAtomicAdd(&params.numObjectsIntegrated, numIntegrated); } static PxU32 createFinalizeContacts_Parallel(PxSolverBodyData* solverBodyData, ThreadContext& mThreadContext, DynamicsContext& context, PxU32 startIndex, PxU32 endIndex, PxsContactManagerOutputIterator& outputs) { PX_PROFILE_ZONE("createFinalizeContacts_Parallel", context.getContextId()); const PxFrictionType::Enum frictionType = context.getFrictionType(); const PxReal correlationDist = context.getCorrelationDistance(); const PxReal bounceThreshold = context.getBounceThreshold(); const PxReal frictionOffsetThreshold = context.getFrictionOffsetThreshold(); const PxReal dt = context.getDt(); const PxReal invDt = PxMin(context.getMaxBiasCoefficient(), context.getInvDt()); PxSolverConstraintDesc* contactDescPtr = mThreadContext.orderedContactConstraints; PxConstraintBatchHeader* headers = mThreadContext.contactConstraintBatchHeaders; PxI32 axisConstraintCount = 0; ThreadContext* threadContext = context.getThreadContext(); threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island threadContext->mZVector.forceSize_Unsafe(0); threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks); threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks); //threadContext->mDeltaV.forceSize_Unsafe(0); //threadContext->mDeltaV.reserve(mThreadContext.mMaxArticulationLinks); //threadContext->mDeltaV.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks); Cm::SpatialVectorF* Z = threadContext->mZVector.begin(); const PxTransform idt(PxIdentity); BlockAllocator blockAllocator(mThreadContext.mConstraintBlockManager, threadContext->mConstraintBlockStream, threadContext->mFrictionPatchStreamPair, threadContext->mConstraintSize); const PxReal ccdMaxSeparation = context.getCCDSeparationThreshold(); for(PxU32 a = startIndex; a < endIndex; ++a) { PxConstraintBatchHeader& header = headers[a]; if(contactDescPtr[header.startIndex].constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT) { PxSolverContactDesc blockDescs[4]; PxsContactManagerOutput* cmOutputs[4]; PxsContactManager* cms[4]; for (PxU32 i = 0; i < header.stride; ++i) { PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex + i]; PxSolverContactDesc& blockDesc = blockDescs[i]; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); cms[i] = cm; PxcNpWorkUnit& unit = cm->getWorkUnit(); cmOutputs[i] = &outputs.getContactManager(unit.mNpIndex); PxSolverBodyData& data0 = desc.linkIndexA != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyADataIndex]; PxSolverBodyData& data1 = desc.linkIndexB != PxSolverConstraintDesc::RIGID_BODY ? solverBodyData[0] : solverBodyData[desc.bodyBDataIndex]; blockDesc.data0 = &data0; blockDesc.data1 = &data1; PxU8 flags = unit.rigidCore0->mFlags; if (unit.rigidCore1) flags |= PxU8(unit.rigidCore1->mFlags); blockDesc.bodyFrame0 = unit.rigidCore0->body2World; blockDesc.bodyFrame1 = unit.rigidCore1 ? unit.rigidCore1->body2World : idt; blockDesc.shapeInteraction = cm->getShapeInteraction(); blockDesc.contactForces = cmOutputs[i]->contactForces; blockDesc.desc = &desc; blockDesc.body0 = desc.bodyA; blockDesc.body1 = desc.bodyB; blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD); blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION); blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY; //second body is articulation if (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) { //kinematic link if (desc.linkIndexB == 0xff) { blockDesc.bodyState1 = PxSolverContactDesc::eSTATIC_BODY; } else { blockDesc.bodyState1 = PxSolverContactDesc::eARTICULATION; } } else { blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY : ((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY); } //blockDesc.flags = unit.flags; PxReal dominance0 = unit.dominance0 ? 1.f : 0.f; PxReal dominance1 = unit.dominance1 ? 1.f : 0.f; blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0; blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1; blockDesc.restDistance = unit.restDistance; blockDesc.frictionPtr = unit.frictionDataPtr; blockDesc.frictionCount = unit.frictionPatchCount; blockDesc.maxCCDSeparation = (flags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD) ? ccdMaxSeparation : PX_MAX_F32; blockDesc.offsetSlop = unit.mOffsetSlop; } #if DY_BATCH_CONSTRAINTS SolverConstraintPrepState::Enum state = SolverConstraintPrepState::eUNBATCHABLE; if(header.stride == 4) { //KS - todo - plumb in axisConstraintCount into this method to keep track of the number of axes state = createFinalizeMethods4[frictionType](cmOutputs, *threadContext, blockDescs, invDt, dt, bounceThreshold, frictionOffsetThreshold, correlationDist, blockAllocator); } if(SolverConstraintPrepState::eSUCCESS != state) #endif { for(PxU32 i = 0; i < header.stride; ++i) { PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex+i]; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); PxcNpWorkUnit& n = cm->getWorkUnit(); PxsContactManagerOutput& output = outputs.getContactManager(n.mNpIndex); createFinalizeMethods[frictionType](blockDescs[i], output, *threadContext, invDt, dt, bounceThreshold, frictionOffsetThreshold, correlationDist, blockAllocator, Z); getContactManagerConstraintDesc(output,*cm,desc); } } for (PxU32 i = 0; i < header.stride; ++i) { PxsContactManager* cm = cms[i]; PxcNpWorkUnit& unit = cm->getWorkUnit(); unit.frictionDataPtr = blockDescs[i].frictionPtr; unit.frictionPatchCount = blockDescs[i].frictionCount; axisConstraintCount += blockDescs[i].axisConstraintCount; } } else if(contactDescPtr[header.startIndex].constraintLengthOver16 == DY_SC_TYPE_RB_1D) { SolverConstraintShaderPrepDesc shaderDescs[4]; PxSolverConstraintPrepDesc descs[4]; for (PxU32 i = 0; i < header.stride; ++i) { PxSolverConstraintDesc& desc = contactDescPtr[header.startIndex + i]; const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint); SolverConstraintShaderPrepDesc& shaderPrepDesc = shaderDescs[i]; PxSolverConstraintPrepDesc& prepDesc = descs[i]; const PxConstraintSolverPrep solverPrep = constraint->solverPrep; const void* constantBlock = constraint->constantBlock; const PxU32 constantBlockByteSize = constraint->constantBlockSize; const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : idt); const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : idt); const PxSolverBody* sbody0 = desc.bodyA; const PxSolverBody* sbody1 = desc.bodyB; PxSolverBodyData* sbodyData0 = &solverBodyData[desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? desc.bodyADataIndex : 0]; PxSolverBodyData* sbodyData1 = &solverBodyData[desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? desc.bodyBDataIndex : 0]; shaderPrepDesc.constantBlock = constantBlock; shaderPrepDesc.constantBlockByteSize = constantBlockByteSize; shaderPrepDesc.constraint = constraint; shaderPrepDesc.solverPrep = solverPrep; prepDesc.desc = &desc; prepDesc.bodyFrame0 = pose0; prepDesc.bodyFrame1 = pose1; prepDesc.data0 = sbodyData0; prepDesc.data1 = sbodyData1; prepDesc.body0 = sbody0; prepDesc.body1 = sbody1; prepDesc.linBreakForce = constraint->linBreakForce; prepDesc.angBreakForce = constraint->angBreakForce; prepDesc.writeback = &context.getConstraintWriteBackPool()[constraint->index]; setupConstraintFlags(prepDesc, constraint->flags); prepDesc.minResponseThreshold = constraint->minResponseThreshold; } #if DY_BATCH_CONSTRAINTS && DY_BATCH_1D SolverConstraintPrepState::Enum state = SolverConstraintPrepState::eUNBATCHABLE; if(header.stride == 4) { PxU32 totalRows; state = setupSolverConstraint4 (shaderDescs, descs, dt, invDt, totalRows, blockAllocator); axisConstraintCount += totalRows; } if(state != SolverConstraintPrepState::eSUCCESS) #endif { for(PxU32 i = 0; i < header.stride; ++i) { axisConstraintCount += SetupSolverConstraint(shaderDescs[i], descs[i], blockAllocator, dt, invDt, Z); } } } } #if PX_ENABLE_SIM_STATS threadContext->getSimStats().numAxisSolverConstraints += axisConstraintCount; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif context.putThreadContext(threadContext); return PxU32(axisConstraintCount); //Can't write to mThreadContext as it's shared!!!! } class PxsCreateFinalizeContactsTask : public Cm::Task { PxsCreateFinalizeContactsTask& operator=(const PxsCreateFinalizeContactsTask&); public: PxsCreateFinalizeContactsTask( const PxU32 numConstraints, PxSolverConstraintDesc* descArray, PxSolverBodyData* solverBodyData, ThreadContext& threadContext, DynamicsContext& context, PxU32 startIndex, PxU32 endIndex, PxsContactManagerOutputIterator& outputs) : Cm::Task(context.getContextId()), mNumConstraints(numConstraints), mDescArray(descArray), mSolverBodyData(solverBodyData), mThreadContext(threadContext), mDynamicsContext(context), mOutputs(outputs), mStartIndex(startIndex), mEndIndex(endIndex) {} virtual void runInternal() { createFinalizeContacts_Parallel(mSolverBodyData, mThreadContext, mDynamicsContext, mStartIndex, mEndIndex, mOutputs); } virtual const char* getName() const { return "PxsDynamics.createFinalizeContacts"; } public: const PxU32 mNumConstraints; PxSolverConstraintDesc* mDescArray; PxSolverBodyData* mSolverBodyData; ThreadContext& mThreadContext; DynamicsContext& mDynamicsContext; PxsContactManagerOutputIterator& mOutputs; PxU32 mStartIndex; PxU32 mEndIndex; }; PxU8* BlockAllocator::reserveConstraintData(const PxU32 size) { mTotalConstraintByteSize += size; return mConstraintBlockStream.reserve(size, mConstraintBlockManager); } PxU8* BlockAllocator::reserveFrictionData(const PxU32 size) { return mFrictionPatchStreamPair.reserve<PxU8>(size); } class PxsCreateArticConstraintsTask : public Cm::Task { PxsCreateArticConstraintsTask& operator=(const PxsCreateArticConstraintsTask&); public: static const PxU32 NbArticsPerTask = 32; PxsCreateArticConstraintsTask(Dy::FeatherstoneArticulation** articulations, const PxU32 nbArticulations, PxSolverBodyData* solverBodyData, ThreadContext& threadContext, DynamicsContext& context, PxsContactManagerOutputIterator& outputs) : Cm::Task(context.getContextId()), mArticulations(articulations), mNbArticulations(nbArticulations), mSolverBodyData(solverBodyData), mThreadContext(threadContext), mDynamicsContext(context), mOutputs(outputs) {} virtual void runInternal() { const PxReal correlationDist = mDynamicsContext.getCorrelationDistance(); const PxReal bounceThreshold = mDynamicsContext.getBounceThreshold(); const PxReal frictionOffsetThreshold = mDynamicsContext.getFrictionOffsetThreshold(); const PxReal dt = mDynamicsContext.getDt(); const PxReal invDt = PxMin(mDynamicsContext.getMaxBiasCoefficient(), mDynamicsContext.getInvDt()); const PxReal ccdMaxSeparation = mDynamicsContext.getCCDSeparationThreshold(); ThreadContext* threadContext = mDynamicsContext.getThreadContext(); threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island threadContext->mZVector.forceSize_Unsafe(0); threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks); threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks); for (PxU32 i = 0; i < mNbArticulations; ++i) { mArticulations[i]->prepareStaticConstraints(dt, invDt, mOutputs, *threadContext, correlationDist, bounceThreshold, frictionOffsetThreshold, ccdMaxSeparation, mSolverBodyData, mThreadContext.mConstraintBlockManager, mDynamicsContext.getConstraintWriteBackPool().begin()); } mDynamicsContext.putThreadContext(threadContext); } virtual const char* getName() const { return "PxsDynamics.createFinalizeContacts"; } public: Dy::FeatherstoneArticulation** mArticulations; PxU32 mNbArticulations; PxSolverBodyData* mSolverBodyData; ThreadContext& mThreadContext; DynamicsContext& mDynamicsContext; PxsContactManagerOutputIterator& mOutputs; }; void PxsSolverCreateFinalizeConstraintsTask::runInternal() { PX_PROFILE_ZONE("CreateConstraints", mContext.getContextId()); ThreadContext& mThreadContext = *mIslandContext.mThreadContext; PxU32 descCount = mThreadContext.mNumDifferentBodyConstraints; PxU32 selfConstraintDescCount = mThreadContext.contactDescArraySize - (mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumStaticConstraints); PxArray<PxU32>& accumulatedConstraintsPerPartition = mThreadContext.mConstraintsPerPartition; PxU32 numHeaders = 0; PxU32 currentPartition = 0; PxU32 maxJ = descCount == 0 ? 0 : accumulatedConstraintsPerPartition[0]; const PxU32 maxBatchPartition = 0xFFFFFFFF; const PxU32 maxBatchSize = mEnhancedDeterminism ? 1u : 4u; PxU32 headersPerPartition = 0; for(PxU32 a = 0; a < descCount;) { PxU32 loopMax = PxMin(maxJ - a, maxBatchSize); PxU16 j = 0; if(loopMax > 0) { PxConstraintBatchHeader& header = mThreadContext.contactConstraintBatchHeaders[numHeaders++]; j=1; PxSolverConstraintDesc& desc = mThreadContext.orderedContactConstraints[a]; if(!isArticulationConstraint(desc) && (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT || desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D) && currentPartition < maxBatchPartition) { for(; j < loopMax && desc.constraintLengthOver16 == mThreadContext.orderedContactConstraints[a+j].constraintLengthOver16 && !isArticulationConstraint(mThreadContext.orderedContactConstraints[a+j]); ++j); } header.startIndex = a; header.stride = j; headersPerPartition++; } if(maxJ == (a + j) && maxJ != descCount) { //Go to next partition! accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition; headersPerPartition = 0; currentPartition++; maxJ = accumulatedConstraintsPerPartition[currentPartition]; } a+= j; } if(descCount) accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition; accumulatedConstraintsPerPartition.forceSize_Unsafe(mThreadContext.mMaxPartitions); PxU32 numDifferentBodyBatchHeaders = numHeaders; for(PxU32 a = 0; a < selfConstraintDescCount; ++a) { PxConstraintBatchHeader& header = mThreadContext.contactConstraintBatchHeaders[numHeaders++]; header.startIndex = a + descCount; header.stride = 1; } PxU32 numSelfConstraintBatchHeaders = numHeaders - numDifferentBodyBatchHeaders; mThreadContext.numDifferentBodyBatchHeaders = numDifferentBodyBatchHeaders; mThreadContext.numSelfConstraintBatchHeaders = numSelfConstraintBatchHeaders; mThreadContext.numContactConstraintBatches = numHeaders; { PxSolverConstraintDesc* descBegin = mThreadContext.orderedContactConstraints; const PxU32 numThreads = getTaskManager()->getCpuDispatcher()->getWorkerCount(); //Choose an appropriate number of constraint prep tasks. This must be proportionate to the number of constraints to prep and the number //of worker threads available. const PxU32 TaskBlockSize = 16; const PxU32 TaskBlockLargeSize = 64; const PxU32 BlockAllocationSize = 64; PxU32 numTasks = (numHeaders+TaskBlockLargeSize-1)/TaskBlockLargeSize; if(numTasks) { if(numTasks < numThreads) numTasks = PxMax(1u, (numHeaders+TaskBlockSize-1)/TaskBlockSize); const PxU32 constraintsPerTask = (numHeaders + numTasks-1)/numTasks; for(PxU32 i = 0; i < numTasks; i+=BlockAllocationSize) { PxU32 blockSize = PxMin(numTasks - i, BlockAllocationSize); PxsCreateFinalizeContactsTask* tasks = reinterpret_cast<PxsCreateFinalizeContactsTask*>(mContext.getTaskPool().allocate(sizeof(PxsCreateFinalizeContactsTask)*blockSize)); for(PxU32 a = 0; a < blockSize; ++a) { PxU32 startIndex = (a + i) * constraintsPerTask; PxU32 endIndex = PxMin(startIndex + constraintsPerTask, numHeaders); PxsCreateFinalizeContactsTask* pTask = PX_PLACEMENT_NEW(&tasks[a], PxsCreateFinalizeContactsTask( descCount, descBegin, mContext.mSolverBodyDataPool.begin(), mThreadContext, mContext, startIndex, endIndex, mOutputs)); pTask->setContinuation(mCont); pTask->removeReference(); } } } } const PxU32 articCount = mIslandContext.mCounts.articulations; for (PxU32 i = 0; i < articCount; i += PxsCreateArticConstraintsTask::NbArticsPerTask) { const PxU32 nbToProcess = PxMin(articCount - i, PxsCreateArticConstraintsTask::NbArticsPerTask); PxsCreateArticConstraintsTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PxsCreateArticConstraintsTask)), PxsCreateArticConstraintsTask) (mThreadContext.mArticulationArray + i, nbToProcess, mContext.mSolverBodyDataPool.begin(), mThreadContext, mContext, mOutputs); task->setContinuation(mCont); task->removeReference(); } } } }
117,138
C++
37.994341
294
0.758584
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrepShared.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_CONTACT_PREP_SHARED_H #define DY_CONTACT_PREP_SHARED_H #include "foundation/PxPreprocessor.h" #include "PxSceneDesc.h" #include "foundation/PxVecMath.h" #include "DyContactPrep.h" #include "DyCorrelationBuffer.h" #include "DyArticulationContactPrep.h" #include "PxsContactManager.h" #include "PxsContactManagerState.h" namespace physx { namespace Dy { template<class PxSolverContactDescT> PX_FORCE_INLINE Sc::ShapeInteraction* getInteraction(const PxSolverContactDescT& desc) { return reinterpret_cast<Sc::ShapeInteraction*>(desc.shapeInteraction); } PX_FORCE_INLINE bool pointsAreClose(const PxTransform& body1ToBody0, const PxVec3& localAnchor0, const PxVec3& localAnchor1, const PxVec3& axis, float correlDist) { const PxVec3 body0PatchPoint1 = body1ToBody0.transform(localAnchor1); return PxAbs((localAnchor0 - body0PatchPoint1).dot(axis))<correlDist; } PX_FORCE_INLINE bool isSeparated(const FrictionPatch& patch, const PxTransform& body1ToBody0, const PxReal correlationDistance) { PX_ASSERT(patch.anchorCount <= 2); for(PxU32 a = 0; a < patch.anchorCount; ++a) { if(!pointsAreClose(body1ToBody0, patch.body0Anchors[a], patch.body1Anchors[a], patch.body0Normal, correlationDistance)) return true; } return false; } inline bool getFrictionPatches(CorrelationBuffer& c, const PxU8* frictionCookie, PxU32 frictionPatchCount, const PxTransform& bodyFrame0, const PxTransform& bodyFrame1, PxReal correlationDistance) { if(frictionCookie == NULL || frictionPatchCount == 0) return true; //KS - this is now DMA'd inside the shader so we don't need to immediate DMA it here const FrictionPatch* patches = reinterpret_cast<const FrictionPatch*>(frictionCookie); //Try working out relative transforms! TODO - can we compute this lazily for the first friction patch bool evaluated = false; PxTransform body1ToBody0; while(frictionPatchCount--) { PxPrefetchLine(patches,128); const FrictionPatch& patch = *patches++; PX_ASSERT (patch.broken == 0 || patch.broken == 1); if(!patch.broken) { // if the eDISABLE_STRONG_FRICTION flag is there we need to blow away the previous frame's friction correlation, so // that we can associate each friction anchor with a target velocity. So we lose strong friction. if(patch.anchorCount != 0 && !(patch.materialFlags & PxMaterialFlag::eDISABLE_STRONG_FRICTION)) { PX_ASSERT(patch.anchorCount <= 2); if(!evaluated) { body1ToBody0 = bodyFrame0.transformInv(bodyFrame1); evaluated = true; } if(patch.body0Normal.dot(body1ToBody0.rotate(patch.body1Normal)) > PXC_SAME_NORMAL) { if(!isSeparated(patch, body1ToBody0, correlationDistance)) { if(c.frictionPatchCount == CorrelationBuffer::MAX_FRICTION_PATCHES) return false; { c.contactID[c.frictionPatchCount][0] = 0xffff; c.contactID[c.frictionPatchCount][1] = 0xffff; //Rotate the contact normal into world space c.frictionPatchWorldNormal[c.frictionPatchCount] = bodyFrame0.rotate(patch.body0Normal); c.frictionPatchContactCounts[c.frictionPatchCount] = 0; c.patchBounds[c.frictionPatchCount].setEmpty(); c.correlationListHeads[c.frictionPatchCount] = CorrelationBuffer::LIST_END; PxMemCopy(&c.frictionPatches[c.frictionPatchCount++], &patch, sizeof(FrictionPatch)); } } } } } } return true; } PX_FORCE_INLINE PxU32 extractContacts(PxContactBuffer& buffer, PxsContactManagerOutput& npOutput, bool& hasMaxImpulse, bool& hasTargetVelocity, PxReal& invMassScale0, PxReal& invMassScale1, PxReal& invInertiaScale0, PxReal& invInertiaScale1, PxReal defaultMaxImpulse) { PxContactStreamIterator iter(npOutput.contactPatches, npOutput.contactPoints, npOutput.getInternalFaceIndice(), npOutput.nbPatches, npOutput.nbContacts); PxU32 numContacts = buffer.count, origContactCount = buffer.count; if(!iter.forceNoResponse) { invMassScale0 = iter.getInvMassScale0(); invMassScale1 = iter.getInvMassScale1(); invInertiaScale0 = iter.getInvInertiaScale0(); invInertiaScale1 = iter.getInvInertiaScale1(); hasMaxImpulse = (iter.patch->internalFlags & PxContactPatch::eHAS_MAX_IMPULSE) != 0; hasTargetVelocity = (iter.patch->internalFlags & PxContactPatch::eHAS_TARGET_VELOCITY) != 0; while(iter.hasNextPatch()) { iter.nextPatch(); while(iter.hasNextContact()) { iter.nextContact(); PxPrefetchLine(iter.contact, 128); PxPrefetchLine(&buffer.contacts[numContacts], 128); PxReal maxImpulse = hasMaxImpulse ? iter.getMaxImpulse() : defaultMaxImpulse; if(maxImpulse != 0.f) { PX_ASSERT(numContacts < PxContactBuffer::MAX_CONTACTS); buffer.contacts[numContacts].normal = iter.getContactNormal(); PX_ASSERT(PxAbs(buffer.contacts[numContacts].normal.magnitude() - 1) < 1e-3f); buffer.contacts[numContacts].point = iter.getContactPoint(); buffer.contacts[numContacts].separation = iter.getSeparation(); //KS - we use the face indices to cache the material indices and flags - avoids bloating the PxContact structure buffer.contacts[numContacts].materialFlags = PxU8(iter.getMaterialFlags()); buffer.contacts[numContacts].maxImpulse = maxImpulse; buffer.contacts[numContacts].staticFriction = iter.getStaticFriction(); buffer.contacts[numContacts].dynamicFriction = iter.getDynamicFriction(); buffer.contacts[numContacts].restitution = iter.getRestitution(); buffer.contacts[numContacts].damping = iter.getDamping(); const PxVec3& targetVel = iter.getTargetVel(); buffer.contacts[numContacts].targetVel = targetVel; ++numContacts; } } } } const PxU32 contactCount = numContacts - origContactCount; buffer.count = numContacts; return contactCount; } struct CorrelationListIterator { CorrelationBuffer& buffer; PxU32 currPatch; PxU32 currContact; CorrelationListIterator(CorrelationBuffer& correlationBuffer, PxU32 startPatch) : buffer(correlationBuffer) { //We need to force us to advance the correlation buffer to the first available contact (if one exists) PxU32 newPatch = startPatch, newContact = 0; while(newPatch != CorrelationBuffer::LIST_END && newContact == buffer.contactPatches[newPatch].count) { newPatch = buffer.contactPatches[newPatch].next; newContact = 0; } currPatch = newPatch; currContact = newContact; } //Returns true if it has another contact pre-loaded. Returns false otherwise PX_FORCE_INLINE bool hasNextContact() const { return (currPatch != CorrelationBuffer::LIST_END && currContact < buffer.contactPatches[currPatch].count); } inline void nextContact(PxU32& patch, PxU32& contact) { PX_ASSERT(currPatch != CorrelationBuffer::LIST_END); PX_ASSERT(currContact < buffer.contactPatches[currPatch].count); patch = currPatch; contact = currContact; PxU32 newPatch = currPatch, newContact = currContact + 1; while(newPatch != CorrelationBuffer::LIST_END && newContact == buffer.contactPatches[newPatch].count) { newPatch = buffer.contactPatches[newPatch].next; newContact = 0; } currPatch = newPatch; currContact = newContact; } private: CorrelationListIterator& operator=(const CorrelationListIterator&); }; PX_FORCE_INLINE void constructContactConstraint(const Mat33V& invSqrtInertia0, const Mat33V& invSqrtInertia1, const FloatVArg invMassNorLenSq0, const FloatVArg invMassNorLenSq1, const FloatVArg angD0, const FloatVArg angD1, const Vec3VArg bodyFrame0p, const Vec3VArg bodyFrame1p, const Vec3VArg normal, const FloatVArg norVel, const VecCrossV& norCross, const Vec3VArg angVel0, const Vec3VArg angVel1, const FloatVArg invDt, const FloatVArg invDtp8, const FloatVArg dt, const FloatVArg restDistance, const FloatVArg maxPenBias, const FloatVArg restitution, const FloatVArg bounceThreshold, const PxContactPoint& contact, SolverContactPoint& solverContact, const FloatVArg ccdMaxSeparation, const Vec3VArg solverOffsetSlop, const FloatVArg damping) { const FloatV zero = FZero(); const Vec3V point = V3LoadA(contact.point); const FloatV separation = FLoad(contact.separation); const FloatV cTargetVel = V3Dot(normal, V3LoadA(contact.targetVel)); const Vec3V ra = V3Sub(point, bodyFrame0p); const Vec3V rb = V3Sub(point, bodyFrame1p); /*ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), V3Zero(), ra); rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), V3Zero(), rb);*/ Vec3V raXn = V3Cross(ra, norCross); Vec3V rbXn = V3Cross(rb, norCross); FloatV vRelAng = FSub(V3Dot(raXn, angVel0), V3Dot(rbXn, angVel1)); const Vec3V slop = V3Scale(solverOffsetSlop, FMax(FSel(FIsEq(norVel, zero), FMax(), FDiv(vRelAng, norVel)), FOne())); raXn = V3Sel(V3IsGrtr(slop, V3Abs(raXn)), V3Zero(), raXn); rbXn = V3Sel(V3IsGrtr(slop, V3Abs(rbXn)), V3Zero(), rbXn); vRelAng = FSub(V3Dot(raXn, angVel0), V3Dot(rbXn, angVel1)); const FloatV vrel = FAdd(norVel, vRelAng); const Vec3V raXnSqrtInertia = M33MulV3(invSqrtInertia0, raXn); const Vec3V rbXnSqrtInertia = M33MulV3(invSqrtInertia1, rbXn); const FloatV resp0 = FAdd(invMassNorLenSq0, FMul(V3Dot(raXnSqrtInertia, raXnSqrtInertia), angD0)); const FloatV resp1 = FSub(FMul(V3Dot(rbXnSqrtInertia, rbXnSqrtInertia), angD1), invMassNorLenSq1); const FloatV unitResponse = FAdd(resp0, resp1); const FloatV penetration = FSub(separation, restDistance); const FloatV penetrationInvDt = FMul(penetration, invDt); const FloatV sumVRel(vrel); const BoolV isGreater2 = BAnd(BAnd(FIsGrtr(restitution, zero), FIsGrtr(bounceThreshold, vrel)), FIsGrtr(FNeg(vrel), penetrationInvDt)); FloatV targetVelocity = FAdd(cTargetVel, FSel(isGreater2, FMul(FNeg(sumVRel), restitution), zero)); //Note - we add on the initial target velocity targetVelocity = FSub(targetVelocity, vrel); FloatV biasedErr, unbiasedErr; FloatV velMultiplier, impulseMultiplier; if (FAllGrtr(zero, restitution)) { 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 { velMultiplier = FSel(FIsGrtr(unitResponse, zero), FRecip(unitResponse), zero); const FloatV penetrationInvDtPt8 = FMax(maxPenBias, FMul(penetration, invDtp8)); FloatV scaledBias = FMul(velMultiplier, penetrationInvDtPt8); const BoolV ccdSeparationCondition = FIsGrtrOrEq(ccdMaxSeparation, penetration); scaledBias = FSel(BAnd(ccdSeparationCondition, isGreater2), zero, scaledBias); impulseMultiplier = FLoad(1.0f); biasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(scaledBias)); unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FSel(isGreater2, zero, FNeg(FMax(scaledBias, zero)))); } //const FloatV unbiasedErr = FScaleAdd(targetVelocity, velMultiplier, FNeg(FMax(scaledBias, zero))); FStore(biasedErr, &solverContact.biasedErr); FStore(unbiasedErr, &solverContact.unbiasedErr); FStore(impulseMultiplier, &solverContact.impulseMultiplier); solverContact.raXn_velMultiplierW = V4SetW(Vec4V_From_Vec3V(raXnSqrtInertia), velMultiplier); solverContact.rbXn_maxImpulseW = V4SetW(Vec4V_From_Vec3V(rbXnSqrtInertia), FLoad(contact.maxImpulse)); } } } #endif
13,346
C
38.841791
156
0.749438
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPrep.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_CONSTRAINT_PREP_H #define DY_CONSTRAINT_PREP_H #include "DyConstraint.h" #include "DySolverConstraintDesc.h" #include "foundation/PxArray.h" #include "PxConstraint.h" namespace physx { class PxcConstraintBlockStream; class PxsConstraintBlockManager; struct PxSolverBody; struct PxSolverBodyData; struct PxSolverConstraintDesc; namespace Cm { struct SpatialVectorF; } namespace Dy { static const PxU32 MAX_CONSTRAINT_ROWS = 20; struct SolverConstraintShaderPrepDesc { const Constraint* constraint; PxConstraintSolverPrep solverPrep; const void* constantBlock; PxU32 constantBlockByteSize; }; SolverConstraintPrepState::Enum setupSolverConstraint4 (SolverConstraintShaderPrepDesc* PX_RESTRICT constraintShaderDescs, PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs, const PxReal dt, const PxReal recipdt, PxU32& totalRows, PxConstraintAllocator& allocator); SolverConstraintPrepState::Enum setupSolverConstraint4 (PxSolverConstraintPrepDesc* PX_RESTRICT constraintDescs, const PxReal dt, const PxReal recipdt, PxU32& totalRows, PxConstraintAllocator& allocator, PxU32 maxRows); PxU32 SetupSolverConstraint(SolverConstraintShaderPrepDesc& shaderDesc, PxSolverConstraintPrepDesc& prepDesc, PxConstraintAllocator& allocator, PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z); class ConstraintHelper { public: static PxU32 setupSolverConstraint( PxSolverConstraintPrepDesc& prepDesc, PxConstraintAllocator& allocator, PxReal dt, PxReal invdt, Cm::SpatialVectorF* Z); }; template<class PrepDescT> PX_FORCE_INLINE void setupConstraintFlags(PrepDescT& prepDesc, PxU16 flags) { prepDesc.disablePreprocessing = (flags & PxConstraintFlag::eDISABLE_PREPROCESSING)!=0; prepDesc.improvedSlerp = (flags & PxConstraintFlag::eIMPROVED_SLERP)!=0; prepDesc.driveLimitsAreForces = (flags & PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES)!=0; prepDesc.extendedLimits = (flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS)!=0; prepDesc.disableConstraint = (flags & PxConstraintFlag::eDISABLE_CONSTRAINT)!=0; } 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); PX_FORCE_INLINE void setupConstraintRows(Px1DConstraint* PX_RESTRICT rows, PxU32 size) { // This is necessary so that there will be sensible defaults and shaders will // continue to work (albeit with a recompile) if the row format changes. // It's a bit inefficient because it fills in all constraint rows even if there // is only going to be one generated. A way around this would be for the shader to // specify the maximum number of rows it needs, or it could call a subroutine to // prep the row before it starts filling it it. PxMemZero(rows, sizeof(Px1DConstraint)*size); for(PxU32 i=0; i<size; i++) { Px1DConstraint& c = rows[i]; //Px1DConstraintInit(c); c.minImpulse = -PX_MAX_REAL; c.maxImpulse = PX_MAX_REAL; } } } } #endif
4,949
C
34.611511
90
0.769246
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverPFConstraints.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DySolverBody.h" #include "DySolverContact.h" #include "DySolverContactPF.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 "DyThresholdTable.h" #include "DySolverConstraintsShared.h" #include "DyFeatherstoneArticulation.h" #include "DyPGS.h" namespace physx { namespace Dy { static void solveContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxSolverBody& b0 = *desc.bodyA; PxSolverBody& b1 = *desc.bodyB; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); Vec3V angState1 = V3LoadA(b1.angularState); SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint); const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc); //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; //const FloatV zero = FZero(); while(currPtr < last) { SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr); currPtr += sizeof(SolverContactCoulombHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; const Vec3V normal = hdr->getNormal(); const FloatV invMassDom0 = FLoad(hdr->dominance0); const FloatV invMassDom1 = FLoad(hdr->dominance1); const FloatV angD0 = FLoad(hdr->angDom0); const FloatV angD1 = FLoad(hdr->angDom1); SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr); currPtr += numNormalConstr * sizeof(SolverContactPoint); PxF32* appliedImpulse = reinterpret_cast<PxF32*> ((reinterpret_cast<PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader)); PxPrefetchLine(appliedImpulse); solveDynamicContacts(contacts, numNormalConstr, normal, invMassDom0, invMassDom1, angD0, angD1, linVel0, angState0, linVel1, angState1, appliedImpulse); } // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(linVel1, b1.linearVelocity); V3StoreA(angState0, b0.angularState); V3StoreA(angState1, b1.angularState); PX_ASSERT(currPtr == last); } static void solveFriction(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxSolverBody& b0 = *desc.bodyA; PxSolverBody& b1 = *desc.bodyB; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V linVel1 = V3LoadA(b1.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); Vec3V angState1 = V3LoadA(b1.angularState); PxU8* PX_RESTRICT ptr = desc.constraint; PxU8* PX_RESTRICT currPtr = ptr; const PxU8* PX_RESTRICT last = ptr + getConstraintLength(desc); while(currPtr < last) { const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr); currPtr += sizeof(SolverFrictionHeader); PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr); currPtr += frictionHeader->getAppliedForcePaddingSize(); SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr); const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr; const PxU32 numNormalConstr = frictionHeader->numNormalConstr; const PxU32 numFrictionPerPoint = numFrictionConstr/numNormalConstr; currPtr += numFrictionConstr * sizeof(SolverContactFriction); const FloatV staticFriction = frictionHeader->getStaticFriction(); const FloatV invMass0D0 = FLoad(frictionHeader->invMass0D0); const FloatV invMass1D1 = FLoad(frictionHeader->invMass1D1); const FloatV angD0 = FLoad(frictionHeader->angDom0); const FloatV angD1 = FLoad(frictionHeader->angDom1); for(PxU32 i=0, j = 0;i<numFrictionConstr;j++) { for(PxU32 p = 0; p < numFrictionPerPoint; p++, i++) { SolverContactFriction& f = frictions[i]; PxPrefetchLine(&frictions[i], 128); const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW); const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW); const Vec3V rbXt0 = Vec3V_From_Vec4V(f.rbXnXYZ_biasW); const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW); const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); const FloatV normalImpulse = FLoad(appliedImpulse[j]); const FloatV maxFriction = FMul(staticFriction, normalImpulse); const FloatV nMaxFriction = FNeg(maxFriction); //Compute the normal velocity of the constraint. const FloatV t0Vel1 = V3Dot(t0, linVel0); const FloatV t0Vel2 = V3Dot(raXt0, angState0); const FloatV t0Vel3 = V3Dot(t0, linVel1); const FloatV t0Vel4 = V3Dot(rbXt0, angState1); const FloatV t0Vel = FSub(FAdd(t0Vel1, t0Vel2), FAdd(t0Vel3, t0Vel4)); const Vec3V delLinVel0 = V3Scale(t0, invMass0D0); const Vec3V delLinVel1 = V3Scale(t0, invMass1D1); // 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 tmp = FNegScaleSub(targetVel,velMultiplier,appliedForce); FloatV newForce = FScaleAdd(t0Vel, velMultiplier, tmp); newForce = FClamp(newForce, nMaxFriction, maxFriction); FloatV deltaF = FSub(newForce, appliedForce); linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0); linVel1 = V3NegScaleSub(delLinVel1, deltaF, linVel1); angState0 = V3ScaleAdd(raXt0, FMul(deltaF, angD0), angState0); angState1 = V3NegScaleSub(rbXt0, FMul(deltaF, angD1), angState1); f.setAppliedForce(newForce); } } } // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(linVel1, b1.linearVelocity); V3StoreA(angState0, b0.angularState); V3StoreA(angState1, b1.angularState); PX_ASSERT(currPtr == last); } static void solveContactCoulomb_BStatic(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxSolverBody& b0 = *desc.bodyA; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); SolverContactCoulombHeader* firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint); const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc); //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; //const FloatV zero = FZero(); while(currPtr < last) { SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr); currPtr += sizeof(SolverContactCoulombHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; SolverContactPoint* PX_RESTRICT contacts = reinterpret_cast<SolverContactPoint*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPoint); PxF32* appliedImpulse = reinterpret_cast<PxF32*> ((reinterpret_cast<PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader)); PxPrefetchLine(appliedImpulse); const Vec3V normal = hdr->getNormal(); const FloatV invMassDom0 = FLoad(hdr->dominance0); const FloatV angD0 = FLoad(hdr->angDom0); solveStaticContacts(contacts, numNormalConstr, normal, invMassDom0, angD0, linVel0, angState0, appliedImpulse); } // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(angState0, b0.angularState); PX_ASSERT(currPtr == last); } static void solveFriction_BStatic(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxSolverBody& b0 = *desc.bodyA; Vec3V linVel0 = V3LoadA(b0.linearVelocity); Vec3V angState0 = V3LoadA(b0.angularState); PxU8* PX_RESTRICT currPtr = desc.constraint; const PxU8* PX_RESTRICT last = currPtr + getConstraintLength(desc); while(currPtr < last) { const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr); const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr; const PxU32 numNormalConstr = frictionHeader->numNormalConstr; const PxU32 numFrictionPerPoint = numFrictionConstr/numNormalConstr; currPtr +=sizeof(SolverFrictionHeader); PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr); currPtr +=frictionHeader->getAppliedForcePaddingSize(); SolverContactFriction* PX_RESTRICT frictions = reinterpret_cast<SolverContactFriction*>(currPtr); currPtr += numFrictionConstr * sizeof(SolverContactFriction); const FloatV invMass0 = FLoad(frictionHeader->invMass0D0); const FloatV angD0 = FLoad(frictionHeader->angDom0); //const FloatV angD1 = FLoad(frictionHeader->angDom1); const FloatV staticFriction = frictionHeader->getStaticFriction(); for(PxU32 i=0, j = 0;i<numFrictionConstr;j++) { for(PxU32 p = 0; p < numFrictionPerPoint; p++, i++) { SolverContactFriction& f = frictions[i]; PxPrefetchLine(&frictions[i+1]); const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW); const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW); const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW); const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); //const FloatV normalImpulse = contacts[f.contactIndex].getAppliedForce(); const FloatV normalImpulse = FLoad(appliedImpulse[j]); const FloatV maxFriction = FMul(staticFriction, normalImpulse); const FloatV nMaxFriction = FNeg(maxFriction); //Compute the normal velocity of the constraint. const FloatV t0Vel1 = V3Dot(t0, linVel0); const FloatV t0Vel2 = V3Dot(raXt0, angState0); const FloatV t0Vel = FAdd(t0Vel1, t0Vel2); const Vec3V delangState0 = V3Scale(raXt0, angD0); const Vec3V delLinVel0 = V3Scale(t0, invMass0); // 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 tmp = FNegScaleSub(targetVel,velMultiplier,appliedForce); FloatV newForce = FScaleAdd(t0Vel, velMultiplier, tmp); newForce = FClamp(newForce, nMaxFriction, maxFriction); const FloatV deltaF = FSub(newForce, appliedForce); linVel0 = V3ScaleAdd(delLinVel0, deltaF, linVel0); angState0 = V3ScaleAdd(delangState0, deltaF, angState0); f.setAppliedForce(newForce); } } } // Write back V3StoreA(linVel0, b0.linearVelocity); V3StoreA(angState0, b0.angularState); PX_ASSERT(currPtr == last); } static void concludeContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/) { PxU8* PX_RESTRICT cPtr = desc.constraint; const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr); PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset;//getConstraintLength(desc); while(cPtr < last) { const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr); cPtr += sizeof(SolverContactCoulombHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; //if(cPtr < last) //PxPrefetchLine(cPtr, 512); PxPrefetchLine(cPtr,128); PxPrefetchLine(cPtr,256); PxPrefetchLine(cPtr,384); const PxU32 pointStride = hdr->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt) : sizeof(SolverContactPoint); for(PxU32 i=0;i<numNormalConstr;i++) { SolverContactPoint *c = reinterpret_cast<SolverContactPoint*>(cPtr); cPtr += pointStride; //c->scaledBias = PxMin(c->scaledBias, 0.f); c->biasedErr = c->unbiasedErr; } } PX_ASSERT(cPtr == last); } static void writeBackContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache, PxSolverBodyData& bd0, PxSolverBodyData& bd1) { PxReal normalForce = 0.f; PxU8* PX_RESTRICT cPtr = desc.constraint; PxReal* PX_RESTRICT vForceWriteback = reinterpret_cast<PxReal*>(desc.writeBack); const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr); PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset; const PxU32 pointStride = firstHeader->type == DY_SC_TYPE_EXT_CONTACT ? sizeof(SolverContactPointExt) : sizeof(SolverContactPoint); bool hasForceThresholds = false; while(cPtr < last) { const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<const SolverContactCoulombHeader*>(cPtr); cPtr += sizeof(SolverContactCoulombHeader); PxF32* appliedImpulse = reinterpret_cast<PxF32*> (const_cast<PxU8*>((reinterpret_cast<const PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader))); hasForceThresholds = hdr->flags & SolverContactHeader::eHAS_FORCE_THRESHOLDS; const PxU32 numNormalConstr = hdr->numNormalConstr; PxPrefetchLine(cPtr, 256); PxPrefetchLine(cPtr, 384); if(vForceWriteback!=NULL) { for(PxU32 i=0; i<numNormalConstr; i++) { PxF32 imp = appliedImpulse[i]; *vForceWriteback = imp; vForceWriteback++; normalForce += imp; } } cPtr += numNormalConstr * pointStride; } PX_ASSERT(cPtr == last); if(hasForceThresholds && desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY && desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY && normalForce !=0 && (bd0.reportThreshold < PX_MAX_REAL || bd1.reportThreshold < PX_MAX_REAL)) { ThresholdStreamElement elt; elt.normalForce = normalForce; elt.threshold = PxMin<float>(bd0.reportThreshold, bd1.reportThreshold); elt.nodeIndexA = PxNodeIndex(bd0.nodeIndex); elt.nodeIndexB = PxNodeIndex(bd1.nodeIndex); elt.shapeInteraction = (reinterpret_cast<SolverContactCoulombHeader*>(desc.constraint))->shapeInteraction; PxOrder(elt.nodeIndexA, elt.nodeIndexB); PX_ASSERT(elt.nodeIndexA < elt.nodeIndexB); PX_ASSERT(cache.mThresholdStreamIndex<cache.mThresholdStreamLength); cache.mThresholdStream[cache.mThresholdStreamIndex++] = elt; } } void solveFrictionBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveFriction(desc[a], cache); } void solveFrictionBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveFriction(desc[a], cache); } void solveFriction_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveFriction_BStatic(desc[a], cache); } /*void solveFriction_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveFriction_BStatic(desc[a], cache); }*/ void solveFriction_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveFriction_BStatic(desc[a], cache); } void solveContactCoulombBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveContactCoulomb(desc[a], cache); } void solveContactCoulombConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { solveContactCoulomb(desc[a], cache); concludeContactCoulomb(desc[a], cache); } } void solveContactCoulombBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].bodyBDataIndex]; solveContactCoulomb(desc[a], cache); writeBackContactCoulomb(desc[a], 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 solveContactCoulomb_BStaticBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveContactCoulomb_BStatic(desc[a], cache); } void solveContactCoulomb_BStaticConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { solveContactCoulomb_BStatic(desc[a], cache); concludeContactCoulomb(desc[a], cache); } } void solveContactCoulomb_BStaticBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].bodyADataIndex]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].bodyBDataIndex]; solveContactCoulomb_BStatic(desc[a], cache); writeBackContactCoulomb(desc[a], cache, bd0, bd1); } if(cache.mThresholdStreamIndex > (cache.mThresholdStreamLength - 4)) { //Not enough space to write 4 more thresholds back! //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; } } static void solveExtContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache) { //We'll need this. // const FloatV zero = FZero(); // const FloatV one = FOne(); Vec3V linVel0, angVel0, linVel1, angVel1; if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.bodyA->linearVelocity); angVel0 = V3LoadA(desc.bodyA->angularState); } else { //articulation Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.bodyB->linearVelocity); angVel1 = V3LoadA(desc.bodyB->angularState); } else if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { //soft body, need to implement linVel1 = V3Zero(); angVel1 = V3Zero(); } else { //articulation Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; } //const PxU8* PX_RESTRICT last = desc.constraint + desc.constraintLengthOver16*16; PxU8* PX_RESTRICT currPtr = desc.constraint; const SolverContactCoulombHeader* PX_RESTRICT firstHeader = reinterpret_cast<SolverContactCoulombHeader*>(currPtr); const PxU8* PX_RESTRICT last = desc.constraint + firstHeader->frictionOffset; //hopefully pointer aliasing doesn't bite. Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero(); while (currPtr < last) { const SolverContactCoulombHeader* PX_RESTRICT hdr = reinterpret_cast<SolverContactCoulombHeader*>(currPtr); currPtr += sizeof(SolverContactCoulombHeader); const PxU32 numNormalConstr = hdr->numNormalConstr; PxF32* appliedImpulse = reinterpret_cast<PxF32*>(const_cast<PxU8*>(((reinterpret_cast<const PxU8*>(hdr)) + hdr->frictionOffset + sizeof(SolverFrictionHeader)))); PxPrefetchLine(appliedImpulse); SolverContactPointExt* PX_RESTRICT contacts = reinterpret_cast<SolverContactPointExt*>(currPtr); PxPrefetchLine(contacts); currPtr += numNormalConstr * sizeof(SolverContactPointExt); Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); const Vec3V normal = hdr->getNormal(); solveExtContacts(contacts, numNormalConstr, normal, linVel0, angVel0, linVel1, angVel1, li0, ai0, li1, ai1, appliedImpulse); linImpulse0 = V3ScaleAdd(li0, FLoad(hdr->dominance0), linImpulse0); angImpulse0 = V3ScaleAdd(ai0, FLoad(hdr->angDom0), angImpulse0); linImpulse1 = V3NegScaleSub(li1, FLoad(hdr->dominance1), linImpulse1); angImpulse1 = V3NegScaleSub(ai1, FLoad(hdr->angDom1), angImpulse1); } if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.bodyA->linearVelocity); V3StoreA(angVel0, desc.bodyA->angularState); } else { getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV); } if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.bodyB->linearVelocity); V3StoreA(angVel1, desc.bodyB->angularState); } else { getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } PX_ASSERT(currPtr == last); } void solveExtFriction(const PxSolverConstraintDesc& desc, SolverContext& cache) { Vec3V linVel0, angVel0, linVel1, angVel1; if(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { linVel0 = V3LoadA(desc.bodyA->linearVelocity); angVel0 = V3LoadA(desc.bodyA->angularState); } else { Cm::SpatialVectorV v = getArticulationA(desc)->pxcFsGetVelocity(desc.linkIndexA); linVel0 = v.linear; angVel0 = v.angular; } if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { linVel1 = V3LoadA(desc.bodyB->linearVelocity); angVel1 = V3LoadA(desc.bodyB->angularState); } else { Cm::SpatialVectorV v = getArticulationB(desc)->pxcFsGetVelocity(desc.linkIndexB); linVel1 = v.linear; angVel1 = v.angular; } //hopefully pointer aliasing doesn't bite. PxU8* PX_RESTRICT currPtr = desc.constraint; const PxU8* PX_RESTRICT last = currPtr + desc.constraintLengthOver16*16; Vec3V linImpulse0 = V3Zero(), linImpulse1 = V3Zero(), angImpulse0 = V3Zero(), angImpulse1 = V3Zero(); while(currPtr < last) { const SolverFrictionHeader* PX_RESTRICT frictionHeader = reinterpret_cast<SolverFrictionHeader*>(currPtr); currPtr += sizeof(SolverFrictionHeader); PxF32* appliedImpulse = reinterpret_cast<PxF32*>(currPtr); currPtr += frictionHeader->getAppliedForcePaddingSize(); SolverContactFrictionExt* PX_RESTRICT frictions = reinterpret_cast<SolverContactFrictionExt*>(currPtr); const PxU32 numFrictionConstr = frictionHeader->numFrictionConstr; currPtr += numFrictionConstr * sizeof(SolverContactFrictionExt); const FloatV staticFriction = frictionHeader->getStaticFriction(); Vec3V li0 = V3Zero(), li1 = V3Zero(), ai0 = V3Zero(), ai1 = V3Zero(); PxU32 numNormalConstr = frictionHeader->numNormalConstr; PxU32 nbFrictionsPerPoint = numFrictionConstr/numNormalConstr; for(PxU32 i = 0, j = 0; i < numFrictionConstr; j++) { for(PxU32 p=0;p<nbFrictionsPerPoint;p++, i++) { SolverContactFrictionExt& f = frictions[i]; PxPrefetchLine(&frictions[i+1]); const Vec3V t0 = Vec3V_From_Vec4V(f.normalXYZ_appliedForceW); const Vec3V raXt0 = Vec3V_From_Vec4V(f.raXnXYZ_velMultiplierW); const Vec3V rbXt0 = Vec3V_From_Vec4V(f.rbXnXYZ_biasW); const FloatV appliedForce = V4GetW(f.normalXYZ_appliedForceW); const FloatV velMultiplier = V4GetW(f.raXnXYZ_velMultiplierW); const FloatV targetVel = FLoad(f.targetVel); const FloatV normalImpulse = FLoad(appliedImpulse[j]);//contacts[f.contactIndex].getAppliedForce(); const FloatV maxFriction = FMul(staticFriction, normalImpulse); const FloatV nMaxFriction = FNeg(maxFriction); //Compute the normal velocity of the constraint. Vec3V rVel = V3MulAdd(linVel0, t0, V3Mul(angVel0, raXt0)); rVel = V3Sub(rVel, V3MulAdd(linVel1, t0, V3Mul(angVel1, rbXt0))); const FloatV t0Vel = FAdd(V3SumElems(rVel), targetVel); FloatV deltaF = FNeg(FMul(t0Vel, velMultiplier)); FloatV newForce = FAdd(appliedForce, deltaF); newForce = FClamp(newForce, nMaxFriction, maxFriction); deltaF = FSub(newForce, appliedForce); linVel0 = V3ScaleAdd(f.linDeltaVA, deltaF, linVel0); angVel0 = V3ScaleAdd(f.angDeltaVA, deltaF, angVel0); linVel1 = V3ScaleAdd(f.linDeltaVB, deltaF, linVel1); angVel1 = V3ScaleAdd(f.angDeltaVB, deltaF, angVel1); li0 = V3ScaleAdd(t0, deltaF, li0); ai0 = V3ScaleAdd(raXt0, deltaF, ai0); li1 = V3ScaleAdd(t0, deltaF, li1); ai1 = V3ScaleAdd(rbXt0, deltaF, ai1); f.setAppliedForce(newForce); } } linImpulse0 = V3ScaleAdd(li0, FLoad(frictionHeader->invMass0D0), linImpulse0); angImpulse0 = V3ScaleAdd(ai0, FLoad(frictionHeader->angDom0), angImpulse0); linImpulse1 = V3NegScaleSub(li1, FLoad(frictionHeader->invMass1D1), linImpulse1); angImpulse1 = V3NegScaleSub(ai1, FLoad(frictionHeader->angDom1), angImpulse1); } if(desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel0, desc.bodyA->linearVelocity); V3StoreA(angVel0, desc.bodyA->angularState); } else { getArticulationA(desc)->pxcFsApplyImpulse(desc.linkIndexA, linImpulse0, angImpulse0, cache.Z, cache.deltaV); } if(desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) { V3StoreA(linVel1, desc.bodyB->linearVelocity); V3StoreA(angVel1, desc.bodyB->angularState); } else { getArticulationB(desc)->pxcFsApplyImpulse(desc.linkIndexB, linImpulse1, angImpulse1, cache.Z, cache.deltaV); } PX_ASSERT(currPtr == last); } void solveExtFrictionBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveExtFriction(desc[a], cache); } /*void solveExtFrictionConcludeBlock(const PxSolverConstraintDesc* PX_RESTRICT desc, const PxU32 constraintCount, SolverContext& cache) { for(PxU32 a = 0; a < constraintCount; ++a) { solveExtFriction(desc[a], cache); } }*/ void solveExtFrictionBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveExtFriction(desc[a], cache); } /*void solveConcludeExtContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveExtContactCoulomb(desc, cache); concludeContactCoulomb(desc, cache); }*/ void solveExtContactCoulombBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) solveExtContactCoulomb(desc[a], cache); } void solveExtContactCoulombConcludeBlock(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { solveExtContactCoulomb(desc[a], cache); concludeContactCoulomb(desc[a], cache); } } void solveExtContactCoulombBlockWriteBack(DY_PGS_SOLVE_METHOD_PARAMS) { for(PxU32 a = 0; a < constraintCount; ++a) { //PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA != PxSolverConstraintDesc::NO_LINK ? 0 : desc[a].bodyADataIndex]; //PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB != PxSolverConstraintDesc::NO_LINK ? 0 : desc[a].bodyBDataIndex]; PxSolverBodyData& bd0 = cache.solverBodyArray[desc[a].linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? desc[a].bodyADataIndex : 0]; PxSolverBodyData& bd1 = cache.solverBodyArray[desc[a].linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? desc[a].bodyBDataIndex : 0]; solveExtContactCoulomb(desc[a], cache); writeBackContactCoulomb(desc[a], cache, bd0, bd1); } if(cache.mThresholdStreamIndex > 0) { //Not enough space to write 4 more thresholds back! //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 solveConcludeContactCoulomb(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveContactCoulomb(desc, cache); concludeContactCoulomb(desc, cache); } void solveConcludeContactCoulomb_BStatic(const PxSolverConstraintDesc& desc, SolverContext& cache) { solveContactCoulomb_BStatic(desc, cache); concludeContactCoulomb(desc, cache); }*/ } }
29,185
C++
34.12154
163
0.748261
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContact4.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_CONTACT4_H #define DY_SOLVER_CONTACT4_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "foundation/PxVecMath.h" #include "DySolverContact.h" namespace physx { namespace Sc { class ShapeInteraction; } namespace Dy { /** \brief Batched SOA contact data. Note, we don't support batching with extended contacts for the simple reason that handling multiple articulations would be complex. */ struct SolverContactHeader4 { enum { eHAS_MAX_IMPULSE = 1 << 0, eHAS_TARGET_VELOCITY = 1 << 1 }; PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU8 numFrictionConstr; PxU8 flag; PxU8 flags[4]; //These counts are the max of the 4 sets of data. //When certain pairs have fewer patches/contacts than others, they are padded with 0s so that no work is performed but //calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD) //KS - used for write-back only PxU8 numNormalConstr0, numNormalConstr1, numNormalConstr2, numNormalConstr3; PxU8 numFrictionConstr0, numFrictionConstr1, numFrictionConstr2, numFrictionConstr3; Vec4V restitution; Vec4V staticFriction; Vec4V dynamicFriction; //Technically, these mass properties could be pulled out into a new structure and shared. For multi-manifold contacts, //this would save 64 bytes per-manifold after the cost of the first manifold Vec4V invMass0D0; Vec4V invMass1D1; Vec4V angDom0; Vec4V angDom1; //Normal is shared between all contacts in the batch. This will save some memory! Vec4V normalX; Vec4V normalY; Vec4V normalZ; Sc::ShapeInteraction* shapeInteraction[4]; //192 or 208 }; #if !PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader4) == 192); #else PX_COMPILE_TIME_ASSERT(sizeof(SolverContactHeader4) == 208); #endif /** \brief This represents a batch of 4 contacts with static rolled into a single structure */ struct SolverContactBatchPointBase4 { Vec4V raXnX; Vec4V raXnY; Vec4V raXnZ; Vec4V velMultiplier; Vec4V scaledBias; Vec4V biasedErr; Vec4V impulseMultiplier; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContactBatchPointBase4) == 112); /** \brief Contains the additional data required to represent 4 contacts between 2 dynamic bodies @see SolverContactBatchPointBase4 */ struct SolverContactBatchPointDynamic4 : public SolverContactBatchPointBase4 { Vec4V rbXnX; Vec4V rbXnY; Vec4V rbXnZ; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContactBatchPointDynamic4) == 160); /** \brief This represents the shared information of a batch of 4 friction constraints */ struct SolverFrictionSharedData4 { BoolV broken; PxU8* frictionBrokenWritebackByte[4]; Vec4V normalX[2]; Vec4V normalY[2]; Vec4V normalZ[2]; }; #if !PX_P64_FAMILY PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionSharedData4) == 128); #endif /** \brief This represents a batch of 4 friction constraints with static rolled into a single structure */ struct SolverContactFrictionBase4 { Vec4V raXnX; Vec4V raXnY; Vec4V raXnZ; Vec4V scaledBias; Vec4V velMultiplier; Vec4V targetVelocity; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFrictionBase4) == 96); /** \brief Contains the additional data required to represent 4 friction constraints between 2 dynamic bodies @see SolverContactFrictionBase4 */ struct SolverContactFrictionDynamic4 : public SolverContactFrictionBase4 { Vec4V rbXnX; Vec4V rbXnY; Vec4V rbXnZ; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContactFrictionDynamic4) == 144); } } #endif
5,310
C
30.058479
164
0.769115
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationPImpl.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_INTERFACE_H #define DY_ARTICULATION_INTERFACE_H #include "DyArticulationUtils.h" #include "DyFeatherstoneArticulation.h" namespace physx { namespace Dy { struct ArticulationSolverDesc; class ArticulationPImpl { public: static PxU32 computeUnconstrainedVelocities(const ArticulationSolverDesc& desc, PxReal dt, PxU32& acCount, const PxVec3& gravity, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* deltaV, const PxReal invLengthScale) { return FeatherstoneArticulation::computeUnconstrainedVelocities(desc, dt, acCount, gravity, Z, deltaV, invLengthScale); } static void updateBodies(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt) { FeatherstoneArticulation::updateBodies(desc, tempDeltaV, dt); } static void updateBodiesTGS(const ArticulationSolverDesc& desc, Cm::SpatialVectorF* tempDeltaV, PxReal dt) { FeatherstoneArticulation::updateBodiesTGS(desc, tempDeltaV, dt); } static void saveVelocity(FeatherstoneArticulation* articulation, Cm::SpatialVectorF* tempDeltaV) { FeatherstoneArticulation::saveVelocity(articulation, tempDeltaV); } static void saveVelocityTGS(FeatherstoneArticulation* articulation, PxReal invDtF32) { FeatherstoneArticulation::saveVelocityTGS(articulation, invDtF32); } static void computeUnconstrainedVelocitiesTGS(const ArticulationSolverDesc& desc, PxReal dt, const PxVec3& gravity, PxU64 contextID, Cm::SpatialVectorF* Z, Cm::SpatialVectorF* DeltaV, const PxReal invLengthScale) { FeatherstoneArticulation::computeUnconstrainedVelocitiesTGS(desc, dt, gravity, contextID, Z, DeltaV, invLengthScale); } static void updateDeltaMotion(const ArticulationSolverDesc& desc, const PxReal dt, Cm::SpatialVectorF* DeltaV, const PxReal totalInvDt) { FeatherstoneArticulation::recordDeltaMotion(desc, dt, DeltaV, totalInvDt); } static void deltaMotionToMotionVel(const ArticulationSolverDesc& desc, const PxReal invDt) { FeatherstoneArticulation::deltaMotionToMotionVelocity(desc, invDt); } static PxU32 setupSolverInternalConstraintsTGS(const ArticulationSolverDesc& desc, PxReal dt, PxReal invDt, PxReal totalDt, PxU32& acCount, Cm::SpatialVectorF* Z) { return FeatherstoneArticulation::setupSolverConstraintsTGS(desc, dt, invDt, totalDt, acCount, Z); } }; } } #endif
4,093
C
35.553571
136
0.770584
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactReduction.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_CONTACT_REDUCTION_H #define DY_CONTACT_REDUCTION_H #include "geomutils/PxContactPoint.h" #include "PxsMaterialManager.h" namespace physx { namespace Dy { //KS - might be OK with 4 but 5 guarantees the deepest + 4 contacts that contribute to largest surface area #define CONTACT_REDUCTION_MAX_CONTACTS 6 #define CONTACT_REDUCTION_MAX_PATCHES 32 #define PXS_NORMAL_TOLERANCE 0.995f #define PXS_SEPARATION_TOLERANCE 0.001f //A patch contains a normal, pair of material indices and a list of indices. These indices are //used to index into the PxContact array that's passed by the user struct ReducedContactPatch { PxU32 numContactPoints; PxU32 contactPoints[CONTACT_REDUCTION_MAX_CONTACTS]; }; struct ContactPatch { PxVec3 rootNormal; ContactPatch* mNextPatch; PxReal maxPenetration; PxU16 startIndex; PxU16 stride; PxU16 rootIndex; PxU16 index; }; struct SortBoundsPredicateManifold { bool operator()(const ContactPatch* idx1, const ContactPatch* idx2) const { return idx1->maxPenetration < idx2->maxPenetration; } }; template <PxU32 MaxPatches> class ContactReduction { public: ReducedContactPatch mPatches[MaxPatches]; PxU32 mNumPatches; ContactPatch mIntermediatePatches[CONTACT_REDUCTION_MAX_PATCHES]; ContactPatch* mIntermediatePatchesPtrs[CONTACT_REDUCTION_MAX_PATCHES]; PxU32 mNumIntermediatePatches; PxContactPoint* PX_RESTRICT mOriginalContacts; PxsMaterialInfo* PX_RESTRICT mMaterialInfo; PxU32 mNumOriginalContacts; ContactReduction(PxContactPoint* PX_RESTRICT originalContacts, PxsMaterialInfo* PX_RESTRICT materialInfo, PxU32 numContacts) : mNumPatches(0), mNumIntermediatePatches(0), mOriginalContacts(originalContacts), mMaterialInfo(materialInfo), mNumOriginalContacts(numContacts) { } void reduceContacts() { //First pass, break up into contact patches, storing the start and stride of the patches //We will need to have contact patches and then coallesce them mIntermediatePatches[0].rootNormal = mOriginalContacts[0].normal; mIntermediatePatches[0].mNextPatch = NULL; mIntermediatePatches[0].startIndex = 0; mIntermediatePatches[0].rootIndex = 0; mIntermediatePatches[0].maxPenetration = mOriginalContacts[0].separation; mIntermediatePatches[0].index = 0; PxU16 numPatches = 1; //PxU32 startIndex = 0; PxU32 numUniquePatches = 1; PxU16 m = 1; for(; m < mNumOriginalContacts; ++m) { PxI32 index = -1; for(PxU32 b = numPatches; b > 0; --b) { ContactPatch& patch = mIntermediatePatches[b-1]; if(mMaterialInfo[patch.startIndex].mMaterialIndex0 == mMaterialInfo[m].mMaterialIndex0 && mMaterialInfo[patch.startIndex].mMaterialIndex1 == mMaterialInfo[m].mMaterialIndex1 && patch.rootNormal.dot(mOriginalContacts[m].normal) >= PXS_NORMAL_TOLERANCE) { index = PxI32(b-1); break; } } if(index != numPatches - 1) { mIntermediatePatches[numPatches-1].stride = PxU16(m - mIntermediatePatches[numPatches - 1].startIndex); //Create a new patch... if(numPatches == CONTACT_REDUCTION_MAX_PATCHES) { break; } mIntermediatePatches[numPatches].startIndex = m; mIntermediatePatches[numPatches].mNextPatch = NULL; if(index == -1) { mIntermediatePatches[numPatches].rootIndex = numPatches; mIntermediatePatches[numPatches].rootNormal = mOriginalContacts[m].normal; mIntermediatePatches[numPatches].maxPenetration = mOriginalContacts[m].separation; mIntermediatePatches[numPatches].index = numPatches; ++numUniquePatches; } else { //Find last element in the link PxU16 rootIndex = mIntermediatePatches[index].rootIndex; mIntermediatePatches[index].mNextPatch = &mIntermediatePatches[numPatches]; mIntermediatePatches[numPatches].rootNormal = mIntermediatePatches[index].rootNormal; mIntermediatePatches[rootIndex].maxPenetration = mIntermediatePatches[numPatches].maxPenetration = PxMin(mIntermediatePatches[rootIndex].maxPenetration, mOriginalContacts[m].separation); mIntermediatePatches[numPatches].rootIndex = rootIndex; mIntermediatePatches[numPatches].index = numPatches; } ++numPatches; } } mIntermediatePatches[numPatches-1].stride = PxU16(m - mIntermediatePatches[numPatches-1].startIndex); //OK, we have a list of contact patches so that we can start contact reduction per-patch //OK, now we can go and reduce the contacts on a per-patch basis... for(PxU32 a = 0; a < numPatches; ++a) { mIntermediatePatchesPtrs[a] = &mIntermediatePatches[a]; } SortBoundsPredicateManifold predicate; PxSort(mIntermediatePatchesPtrs, numPatches, predicate); PxU32 numReducedPatches = 0; for(PxU32 a = 0; a < numPatches; ++a) { if(mIntermediatePatchesPtrs[a]->rootIndex == mIntermediatePatchesPtrs[a]->index) { //Reduce this patch... if(numReducedPatches == MaxPatches) break; ReducedContactPatch& reducedPatch = mPatches[numReducedPatches++]; //OK, now we need to work out if we have to reduce patches... PxU32 contactCount = 0; { ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { contactCount += tmpPatch->stride; tmpPatch = tmpPatch->mNextPatch; } } if(contactCount <= CONTACT_REDUCTION_MAX_CONTACTS) { //Just add the contacts... ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; PxU32 ind = 0; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { reducedPatch.contactPoints[ind++] = tmpPatch->startIndex + b; } tmpPatch = tmpPatch->mNextPatch; } reducedPatch.numContactPoints = contactCount; } else { //Iterate through and find the most extreme point PxU32 ind = 0; { PxReal dist = 0.f; ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { PxReal magSq = mOriginalContacts[tmpPatch->startIndex + b].point.magnitudeSquared(); if(dist < magSq) { ind = tmpPatch->startIndex + b; dist = magSq; } } tmpPatch = tmpPatch->mNextPatch; } } reducedPatch.contactPoints[0] = ind; const PxVec3 p0 = mOriginalContacts[ind].point; //Now find the point farthest from this point... { PxReal maxDist = 0.f; ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { PxReal magSq = (p0 - mOriginalContacts[tmpPatch->startIndex + b].point).magnitudeSquared(); if(magSq > maxDist) { ind = tmpPatch->startIndex + b; maxDist = magSq; } } tmpPatch = tmpPatch->mNextPatch; } } reducedPatch.contactPoints[1] = ind; const PxVec3 p1 = mOriginalContacts[ind].point; //Now find the point farthest from the segment PxVec3 n = (p0 - p1).cross(mIntermediatePatchesPtrs[a]->rootNormal); //PxReal tVal = 0.f; { PxReal maxDist = 0.f; //PxReal tmpTVal; ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { //PxReal magSq = tmpDistancePointSegmentSquared(p0, p1, mOriginalContacts[tmpPatch->startIndex + b].point, tmpTVal); PxReal magSq = (mOriginalContacts[tmpPatch->startIndex + b].point - p0).dot(n); if(magSq > maxDist) { ind = tmpPatch->startIndex + b; //tVal = tmpTVal; maxDist = magSq; } } tmpPatch = tmpPatch->mNextPatch; } } reducedPatch.contactPoints[2] = ind; //const PxVec3 closest = (p0 + (p1 - p0) * tVal); const PxVec3 dir = -n;//closest - p3; { PxReal maxDist = 0.f; //PxReal tVal = 0.f; ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { PxReal magSq = (mOriginalContacts[tmpPatch->startIndex + b].point - p0).dot(dir); if(magSq > maxDist) { ind = tmpPatch->startIndex + b; maxDist = magSq; } } tmpPatch = tmpPatch->mNextPatch; } } reducedPatch.contactPoints[3] = ind; //Now, we iterate through all the points, and cluster the points. From this, we establish the deepest point that's within a //tolerance of this point and keep that point PxReal separation[CONTACT_REDUCTION_MAX_CONTACTS]; PxU32 deepestInd[CONTACT_REDUCTION_MAX_CONTACTS]; for(PxU32 i = 0; i < 4; ++i) { PxU32 index = reducedPatch.contactPoints[i]; separation[i] = mOriginalContacts[index].separation - PXS_SEPARATION_TOLERANCE; deepestInd[i] = index; } ContactPatch* tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { PxContactPoint& point = mOriginalContacts[tmpPatch->startIndex + b]; PxReal distance = PX_MAX_REAL; PxU32 index = 0; for(PxU32 c = 0; c < 4; ++c) { PxVec3 dif = mOriginalContacts[reducedPatch.contactPoints[c]].point - point.point; PxReal d = dif.magnitudeSquared(); if(distance > d) { distance = d; index = c; } } if(separation[index] > point.separation) { deepestInd[index] = tmpPatch->startIndex+b; separation[index] = point.separation; } } tmpPatch = tmpPatch->mNextPatch; } bool chosen[64]; PxMemZero(chosen, sizeof(chosen)); for(PxU32 i = 0; i < 4; ++i) { reducedPatch.contactPoints[i] = deepestInd[i]; chosen[deepestInd[i]] = true; } for(PxU32 i = 4; i < CONTACT_REDUCTION_MAX_CONTACTS; ++i) { separation[i] = PX_MAX_REAL; deepestInd[i] = 0; } tmpPatch = mIntermediatePatchesPtrs[a]; while(tmpPatch) { for(PxU32 b = 0; b < tmpPatch->stride; ++b) { if(!chosen[tmpPatch->startIndex+b]) { PxContactPoint& point = mOriginalContacts[tmpPatch->startIndex + b]; for(PxU32 j = 4; j < CONTACT_REDUCTION_MAX_CONTACTS; ++j) { if(point.separation < separation[j]) { for(PxU32 k = CONTACT_REDUCTION_MAX_CONTACTS-1; k > j; --k) { separation[k] = separation[k-1]; deepestInd[k] = deepestInd[k-1]; } separation[j] = point.separation; deepestInd[j] = tmpPatch->startIndex+b; break; } } } } tmpPatch = tmpPatch->mNextPatch; } for(PxU32 i = 4; i < CONTACT_REDUCTION_MAX_CONTACTS; ++i) { reducedPatch.contactPoints[i] = deepestInd[i]; } reducedPatch.numContactPoints = CONTACT_REDUCTION_MAX_CONTACTS; } } } mNumPatches = numReducedPatches; } }; } } #endif
13,097
C
31.02445
192
0.647095
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyTGSDynamics.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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/PxTime.h" #include "foundation/PxAtomic.h" #include "foundation/PxSIMDHelpers.h" #include "PxvDynamics.h" #include "common/PxProfileZone.h" #include "PxsRigidBody.h" #include "PxsContactManager.h" #include "DyTGSDynamics.h" #include "DyBodyCoreIntegrator.h" #include "DySolverCore.h" #include "DySolverControl.h" #include "DySolverContact.h" #include "DySolverContactPF.h" #include "DyArticulationContactPrep.h" #include "DySolverBody.h" #include "DyConstraintPrep.h" #include "DyConstraintPartition.h" #include "CmFlushPool.h" #include "DyArticulationPImpl.h" #include "PxsMaterialManager.h" #include "DySolverContactPF4.h" #include "DyContactReduction.h" #include "PxcNpContactPrepShared.h" #include "DyContactPrep.h" #include "DySolverControlPF.h" #include "PxSceneDesc.h" #include "PxsSimpleIslandManager.h" #include "PxvNphaseImplementationContext.h" #include "PxsContactManagerState.h" #include "DyContactPrepShared.h" #include "DySolverContext.h" #include "DyDynamics.h" #include "DySolverConstraint1D.h" #include "PxvSimStats.h" #include "DyTGSContactPrep.h" #include "DyFeatherstoneArticulation.h" #include "DySleep.h" #include "DyTGS.h" #define PX_USE_BLOCK_SOLVER 1 #define PX_USE_BLOCK_1D 1 namespace physx { namespace Dy { static inline void waitForBodyProgress(PxTGSSolverBodyVel& body, PxU32 desiredProgress, PxU32 iteration) { const PxI32 target = PxI32(desiredProgress + body.maxDynamicPartition * iteration); volatile PxI32* progress = reinterpret_cast<PxI32*>(&body.partitionMask); WAIT_FOR_PROGRESS(progress, target); } static inline void incrementBodyProgress(PxTGSSolverBodyVel& body) { if (body.maxDynamicPartition != 0) (*reinterpret_cast<volatile PxU32*>(&body.partitionMask))++; } static inline void waitForArticulationProgress(Dy::FeatherstoneArticulation& artic, PxU32 desiredProgress, PxU32 iteration) { const PxI32 target = PxI32(desiredProgress + artic.maxSolverFrictionProgress * iteration); volatile PxI32* progress = reinterpret_cast<PxI32*>(&artic.solverProgress); WAIT_FOR_PROGRESS(progress, target); } static inline void incrementArticulationProgress(Dy::FeatherstoneArticulation& artic) { (*reinterpret_cast<volatile PxU32*>(&artic.solverProgress))++; } static inline void waitForProgresses(const PxSolverConstraintDesc& desc, PxU32 iteration) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) waitForBodyProgress(*desc.tgsBodyA, desc.progressA, iteration); else waitForArticulationProgress(*getArticulationA(desc), desc.progressA, iteration); if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) waitForBodyProgress(*desc.tgsBodyB, desc.progressB, iteration); else waitForArticulationProgress(*getArticulationB(desc), desc.progressB, iteration); } static inline void incrementProgress(const PxSolverConstraintDesc& desc) { if (desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY) { incrementBodyProgress(*desc.tgsBodyA); } else incrementArticulationProgress(*getArticulationA(desc)); if (desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY) incrementBodyProgress(*desc.tgsBodyB); else if(desc.articulationA != desc.articulationB) incrementArticulationProgress(*getArticulationB(desc)); } Context* createTGSDynamicsContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool, PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism, PxReal lengthScale) { return PX_NEW(DynamicsTGSContext)( memBlockPool, scratchAllocator, taskPool, simStats, taskManager, allocatorCallback, materialManager, islandManager, contextID, enableStabilization, useEnhancedDeterminism, lengthScale); } void DynamicsTGSContext::destroy() { this->~DynamicsTGSContext(); PX_FREE_THIS; } void DynamicsTGSContext::resetThreadContexts() { PxcThreadCoherentCacheIterator<ThreadContext, PxcNpMemBlockPool> threadContextIt(mThreadContextPool); ThreadContext* threadContext = threadContextIt.getNext(); while (threadContext != NULL) { threadContext->reset(); threadContext = threadContextIt.getNext(); } } PX_FORCE_INLINE PxVec3 safeRecip(const PxVec3& v) { return PxVec3(v.x == 0.f ? 0.f : 1.f/v.x, v.y == 0.f ? 0.f : 1.f/v.y, v.z == 0.f ? 0.f : 1.f/v.z); } 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) { const PxMat33Padded rotation(globalPose.q); const PxVec3 sqrtInvInertia = computeSafeSqrtInertia(invInertia); const PxVec3 sqrtBodySpaceInertia = safeRecip(sqrtInvInertia); Cm::transformInertiaTensor(sqrtInvInertia, rotation, solverBodyTxInertia.sqrtInvInertia); solverBodyTxInertia.deltaBody2World.p = globalPose.p; solverBodyTxInertia.deltaBody2World.q = PxQuat(PxIdentity); PxMat33 sqrtInertia; Cm::transformInertiaTensor(sqrtBodySpaceInertia, rotation, sqrtInertia); PxVec3 lv = linearVelocity; PxVec3 av = angularVelocity; 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); PxVec3 localAngVel = globalPose.q.rotateInv(av); PxVec3 origMom = localInertia.multiply(localAngVel); PxVec3 torque = -localAngVel.cross(origMom); PxVec3 newMom = origMom + torque * dt; const PxReal denom = newMom.magnitude(); PxReal ratio = denom > 0.f ? origMom.magnitude() / denom : 0.f; newMom *= ratio; PxVec3 newDeltaAngVel = globalPose.q.rotate(invInertia.multiply(newMom) - localAngVel); av += newDeltaAngVel; } if (lockFlags) { if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X) lv.x = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y) lv.y = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z) lv.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) { av.x = 0.f; //data.sqrtInvInertia.column0 = PxVec3(0.f); } if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y) { av.y = 0.f; //data.sqrtInvInertia.column1 = PxVec3(0.f); } if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z) { av.z = 0.f; //data.sqrtInvInertia.column2 = PxVec3(0.f); } } solverVel.linearVelocity = lv; solverVel.angularVelocity = sqrtInertia * av; solverVel.deltaLinDt = PxVec3(0.f); solverVel.deltaAngDt = PxVec3(0.f); solverVel.lockFlags = PxU16(lockFlags); solverVel.isKinematic = isKinematic; solverVel.maxAngVel = PxSqrt(maxAngVelSq); solverVel.partitionMask = 0; solverBodyData.nodeIndex = nodeIndex; solverBodyData.invMass = invMass; solverBodyData.penBiasClamp = maxDepenetrationVelocity; solverBodyData.maxContactImpulse = maxContactImpulse; solverBodyData.reportThreshold = reportThreshold; solverBodyData.originalLinearVelocity = lv; solverBodyData.originalAngularVelocity = av; PX_ASSERT(lv.isFinite()); PX_ASSERT(av.isFinite()); } void copyToSolverBodyDataStepKinematic(const PxVec3& linearVelocity, const PxVec3& angularVelocity, const PxTransform& globalPose, PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxReal maxAngVelSq, PxTGSSolverBodyVel& solverVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData) { const PxMat33Padded rotation(globalPose.q); solverBodyTxInertia.deltaBody2World.p = globalPose.p; solverBodyTxInertia.deltaBody2World.q = PxQuat(PxIdentity); solverBodyTxInertia.sqrtInvInertia = PxMat33(PxVec3(0.f), PxVec3(0.f), PxVec3(0.f)); solverVel.linearVelocity = PxVec3(0.f); solverVel.angularVelocity = PxVec3(0.f); solverVel.deltaLinDt = PxVec3(0.f); solverVel.deltaAngDt = PxVec3(0.f); solverVel.lockFlags = 0; solverVel.isKinematic = true; solverVel.maxAngVel = PxSqrt(maxAngVelSq); solverVel.partitionMask = 0; solverVel.nbStaticInteractions = 0; solverVel.maxDynamicPartition = 0; solverBodyData.nodeIndex = nodeIndex; solverBodyData.invMass = 0.f; solverBodyData.penBiasClamp = maxDepenetrationVelocity; solverBodyData.maxContactImpulse = maxContactImpulse; solverBodyData.reportThreshold = reportThreshold; solverBodyData.originalLinearVelocity = linearVelocity; solverBodyData.originalAngularVelocity = angularVelocity; } // =========================== Basic methods DynamicsTGSContext::DynamicsTGSContext( PxcNpMemBlockPool* memBlockPool, PxcScratchAllocator& scratchAllocator, Cm::FlushPool& taskPool, PxvSimStats& simStats, PxTaskManager* taskManager, PxVirtualAllocatorCallback* allocatorCallback, PxsMaterialManager* materialManager, IG::SimpleIslandManager* islandManager, PxU64 contextID, bool enableStabilization, bool useEnhancedDeterminism, PxReal lengthScale) : Dy::Context (islandManager, allocatorCallback, simStats, enableStabilization, useEnhancedDeterminism, PX_MAX_F32, lengthScale, contextID), // PT: TODO: would make sense to move all the following members to the base class but include paths get in the way atm mThreadContextPool (memBlockPool), mMaterialManager (materialManager), mScratchAllocator (scratchAllocator), mTaskPool (taskPool), mTaskManager (taskManager) { createThresholdStream(*allocatorCallback); createForceChangeThresholdStream(*allocatorCallback); mExceededForceThresholdStream[0] = PX_NEW(ThresholdStream)(*allocatorCallback); mExceededForceThresholdStream[1] = PX_NEW(ThresholdStream)(*allocatorCallback); mThresholdStreamOut = 0; mCurrentIndex = 0; PxMemZero(&mWorldSolverBodyVel, sizeof(mWorldSolverBodyVel)); mWorldSolverBodyVel.lockFlags = 0; mWorldSolverBodyVel.isKinematic = false; mWorldSolverBodyTxInertia.sqrtInvInertia = PxMat33(PxZero); mWorldSolverBodyTxInertia.deltaBody2World = PxTransform(PxIdentity); mWorldSolverBodyData2.penBiasClamp = -PX_MAX_REAL; mWorldSolverBodyData2.maxContactImpulse = PX_MAX_REAL; mWorldSolverBodyData2.nodeIndex = PX_INVALID_NODE; mWorldSolverBodyData2.invMass = 0; mWorldSolverBodyData2.reportThreshold = PX_MAX_REAL; mWorldSolverBodyData2.originalLinearVelocity = PxVec3(0.f); mWorldSolverBodyData2.originalAngularVelocity = PxVec3(0.f); } DynamicsTGSContext::~DynamicsTGSContext() { PX_DELETE(mExceededForceThresholdStream[1]); PX_DELETE(mExceededForceThresholdStream[0]); } void DynamicsTGSContext::setDescFromIndices(PxSolverConstraintDesc& desc, const IG::IslandSim& islandSim, const PxsIndexedInteraction& constraint, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies) { PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1); const PxU32 offsetMap[] = { solverBodyOffset, 0 }; //const PxU32 offsetMap[] = {mKinematicCount, 0}; if (constraint.indexType0 == PxsIndexedInteraction::eARTICULATION) { const PxNodeIndex& nodeIndex0 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation0); const IG::Node& node0 = islandSim.getNode(nodeIndex0); desc.articulationA = node0.getArticulation(); desc.linkIndexA = nodeIndex0.articulationLinkId(); desc.bodyADataIndex = 0; } else { desc.tgsBodyA = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBodyVel : &solverBodies[PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0] + 1]; desc.bodyADataIndex = constraint.indexType0 == PxsIndexedInteraction::eWORLD ? 0 : PxU32(constraint.solverBody0) + offsetMap[constraint.indexType0] + 1; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } if (constraint.indexType1 == PxsIndexedInteraction::eARTICULATION) { const PxNodeIndex& nodeIndex1 = reinterpret_cast<const PxNodeIndex&>(constraint.articulation1); const IG::Node& node1 = islandSim.getNode(nodeIndex1); desc.articulationB = node1.getArticulation(); desc.linkIndexB = nodeIndex1.articulationLinkId();// PxTo8(getLinkIndex(constraint.articulation1)); desc.bodyBDataIndex = 0; } else { desc.tgsBodyB = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? &mWorldSolverBodyVel : &solverBodies[PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1] + 1]; desc.bodyBDataIndex = constraint.indexType1 == PxsIndexedInteraction::eWORLD ? 0 : PxU32(constraint.solverBody1) + offsetMap[constraint.indexType1] + 1; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } void DynamicsTGSContext::setDescFromIndices(PxSolverConstraintDesc& desc, IG::EdgeIndex edgeIndex, const IG::SimpleIslandManager& islandManager, PxU32* bodyRemap, PxU32 solverBodyOffset, PxTGSSolverBodyVel* solverBodies) { PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eBODY == 0); PX_COMPILE_TIME_ASSERT(PxsIndexedInteraction::eKINEMATIC == 1); const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim(); PxNodeIndex node1 = islandSim.getNodeIndex1(edgeIndex); if (node1.isStaticBody()) { desc.tgsBodyA = &mWorldSolverBodyVel; desc.bodyADataIndex = 0; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } else { const IG::Node& node = islandSim.getNode(node1); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { PX_ASSERT(node1.isArticulation()); Dy::FeatherstoneArticulation* a = islandSim.getLLArticulation(node1); PxU8 type; a->fillIndexType(node1.articulationLinkId(),type); if (type == PxsIndexedInteraction::eARTICULATION) { desc.articulationA = a; desc.linkIndexA = node1.articulationLinkId(); } else { desc.tgsBodyA = &mWorldSolverBodyVel; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } desc.bodyADataIndex = 0; } else { PX_ASSERT(!node1.isArticulation()); PxU32 activeIndex = islandSim.getActiveNodeIndex(node1); PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset; desc.tgsBodyA = &solverBodies[index + 1]; desc.bodyADataIndex = index + 1; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } } PxNodeIndex node2 = islandSim.getNodeIndex2(edgeIndex); if (node2.isStaticBody()) { desc.tgsBodyB = &mWorldSolverBodyVel; desc.bodyBDataIndex = 0; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } else { const IG::Node& node = islandSim.getNode(node2); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { PX_ASSERT(node2.isArticulation()); Dy::FeatherstoneArticulation* b = islandSim.getLLArticulation(node2); PxU8 type; b->fillIndexType(node2.articulationLinkId(), type); if (type == PxsIndexedInteraction::eARTICULATION) { desc.articulationB = b; desc.linkIndexB = node2.articulationLinkId(); } else { desc.tgsBodyB = &mWorldSolverBodyVel; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } desc.bodyBDataIndex = 0; } else { PX_ASSERT(!node2.isArticulation()); PxU32 activeIndex = islandSim.getActiveNodeIndex(node2); PxU32 index = node.isKinematic() ? activeIndex : bodyRemap[activeIndex] + solverBodyOffset; desc.tgsBodyB = &solverBodies[index + 1]; desc.bodyBDataIndex = index + 1; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } } namespace { class DynamicsMergeTask : public Cm::Task { PxBaseTask* mSecondContinuation; public: DynamicsMergeTask(PxU64 contextId) : Cm::Task(contextId), mSecondContinuation(NULL) { } void setSecondContinuation(PxBaseTask* task) { task->addReference(); mSecondContinuation = task; } virtual const char* getName() const { return "MergeTask"; } virtual void runInternal() { } virtual void release() { mSecondContinuation->removeReference(); Cm::Task::release(); } }; class KinematicCopyTGSTask : public Cm::Task { const PxNodeIndex* const mKinematicIndices; const PxU32 mNbKinematics; const IG::IslandSim& mIslandSim; PxTGSSolverBodyVel* mVels; PxTGSSolverBodyTxInertia* mInertia; PxTGSSolverBodyData* mBodyData; PX_NOCOPY(KinematicCopyTGSTask) public: static const PxU32 NbKinematicsPerTask = 1024; KinematicCopyTGSTask(const PxNodeIndex* const kinematicIndices, PxU32 nbKinematics, const IG::IslandSim& islandSim, PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* inertias, PxTGSSolverBodyData* datas, PxU64 contextID) : Cm::Task(contextID), mKinematicIndices(kinematicIndices), mNbKinematics(nbKinematics), mIslandSim(islandSim), mVels(vels), mInertia(inertias), mBodyData(datas) { } virtual const char* getName() const { return "KinematicCopyTask"; } virtual void runInternal() { for (PxU32 i = 0; i<mNbKinematics; i++) { PxsRigidBody* rigidBody = mIslandSim.getRigidBody(mKinematicIndices[i]); const PxsBodyCore& core = rigidBody->getCore(); copyToSolverBodyDataStepKinematic(core.linearVelocity, core.angularVelocity, core.body2World, core.maxPenBias, core.maxContactImpulse, mKinematicIndices[i].index(), core.contactReportThreshold, core.maxAngularVelocitySq, mVels[i], mInertia[i], mBodyData[i]); rigidBody->saveLastCCDTransform(); } } }; class UpdateContinuationTGSTask : public Cm::Task { DynamicsTGSContext& mContext; IG::SimpleIslandManager& mSimpleIslandManager; PxBaseTask* mLostTouchTask; PxU32 mMaxArticulationLinks; PX_NOCOPY(UpdateContinuationTGSTask) public: UpdateContinuationTGSTask(DynamicsTGSContext& context, IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* lostTouchTask, PxU64 contextID, PxU32 maxLinks) : Cm::Task(contextID), mContext(context), mSimpleIslandManager(simpleIslandManager), mLostTouchTask(lostTouchTask), mMaxArticulationLinks(maxLinks) { } virtual const char* getName() const { return "UpdateContinuationTask";} virtual void runInternal() { mContext.updatePostKinematic(mSimpleIslandManager, mCont, mLostTouchTask, mMaxArticulationLinks); //Allow lost touch task to run once all tasks have be scheduled mLostTouchTask->removeReference(); } }; } void DynamicsTGSContext::update(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxvNphaseImplementationContext* nphase, PxU32 /*maxPatchesPerCM*/, PxU32 maxArticulationLinks, PxReal dt, const PxVec3& gravity, PxBitMapPinned& /*changedHandleMap*/) { PX_PROFILE_ZONE("Dynamics.solverQueueTasks", mContextID); PX_UNUSED(simpleIslandManager); mOutputIterator = nphase->getContactManagerOutputs(); // PT: TODO: refactor mDt = dt; mInvDt = 1.0f / dt; mGravity = gravity; const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim(); const PxU32 islandCount = islandSim.getNbActiveIslands(); const PxU32 activatedContactCount = islandSim.getNbActivatedEdges(IG::Edge::eCONTACT_MANAGER); const IG::EdgeIndex* const activatingEdges = islandSim.getActivatedEdges(IG::Edge::eCONTACT_MANAGER); for (PxU32 a = 0; a < activatedContactCount; ++a) { PxsContactManager* cm = simpleIslandManager.getContactManager(activatingEdges[a]); if (cm) cm->getWorkUnit().frictionPatchCount = 0; //KS - zero the friction patch count on any activating edges } #if PX_ENABLE_SIM_STATS if (islandCount > 0) { mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics(); mSimStats.mNbActiveDynamicBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); mSimStats.mNbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT); } else { mSimStats.mNbActiveKinematicBodies = islandSim.getNbActiveKinematics(); mSimStats.mNbActiveDynamicBodies = 0; mSimStats.mNbActiveConstraints = 0; } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif mThresholdStreamOut = 0; resetThreadContexts(); //If there is no work to do then we can do nothing at all. if(!islandCount) return; //Block to make sure it doesn't run before stage2 of update! lostTouchTask->addReference(); UpdateContinuationTGSTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateContinuationTGSTask)), UpdateContinuationTGSTask) (*this, simpleIslandManager, lostTouchTask, mContextID, maxArticulationLinks); task->setContinuation(continuation); //KS - test that world solver body's velocities are finite and 0, then set it to 0. //Technically, the velocity should always be 0 but can be stomped if a NAN creeps into the simulation. PX_ASSERT(mWorldSolverBodyVel.linearVelocity == PxVec3(0.f)); PX_ASSERT(mWorldSolverBodyVel.angularVelocity == PxVec3(0.f)); PX_ASSERT(mWorldSolverBodyVel.linearVelocity.isFinite()); PX_ASSERT(mWorldSolverBodyVel.angularVelocity.isFinite()); mWorldSolverBodyVel.linearVelocity = mWorldSolverBodyVel.angularVelocity = PxVec3(0.f); const PxU32 kinematicCount = islandSim.getNbActiveKinematics(); const PxNodeIndex* const kinematicIndices = islandSim.getActiveKinematics(); mKinematicCount = kinematicCount; const PxU32 bodyCount = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE); PxU32 numArtics = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE); { if (kinematicCount + bodyCount > mSolverBodyVelPool.capacity()) { mSolverBodyRemapTable.reserve((kinematicCount + bodyCount + 31 + 1) & ~31); mSolverBodyVelPool.reserve((kinematicCount + bodyCount +31 + 1) & ~31); mSolverBodyTxInertiaPool.reserve((kinematicCount + bodyCount +31 + 1) & ~31); mSolverBodyDataPool2.reserve((kinematicCount + bodyCount +31 + 1) & ~31); } { mSolverBodyVelPool.resize(kinematicCount + bodyCount +1); mSolverBodyTxInertiaPool.resize(kinematicCount + bodyCount +1); mSolverBodyDataPool2.resize(kinematicCount + bodyCount +1); mSolverBodyRemapTable.resize(kinematicCount + bodyCount + 1); } // integrate and copy all the kinematics - overkill, since not all kinematics // need solver bodies mSolverBodyVelPool[0] = mWorldSolverBodyVel; mSolverBodyTxInertiaPool[0] = mWorldSolverBodyTxInertia; mSolverBodyDataPool2[0] = mWorldSolverBodyData2; if(kinematicCount) { PX_PROFILE_ZONE("Dynamics.updateKinematics", mContextID); // PT: TODO: why no PxMemZero here compared to PGS? for (PxU32 i = 0; i < kinematicCount; i+= KinematicCopyTGSTask::NbKinematicsPerTask) { const PxU32 nbToProcess = PxMin(kinematicCount - i, KinematicCopyTGSTask::NbKinematicsPerTask); KinematicCopyTGSTask* kinematicTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(KinematicCopyTGSTask)), KinematicCopyTGSTask) (kinematicIndices + i, nbToProcess, islandSim, &mSolverBodyVelPool[i+1], &mSolverBodyTxInertiaPool[i + 1], &mSolverBodyDataPool2[i + 1], mContextID); kinematicTask->setContinuation(task); kinematicTask->removeReference(); } } } const PxU32 numArticulationConstraints = numArtics* maxArticulationLinks; //Just allocate enough memory to fit worst-case maximum size articulations... const PxU32 nbActiveContactManagers = islandSim.getNbActiveEdges(IG::Edge::eCONTACT_MANAGER); const PxU32 nbActiveConstraints = islandSim.getNbActiveEdges(IG::Edge::eCONSTRAINT); const PxU32 totalConstraintCount = nbActiveConstraints + nbActiveContactManagers + numArticulationConstraints; mSolverConstraintDescPool.forceSize_Unsafe(0); mSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mOrderedSolverConstraintDescPool.forceSize_Unsafe(0); mOrderedSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mOrderedSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mContactConstraintBatchHeaders.forceSize_Unsafe(0); mContactConstraintBatchHeaders.reserve((totalConstraintCount + 63) & (~63)); mContactConstraintBatchHeaders.forceSize_Unsafe(totalConstraintCount); mTempSolverConstraintDescPool.forceSize_Unsafe(0); mTempSolverConstraintDescPool.reserve((totalConstraintCount + 63) & (~63)); mTempSolverConstraintDescPool.forceSize_Unsafe(totalConstraintCount); mContactList.forceSize_Unsafe(0); mContactList.reserve((nbActiveContactManagers + 63u) & (~63u)); mContactList.forceSize_Unsafe(nbActiveContactManagers); mMotionVelocityArray.forceSize_Unsafe(0); mMotionVelocityArray.reserve((bodyCount + 63u) & (~63u)); mMotionVelocityArray.forceSize_Unsafe(bodyCount); mBodyCoreArray.forceSize_Unsafe(0); mBodyCoreArray.reserve((bodyCount + 63u) & (~63u)); mBodyCoreArray.forceSize_Unsafe(bodyCount); mRigidBodyArray.forceSize_Unsafe(0); mRigidBodyArray.reserve((bodyCount + 63u) & (~63u)); mRigidBodyArray.forceSize_Unsafe(bodyCount); mArticulationArray.forceSize_Unsafe(0); mArticulationArray.reserve((numArtics + 63u) & (~63u)); mArticulationArray.forceSize_Unsafe(numArtics); mNodeIndexArray.forceSize_Unsafe(0); mNodeIndexArray.reserve((bodyCount + 63u) & (~63u)); mNodeIndexArray.forceSize_Unsafe(bodyCount); ThresholdStream& stream = getThresholdStream(); stream.forceSize_Unsafe(0); stream.reserve(PxNextPowerOfTwo(nbActiveContactManagers != 0 ? nbActiveContactManagers - 1 : nbActiveContactManagers)); //flip exceeded force threshold buffer mCurrentIndex = 1 - mCurrentIndex; task->removeReference(); } void DynamicsTGSContext::updatePostKinematic(IG::SimpleIslandManager& simpleIslandManager, PxBaseTask* continuation, PxBaseTask* lostTouchTask, PxU32 maxLinks) { const IG::IslandSim& islandSim = simpleIslandManager.getAccurateIslandSim(); const IG::IslandId*const islandIds = islandSim.getActiveIslands(); DynamicsMergeTask* mergeTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(DynamicsMergeTask)), DynamicsMergeTask)(mContextID); mergeTask->setContinuation(continuation); mergeTask->setSecondContinuation(lostTouchTask); PxU32 currentIsland = 0; PxU32 currentBodyIndex = 0; PxU32 currentArticulation = 0; PxU32 currentContact = 0; PxU32 constraintIndex = 0; const PxU32 minIslandSize = mSolverBatchSize; const PxU32 islandCount = islandSim.getNbActiveIslands(); const PxU32 articulationBatchSize = mSolverArticBatchSize; //while(start<sentinel) while (currentIsland < islandCount) { SolverIslandObjectsStep objectStarts; objectStarts.articulations = mArticulationArray.begin() + currentArticulation; objectStarts.bodies = mRigidBodyArray.begin() + currentBodyIndex; objectStarts.contactManagers = mContactList.begin() + currentContact; objectStarts.constraintDescs = mSolverConstraintDescPool.begin() + constraintIndex; objectStarts.orderedConstraintDescs = mOrderedSolverConstraintDescPool.begin() + constraintIndex; objectStarts.constraintBatchHeaders = mContactConstraintBatchHeaders.begin() + constraintIndex; objectStarts.tempConstraintDescs = mTempSolverConstraintDescPool.begin() + constraintIndex; objectStarts.motionVelocities = mMotionVelocityArray.begin() + currentBodyIndex; objectStarts.bodyCoreArray = mBodyCoreArray.begin() + currentBodyIndex; objectStarts.islandIds = islandIds + currentIsland; objectStarts.bodyRemapTable = mSolverBodyRemapTable.begin(); objectStarts.nodeIndexArray = mNodeIndexArray.begin() + currentBodyIndex; PxU32 startIsland = currentIsland; PxU32 constraintCount = 0; PxU32 nbArticulations = 0; PxU32 nbBodies = 0; PxU32 nbConstraints = 0; PxU32 nbContactManagers = 0; while (nbBodies < minIslandSize && currentIsland < islandCount && nbArticulations < articulationBatchSize) { const IG::Island& island = islandSim.getIsland(islandIds[currentIsland]); nbBodies += island.mNodeCount[IG::Node::eRIGID_BODY_TYPE]; nbArticulations += island.mNodeCount[IG::Node::eARTICULATION_TYPE]; nbConstraints += island.mEdgeCount[IG::Edge::eCONSTRAINT]; nbContactManagers += island.mEdgeCount[IG::Edge::eCONTACT_MANAGER]; constraintCount = nbConstraints + nbContactManagers; currentIsland++; } objectStarts.numIslands = currentIsland - startIsland; constraintIndex += nbArticulations* maxLinks; PxsIslandIndices counts; counts.articulations = nbArticulations; counts.bodies = nbBodies; counts.constraints = nbConstraints; counts.contactManagers = nbContactManagers; solveIsland(objectStarts, counts, mKinematicCount + currentBodyIndex, simpleIslandManager, mSolverBodyRemapTable.begin(), mMaterialManager, mOutputIterator, mergeTask); currentBodyIndex += nbBodies; currentArticulation += nbArticulations; currentContact += nbContactManagers; constraintIndex += constraintCount; } mergeTask->removeReference(); } void DynamicsTGSContext::prepareBodiesAndConstraints(const SolverIslandObjectsStep& objects, IG::SimpleIslandManager& islandManager, IslandContextStep& islandContext) { Dy::ThreadContext& mThreadContext = *islandContext.mThreadContext; mThreadContext.mMaxSolverPositionIterations = 0; mThreadContext.mMaxSolverVelocityIterations = 0; mThreadContext.mAxisConstraintCount = 0; mThreadContext.mContactDescPtr = mThreadContext.contactConstraintDescArray; mThreadContext.mFrictionDescPtr = mThreadContext.frictionConstraintDescArray.begin(); mThreadContext.mNumDifferentBodyConstraints = 0; mThreadContext.mNumStaticConstraints = 0; mThreadContext.mNumSelfConstraints = 0; mThreadContext.mNumDifferentBodyFrictionConstraints = 0; mThreadContext.mNumSelfConstraintFrictionBlocks = 0; mThreadContext.mNumSelfFrictionConstraints = 0; mThreadContext.numContactConstraintBatches = 0; mThreadContext.contactDescArraySize = 0; mThreadContext.motionVelocityArray = objects.motionVelocities; mThreadContext.mBodyCoreArray = objects.bodyCoreArray; mThreadContext.mRigidBodyArray = objects.bodies; mThreadContext.mArticulationArray = objects.articulations; mThreadContext.bodyRemapTable = objects.bodyRemapTable; mThreadContext.mNodeIndexArray = objects.nodeIndexArray; const PxU32 frictionConstraintCount = 0; mThreadContext.resizeArrays(frictionConstraintCount, islandContext.mCounts.articulations); PxsBodyCore** PX_RESTRICT bodyArrayPtr = mThreadContext.mBodyCoreArray; PxsRigidBody** PX_RESTRICT rigidBodyPtr = mThreadContext.mRigidBodyArray; FeatherstoneArticulation** PX_RESTRICT articulationPtr = mThreadContext.mArticulationArray; PxU32* PX_RESTRICT bodyRemapTable = mThreadContext.bodyRemapTable; PxU32* PX_RESTRICT nodeIndexArray = mThreadContext.mNodeIndexArray; PxU32 nbIslands = objects.numIslands; const IG::IslandId* const islandIds = objects.islandIds; const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim(); PxU32 bodyIndex = 0, articIndex = 0; for (PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); PxNodeIndex currentIndex = island.mRootNode; while (currentIndex.isValid()) { const IG::Node& node = islandSim.getNode(currentIndex); if (node.getNodeType() == IG::Node::eARTICULATION_TYPE) { articulationPtr[articIndex++] = node.getArticulation(); } else { PxsRigidBody* rigid = node.getRigidBody(); PX_ASSERT(bodyIndex < (islandContext.mCounts.bodies + mKinematicCount + 1)); rigidBodyPtr[bodyIndex] = rigid; bodyArrayPtr[bodyIndex] = &rigid->getCore(); nodeIndexArray[bodyIndex] = currentIndex.index(); bodyRemapTable[islandSim.getActiveNodeIndex(currentIndex)] = bodyIndex++; } currentIndex = node.mNextNode; } } PxsIndexedContactManager* indexedManagers = objects.contactManagers; PxU32 currentContactIndex = 0; for (PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); IG::EdgeIndex contactEdgeIndex = island.mFirstEdge[IG::Edge::eCONTACT_MANAGER]; while (contactEdgeIndex != IG_INVALID_EDGE) { const IG::Edge& edge = islandSim.getEdge(contactEdgeIndex); PxsContactManager* contactManager = islandManager.getContactManager(contactEdgeIndex); if (contactManager) { const PxNodeIndex nodeIndex1 = islandSim.getNodeIndex1(contactEdgeIndex); const PxNodeIndex nodeIndex2 = islandSim.getNodeIndex2(contactEdgeIndex); PxsIndexedContactManager& indexedManager = indexedManagers[currentContactIndex++]; indexedManager.contactManager = contactManager; PX_ASSERT(!nodeIndex1.isStaticBody()); { const IG::Node& node1 = islandSim.getNode(nodeIndex1); //Is it an articulation or not??? if (node1.getNodeType() == IG::Node::eARTICULATION_TYPE) { indexedManager.articulation0 = nodeIndex1.getInd(); const PxU32 linkId = nodeIndex1.articulationLinkId(); node1.getArticulation()->fillIndexType(linkId, indexedManager.indexType0); } else { if (node1.isKinematic()) { indexedManager.indexType0 = PxsIndexedInteraction::eKINEMATIC; indexedManager.solverBody0 = islandSim.getActiveNodeIndex(nodeIndex1); } else { indexedManager.indexType0 = PxsIndexedInteraction::eBODY; indexedManager.solverBody0 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex1)]; } PX_ASSERT(indexedManager.solverBody0 < (islandContext.mCounts.bodies + mKinematicCount + 1)); } } if (nodeIndex2.isStaticBody()) { indexedManager.indexType1 = PxsIndexedInteraction::eWORLD; } else { const IG::Node& node2 = islandSim.getNode(nodeIndex2); //Is it an articulation or not??? if (node2.getNodeType() == IG::Node::eARTICULATION_TYPE) { indexedManager.articulation1 = nodeIndex2.getInd(); const PxU32 linkId = nodeIndex2.articulationLinkId(); node2.getArticulation()->fillIndexType(linkId, indexedManager.indexType1); } else { if (node2.isKinematic()) { indexedManager.indexType1 = PxsIndexedInteraction::eKINEMATIC; indexedManager.solverBody1 = islandSim.getActiveNodeIndex(nodeIndex2); } else { indexedManager.indexType1 = PxsIndexedInteraction::eBODY; indexedManager.solverBody1 = bodyRemapTable[islandSim.getActiveNodeIndex(nodeIndex2)]; } PX_ASSERT(indexedManager.solverBody1 < (islandContext.mCounts.bodies + mKinematicCount + 1)); } } } contactEdgeIndex = edge.mNextIslandEdge; } } islandContext.mCounts.contactManagers = currentContactIndex; } struct ConstraintLess { bool operator()(const PxSolverConstraintDesc& left, const PxSolverConstraintDesc& right) const { return reinterpret_cast<Constraint*>(left.constraint)->index > reinterpret_cast<Constraint*>(right.constraint)->index; } }; void DynamicsTGSContext::setupDescs(IslandContextStep& mIslandContext, const SolverIslandObjectsStep& mObjects, PxU32* mBodyRemapTable, PxU32 mSolverBodyOffset, PxsContactManagerOutputIterator& outputs) { PX_UNUSED(outputs); ThreadContext& mThreadContext = *mIslandContext.mThreadContext; PxSolverConstraintDesc* contactDescPtr = mObjects.constraintDescs; //PxU32 constraintCount = mCounts.constraints + mCounts.contactManagers; PxU32 nbIslands = mObjects.numIslands; const IG::IslandId* const islandIds = mObjects.islandIds; const IG::IslandSim& islandSim = mIslandManager->getAccurateIslandSim(); for (PxU32 i = 0; i < nbIslands; ++i) { const IG::Island& island = islandSim.getIsland(islandIds[i]); IG::EdgeIndex edgeId = island.mFirstEdge[IG::Edge::eCONSTRAINT]; while (edgeId != IG_INVALID_EDGE) { PxSolverConstraintDesc& desc = *contactDescPtr; const IG::Edge& edge = islandSim.getEdge(edgeId); Dy::Constraint* constraint = mIslandManager->getConstraint(edgeId); setDescFromIndices(desc, edgeId, *mIslandManager, mBodyRemapTable, mSolverBodyOffset, mSolverBodyVelPool.begin()); desc.constraint = reinterpret_cast<PxU8*>(constraint); desc.constraintLengthOver16 = DY_SC_TYPE_RB_1D; contactDescPtr++; edgeId = edge.mNextIslandEdge; } } PxSort(mObjects.constraintDescs, PxU32(contactDescPtr - mObjects.constraintDescs), ConstraintLess()); if (mIslandContext.mCounts.contactManagers) { for (PxU32 a = 0; a < mIslandContext.mCounts.contactManagers; ++a) { //PxsContactManagerOutput& output = outputs.getContactManager(mObjects.contactManagers[a].contactManager->getWorkUnit().mNpIndex); //if (output.nbContacts > 0) { PxSolverConstraintDesc& desc = *contactDescPtr; setDescFromIndices(desc, islandSim, mObjects.contactManagers[a], mSolverBodyOffset, mSolverBodyVelPool.begin()); desc.constraint = reinterpret_cast<PxU8*>(mObjects.contactManagers[a].contactManager); desc.constraintLengthOver16 = DY_SC_TYPE_RB_CONTACT; contactDescPtr++; } //else //{ // //Clear friction state! // mObjects.contactManagers[a].contactManager->getWorkUnit().frictionDataPtr = NULL; // mObjects.contactManagers[a].contactManager->getWorkUnit().frictionPatchCount = 0; //} } } mThreadContext.contactDescArraySize = PxU32(contactDescPtr - mObjects.constraintDescs); } void DynamicsTGSContext::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*/) { PX_PROFILE_ZONE("PreIntegrate", mContextID); PxU32 localMaxPosIter = 0; PxU32 localMaxVelIter = 0; for (PxU32 i = 0; i < bodyCount; ++i) { PxsBodyCore& core = *bodyArray[i]; const PxsRigidBody& rBody = *originalBodyArray[i]; const PxU16 iterWord = core.solverIterationCounts; localMaxPosIter = PxMax<PxU32>(PxU32(iterWord & 0xff), localMaxPosIter); localMaxVelIter = PxMax<PxU32>(PxU32(iterWord >> 8), localMaxVelIter); //const Cm::SpatialVector& accel = originalBodyArray[i]->getAccelerationV(); bodyCoreComputeUnconstrainedVelocity(gravity, dt, core.linearDamping, core.angularDamping, rBody.accelScale, core.maxLinearVelocitySq, core.maxAngularVelocitySq, core.linearVelocity, core.angularVelocity, core.disableGravity!=0); copyToSolverBodyDataStep(core.linearVelocity, core.angularVelocity, core.inverseMass, core.inverseInertia, core.body2World, core.maxPenBias, core.maxContactImpulse, nodeIndexArray[i], core.contactReportThreshold, core.maxAngularVelocitySq, core.lockFlags, false, solverBodyVelPool[i+1], solverBodyTxInertia[i+1], solverBodyDataPool2[i+1], dt, core.mFlags & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES); } posIters = localMaxPosIter; velIters = localMaxVelIter; } void DynamicsTGSContext::createSolverConstraints(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders, PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& islandThreadContext, Dy::ThreadContext& threadContext, PxReal stepDt, PxReal totalDt, PxReal invStepDt, const PxReal biasCoefficient, PxI32 velIters) { PX_UNUSED(totalDt); //PX_PROFILE_ZONE("CreateConstraints", 0); PxTransform idt(PxIdentity); BlockAllocator blockAllocator(islandThreadContext.mConstraintBlockManager, threadContext.mConstraintBlockStream, threadContext.mFrictionPatchStreamPair, threadContext.mConstraintSize); PxTGSSolverBodyTxInertia* txInertias = mSolverBodyTxInertiaPool.begin(); PxTGSSolverBodyData* solverBodyDatas = mSolverBodyDataPool2.begin(); const PxReal invTotalDt = 1.f / totalDt; PxReal denom = (totalDt); if (velIters) denom += stepDt; const PxReal invTotalDtPlusStep = 1.f / denom; for (PxU32 h = 0; h < nbHeaders; ++h) { PxConstraintBatchHeader& hdr = headers[h]; PxU32 startIdx = hdr.startIndex; PxU32 endIdx = startIdx + hdr.stride; if (contactDescPtr[startIdx].constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT) { PxTGSSolverContactDesc blockDescs[4]; PxsContactManagerOutput* cmOutputs[4]; PxsContactManager* cms[4]; for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++) { PxSolverConstraintDesc& desc = contactDescPtr[a]; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); PxTGSSolverContactDesc& blockDesc = blockDescs[i]; cms[i] = cm; PxcNpWorkUnit& unit = cm->getWorkUnit(); PxsContactManagerOutput* cmOutput = &outputs.getContactManager(unit.mNpIndex); cmOutputs[i] = cmOutput; PxTGSSolverBodyVel& b0 = *desc.tgsBodyA; PxTGSSolverBodyVel& b1 = *desc.tgsBodyB; PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex]; PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex]; PxTGSSolverBodyData& data0 = solverBodyDatas[desc.bodyADataIndex]; PxTGSSolverBodyData& data1 = solverBodyDatas[desc.bodyBDataIndex]; blockDesc.body0 = &b0; blockDesc.body1 = &b1; blockDesc.bodyFrame0 = unit.rigidCore0->body2World; blockDesc.bodyFrame1 = unit.rigidCore1->body2World; blockDesc.shapeInteraction = cm->getShapeInteraction(); blockDesc.contactForces = cmOutput->contactForces; blockDesc.desc = &desc; blockDesc.body0 = &b0; blockDesc.body1 = &b1; blockDesc.body0TxI = &txI0; blockDesc.body1TxI = &txI1; blockDesc.bodyData0 = &data0; blockDesc.bodyData1 = &data1; blockDesc.hasForceThresholds = !!(unit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD); blockDesc.disableStrongFriction = !!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION); blockDesc.bodyState0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? PxSolverContactDesc::eARTICULATION : PxSolverContactDesc::eDYNAMIC_BODY; if (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) { //kinematic link if (desc.linkIndexB == 0xff) { blockDesc.bodyState1 = PxSolverContactDesc::eSTATIC_BODY; } else { blockDesc.bodyState1 = PxSolverContactDesc::eARTICULATION; } } else { blockDesc.bodyState1 = (unit.flags & PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR) ? PxSolverContactDesc::eKINEMATIC_BODY : ((unit.flags & PxcNpWorkUnitFlag::eDYNAMIC_BODY1) ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eSTATIC_BODY); } //blockDesc.flags = unit.flags; PxReal maxImpulse0 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : data0.maxContactImpulse; PxReal maxImpulse1 = (unit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : data1.maxContactImpulse; PxReal dominance0 = unit.dominance0 ? 1.f : 0.f; PxReal dominance1 = unit.dominance1 ? 1.f : 0.f; blockDesc.invMassScales.linear0 = blockDesc.invMassScales.angular0 = dominance0; blockDesc.invMassScales.linear1 = blockDesc.invMassScales.angular1 = dominance1; blockDesc.restDistance = unit.restDistance; blockDesc.frictionPtr = unit.frictionDataPtr; blockDesc.frictionCount = unit.frictionPatchCount; blockDesc.maxCCDSeparation = PX_MAX_F32; blockDesc.maxImpulse = PxMin(maxImpulse0, maxImpulse1); blockDesc.torsionalPatchRadius = unit.mTorsionalPatchRadius; blockDesc.minTorsionalPatchRadius = unit.mMinTorsionalPatchRadius; blockDesc.offsetSlop = unit.mOffsetSlop; } SolverConstraintPrepState::Enum buildState = SolverConstraintPrepState::eUNBATCHABLE; #if PX_USE_BLOCK_SOLVER if (hdr.stride == 4) { buildState = createFinalizeSolverContacts4Step( cmOutputs, threadContext, blockDescs, invStepDt, totalDt, invTotalDtPlusStep, stepDt, mBounceThreshold, mFrictionOffsetThreshold, mCorrelationDistance, biasCoefficient, blockAllocator); } #endif if (buildState != SolverConstraintPrepState::eSUCCESS) { for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++) { PxSolverConstraintDesc& desc = contactDescPtr[a]; PxsContactManager* cm = reinterpret_cast<PxsContactManager*>(desc.constraint); //PxcNpWorkUnit& n = cm->getWorkUnit(); PxsContactManagerOutput& output = *cmOutputs[i]; //PX_ASSERT(output.nbContacts != 0); createFinalizeSolverContactsStep(blockDescs[i], output, threadContext, invStepDt, invTotalDtPlusStep, totalDt, stepDt, mBounceThreshold, mFrictionOffsetThreshold, mCorrelationDistance, biasCoefficient, blockAllocator); getContactManagerConstraintDesc(output, *cm, desc); //PX_ASSERT(desc.constraint != NULL); } } for (PxU32 i = 0; i < hdr.stride; ++i) { PxsContactManager* cm = cms[i]; PxcNpWorkUnit& unit = cm->getWorkUnit(); unit.frictionDataPtr = blockDescs[i].frictionPtr; unit.frictionPatchCount = blockDescs[i].frictionCount; } } else if (contactDescPtr[startIdx].constraintLengthOver16 == DY_SC_TYPE_RB_1D) { SolverConstraintShaderPrepDesc shaderPrepDescs[4]; PxTGSSolverConstraintPrepDesc prepDescs[4]; for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++) { SolverConstraintShaderPrepDesc& shaderPrepDesc = shaderPrepDescs[i]; PxTGSSolverConstraintPrepDesc& prepDesc = prepDescs[i]; const PxTransform id(PxIdentity); { PxSolverConstraintDesc& desc = contactDescPtr[a]; const Constraint* constraint = reinterpret_cast<const Constraint*>(desc.constraint); const PxConstraintSolverPrep solverPrep = constraint->solverPrep; const void* constantBlock = constraint->constantBlock; const PxU32 constantBlockByteSize = constraint->constantBlockSize; const PxTransform& pose0 = (constraint->body0 ? constraint->body0->getPose() : id); const PxTransform& pose1 = (constraint->body1 ? constraint->body1->getPose() : id); const PxTGSSolverBodyVel* sbody0 = desc.tgsBodyA; const PxTGSSolverBodyVel* sbody1 = desc.tgsBodyB; PxTGSSolverBodyTxInertia& txI0 = txInertias[desc.bodyADataIndex]; PxTGSSolverBodyTxInertia& txI1 = txInertias[desc.bodyBDataIndex]; PxTGSSolverBodyData& data0 = solverBodyDatas[desc.bodyADataIndex]; PxTGSSolverBodyData& data1 = solverBodyDatas[desc.bodyBDataIndex]; shaderPrepDesc.constantBlock = constantBlock; shaderPrepDesc.constantBlockByteSize = constantBlockByteSize; shaderPrepDesc.constraint = constraint; shaderPrepDesc.solverPrep = solverPrep; prepDesc.desc = &desc; prepDesc.bodyFrame0 = pose0; prepDesc.bodyFrame1 = pose1; prepDesc.body0 = sbody0; prepDesc.body1 = sbody1; prepDesc.body0TxI = &txI0; prepDesc.body1TxI = &txI1; prepDesc.bodyData0 = &data0; prepDesc.bodyData1 = &data1; prepDesc.linBreakForce = constraint->linBreakForce; prepDesc.angBreakForce = constraint->angBreakForce; prepDesc.writeback = &getConstraintWriteBackPool()[constraint->index]; setupConstraintFlags(prepDesc, constraint->flags); prepDesc.minResponseThreshold = constraint->minResponseThreshold; prepDesc.bodyState0 = desc.linkIndexA == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION; prepDesc.bodyState1 = desc.linkIndexB == PxSolverConstraintDesc::RIGID_BODY ? PxSolverContactDesc::eDYNAMIC_BODY : PxSolverContactDesc::eARTICULATION; } } SolverConstraintPrepState::Enum buildState = SolverConstraintPrepState::eUNBATCHABLE; #if PX_USE_BLOCK_SOLVER #if PX_USE_BLOCK_1D if (hdr.stride == 4) { PxU32 totalRows; buildState = setupSolverConstraintStep4 (shaderPrepDescs, prepDescs, stepDt, totalDt, invStepDt, invTotalDt, totalRows, blockAllocator, mLengthScale, biasCoefficient); } #endif #endif if (buildState != SolverConstraintPrepState::eSUCCESS) { for (PxU32 a = startIdx, i = 0; a < endIdx; ++a, i++) { PxReal clampedInvDt = invStepDt; SetupSolverConstraintStep(shaderPrepDescs[i], prepDescs[i], blockAllocator, stepDt, totalDt, clampedInvDt, invTotalDt, mLengthScale, biasCoefficient); } } } } } void solveContactBlock (DY_TGS_SOLVE_METHOD_PARAMS); void solve1DBlock (DY_TGS_SOLVE_METHOD_PARAMS); void solveExtContactBlock (DY_TGS_SOLVE_METHOD_PARAMS); void solveExt1DBlock (DY_TGS_SOLVE_METHOD_PARAMS); void solveContact4 (DY_TGS_SOLVE_METHOD_PARAMS); void solve1D4 (DY_TGS_SOLVE_METHOD_PARAMS); TGSSolveBlockMethod g_SolveTGSMethods[] = { 0, solveContactBlock, // DY_SC_TYPE_RB_CONTACT solve1DBlock, // DY_SC_TYPE_RB_1D solveExtContactBlock, // DY_SC_TYPE_EXT_CONTACT solveExt1DBlock, // DY_SC_TYPE_EXT_1D solveContactBlock, // DY_SC_TYPE_STATIC_CONTACT solveContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT solveContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT solveContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT solve1D4, // DY_SC_TYPE_BLOCK_1D, }; void writeBackContact (DY_TGS_WRITEBACK_METHOD_PARAMS); void writeBack1D (DY_TGS_WRITEBACK_METHOD_PARAMS); void writeBackContact4 (DY_TGS_WRITEBACK_METHOD_PARAMS); void writeBack1D4 (DY_TGS_WRITEBACK_METHOD_PARAMS); TGSWriteBackMethod g_WritebackTGSMethods[] = { 0, writeBackContact, // DY_SC_TYPE_RB_CONTACT writeBack1D, // DY_SC_TYPE_RB_1D writeBackContact, // DY_SC_TYPE_EXT_CONTACT writeBack1D, // DY_SC_TYPE_EXT_1D writeBackContact, // DY_SC_TYPE_STATIC_CONTACT writeBackContact, // DY_SC_TYPE_NOFRICTION_RB_CONTACT writeBackContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT writeBackContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT writeBack1D4, // DY_SC_TYPE_BLOCK_1D, }; void solveConclude1DBlock (DY_TGS_CONCLUDE_METHOD_PARAMS); void solveConcludeContactBlock (DY_TGS_CONCLUDE_METHOD_PARAMS); void solveConcludeContact4 (DY_TGS_CONCLUDE_METHOD_PARAMS); void solveConclude1D4 (DY_TGS_CONCLUDE_METHOD_PARAMS); void solveConcludeContactExtBlock (DY_TGS_CONCLUDE_METHOD_PARAMS); void solveConclude1DBlockExt (DY_TGS_CONCLUDE_METHOD_PARAMS); TGSSolveConcludeMethod g_SolveConcludeTGSMethods[] = { 0, solveConcludeContactBlock, // DY_SC_TYPE_RB_CONTACT solveConclude1DBlock, // DY_SC_TYPE_RB_1D solveConcludeContactExtBlock, // DY_SC_TYPE_EXT_CONTACT solveConclude1DBlockExt, // DY_SC_TYPE_EXT_1D solveConcludeContactBlock, // DY_SC_TYPE_STATIC_CONTACT solveConcludeContactBlock, // DY_SC_TYPE_NOFRICTION_RB_CONTACT solveConcludeContact4, // DY_SC_TYPE_BLOCK_RB_CONTACT solveConcludeContact4, // DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT solveConclude1D4, // DY_SC_TYPE_BLOCK_1D, }; void DynamicsTGSContext::solveConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxReal invStepDt, const PxTGSSolverBodyTxInertia* const solverTxInertia, PxReal elapsedTime, PxReal minPenetration, SolverContext& cache) { PX_UNUSED(invStepDt); for (PxU32 h = 0; h < nbHeaders; ++h) { const PxConstraintBatchHeader& hdr = batchHeaders[h]; g_SolveTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, minPenetration, elapsedTime, cache); } } template <bool TSync> void DynamicsTGSContext::parallelSolveConstraints(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxTGSSolverBodyTxInertia* solverTxInertia, PxReal elapsedTime, PxReal minPenetration, SolverContext& cache, PxU32 iterCount) { for (PxU32 h = 0; h < nbHeaders; ++h) { const PxConstraintBatchHeader& hdr = batchHeaders[h]; const PxSolverConstraintDesc& desc = contactDescPtr[hdr.startIndex]; if (TSync) { PX_ASSERT(hdr.stride == 1); waitForProgresses(desc, iterCount); } g_SolveTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, minPenetration, elapsedTime, cache); if (TSync) { PxMemoryBarrier(); incrementProgress(desc); } } } void DynamicsTGSContext::writebackConstraintsIteration(const PxConstraintBatchHeader* const hdrs, const PxSolverConstraintDesc* const contactDescPtr, PxU32 nbHeaders) { PX_PROFILE_ZONE("Writeback", mContextID); for (PxU32 h = 0; h < nbHeaders; ++h) { const PxConstraintBatchHeader& hdr = hdrs[h]; g_WritebackTGSMethods[hdr.constraintType](hdr, contactDescPtr, NULL); } } void DynamicsTGSContext::parallelWritebackConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders) { for (PxU32 h = 0; h < nbHeaders; ++h) { const PxConstraintBatchHeader& hdr = batchHeaders[h]; g_WritebackTGSMethods[hdr.constraintType](hdr, contactDescPtr, NULL); } } template <bool TSync> void DynamicsTGSContext::solveConcludeConstraintsIteration(const PxSolverConstraintDesc* const contactDescPtr, const PxConstraintBatchHeader* const batchHeaders, PxU32 nbHeaders, PxTGSSolverBodyTxInertia* solverTxInertia, PxReal elapsedTime, SolverContext& cache, PxU32 iterCount) { for (PxU32 h = 0; h < nbHeaders; ++h) { const PxConstraintBatchHeader& hdr = batchHeaders[h]; const PxSolverConstraintDesc& desc = contactDescPtr[hdr.startIndex]; if (TSync) waitForProgresses(desc, iterCount); g_SolveConcludeTGSMethods[hdr.constraintType](hdr, contactDescPtr, solverTxInertia, elapsedTime, cache); if (TSync) { PxMemoryBarrier(); incrementProgress(desc); } } } void integrateCoreStep(PxTGSSolverBodyVel& vel, PxTGSSolverBodyTxInertia& txInertia, PxF32 dt) { PxU32 lockFlags = vel.lockFlags; if (lockFlags) { if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X) vel.linearVelocity.x = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y) vel.linearVelocity.y = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z) vel.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) vel.angularVelocity.x = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y) vel.angularVelocity.y = 0.f; if (lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z) vel.angularVelocity.z = 0.f; } PxVec3 linearMotionVel = vel.linearVelocity; const PxVec3 delta = linearMotionVel * dt; PxVec3 unmolestedAngVel = vel.angularVelocity; PxVec3 angularMotionVel = txInertia.sqrtInvInertia * vel.angularVelocity; PxReal w2 = angularMotionVel.magnitudeSquared(); txInertia.deltaBody2World.p += delta; PX_ASSERT(txInertia.deltaBody2World.p.isFinite()); // Integrate the rotation using closed form quaternion integrator if (w2 != 0.0f) { PxReal w = PxSqrt(w2); //KS - we allow a little bit more angular velocity than the default //maxAngVel member otherwise the simulation feels a little flimsy /*const PxReal maxW = PxMax(50.f, vel.maxAngVel); if (w > maxW) { PxReal ratio = maxW / w; vel.angularVelocity *= ratio; }*/ 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 * txInertia.deltaBody2World.q; result += txInertia.deltaBody2World.q * q; txInertia.deltaBody2World.q = result.getNormalized(); PX_ASSERT(txInertia.deltaBody2World.q.isSane()); PX_ASSERT(txInertia.deltaBody2World.q.isFinite()); //Accumulate the angular rotations in a space we can project the angular constraints to } vel.deltaAngDt += unmolestedAngVel * dt; vel.deltaLinDt += delta; /*solverBodyData.body2World = txInertia.body2World; solverBodyData.deltaLinDt = vel.deltaLinDt; solverBodyData.deltaAngDt = vel.deltaAngDt;*/ } void averageVelocity(PxTGSSolverBodyVel& vel, PxF32 invDt, PxReal ratio) { const PxVec3 frameLinVel = vel.deltaLinDt*invDt; const PxVec3 frameAngVel = vel.deltaAngDt*invDt; if (frameLinVel.magnitudeSquared() < vel.linearVelocity.magnitudeSquared() || frameAngVel.magnitudeSquared() < vel.angularVelocity.magnitudeSquared()) { const PxReal otherRatio = 1.f - ratio; vel.linearVelocity = (vel.linearVelocity*ratio + frameLinVel*otherRatio); vel.angularVelocity = (vel.angularVelocity*ratio + frameAngVel*otherRatio); } } void DynamicsTGSContext::integrateBodies(const SolverIslandObjectsStep& /*objects*/, PxU32 count, PxTGSSolverBodyVel* PX_RESTRICT vels, PxTGSSolverBodyTxInertia* PX_RESTRICT txInertias, const PxTGSSolverBodyData*const PX_RESTRICT /*bodyDatas*/, PxReal dt, PxReal invTotalDt, bool average, PxReal ratio) { for (PxU32 k = 0; k < count; k++) { integrateCoreStep(vels[k + 1], txInertias[k + 1], dt); if (average) averageVelocity(vels[k + 1], invTotalDt, ratio); } } void DynamicsTGSContext::parallelIntegrateBodies(PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias, const PxTGSSolverBodyData* const /*bodyDatas*/, PxU32 count, PxReal dt, PxU32 iteration, PxReal invTotalDt, bool average, PxReal ratio) { PX_UNUSED(iteration); for (PxU32 k = 0; k < count; k++) { PX_ASSERT(vels[k + 1].partitionMask == (iteration * vels[k + 1].maxDynamicPartition)); integrateCoreStep(vels[k + 1], txInertias[k + 1], dt); if (average) averageVelocity(vels[k + 1], invTotalDt, ratio); } } void DynamicsTGSContext::copyBackBodies(const SolverIslandObjectsStep& objects, PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyDatas, PxReal invDt, IG::IslandSim& islandSim, PxU32 startIdx, PxU32 endIdx) { for (PxU32 k = startIdx; k < endIdx; k++) { //PxStepSolverBody& solverBodyData = solverBodyData2[k + 1]; PxTGSSolverBodyVel& solverBodyVel = vels[k + 1]; PxTGSSolverBodyTxInertia& solverBodyTxI = txInertias[k + 1]; PxTGSSolverBodyData& solverBodyData = solverBodyDatas[k + 1]; const Cm::SpatialVector motionVel(solverBodyVel.deltaLinDt*invDt, solverBodyTxI.sqrtInvInertia*(solverBodyVel.deltaAngDt*invDt)); PxsRigidBody& rBody = *objects.bodies[k]; PxsBodyCore& core = rBody.getCore(); rBody.mLastTransform = core.body2World; core.body2World.q = (solverBodyTxI.deltaBody2World.q * core.body2World.q).getNormalized(); core.body2World.p = solverBodyTxI.deltaBody2World.p; /*core.linearVelocity = (solverBodyVel.linearVelocity); core.angularVelocity = solverBodyTxI.sqrtInvInertia*(solverBodyVel.angularVelocity);*/ PxVec3 linearVelocity = (solverBodyVel.linearVelocity); PxVec3 angularVelocity = solverBodyTxI.sqrtInvInertia*(solverBodyVel.angularVelocity); core.linearVelocity = linearVelocity; core.angularVelocity = angularVelocity; const bool hasStaticTouch = islandSim.getIslandStaticTouchCount(PxNodeIndex(solverBodyData.nodeIndex)) != 0; sleepCheck(&rBody, mDt, mEnableStabilization, motionVel, hasStaticTouch); } } void DynamicsTGSContext::stepArticulations(Dy::ThreadContext& threadContext, const PxsIslandIndices& counts, PxReal dt, PxReal totalInvDt) { for (PxU32 a = 0; a < counts.articulations; ++a) { ArticulationSolverDesc& d = threadContext.getArticulations()[a]; //if(d.articulation->numTotalConstraints > 0) //d.articulation->solveInternalConstraints(dt, 1.f / dt, threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), false); ArticulationPImpl::updateDeltaMotion(d, dt, threadContext.mDeltaV.begin(), totalInvDt); } } void DynamicsTGSContext::updateArticulations(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt) { for (PxU32 a = startIdx; a < endIdx; ++a) { ArticulationSolverDesc& d = threadContext.getArticulations()[a]; ArticulationPImpl::updateBodiesTGS(d, threadContext.mDeltaV.begin(), dt); } } namespace { class ArticulationTask : public Cm::Task { Dy::DynamicsTGSContext& mContext; ArticulationSolverDesc* mDescs; PxU32 mNbDescs; PxVec3 mGravity; PxReal mDt; PX_NOCOPY(ArticulationTask) public: static const PxU32 MaxNbPerTask = 32; ArticulationTask(Dy::DynamicsTGSContext& context, ArticulationSolverDesc* descs, PxU32 nbDescs, const PxVec3& gravity, PxReal dt, PxU64 contextId) : Cm::Task(contextId), mContext(context), mDescs(descs), mNbDescs(nbDescs), mGravity(gravity), mDt(dt) { } virtual const char* getName() const { return "ArticulationTask"; } virtual void runInternal() { PxU32 maxLinks = 0; for (PxU32 i = 0; i < mNbDescs; i++) { maxLinks = PxMax(maxLinks, PxU32(mDescs[i].linkCount)); } Dy::ThreadContext& threadContext = *mContext.getThreadContext(); threadContext.mZVector.forceSize_Unsafe(0); threadContext.mZVector.reserve(maxLinks); threadContext.mZVector.forceSize_Unsafe(maxLinks); threadContext.mDeltaV.forceSize_Unsafe(0); threadContext.mDeltaV.reserve(maxLinks); threadContext.mDeltaV.forceSize_Unsafe(maxLinks); const PxReal invLengthScale = 1.f / mContext.getLengthScale(); for (PxU32 a = 0; a < mNbDescs; ++a) { ArticulationPImpl::computeUnconstrainedVelocitiesTGS(mDescs[a], mDt, mGravity, getContextId(), threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), invLengthScale); } mContext.putThreadContext(&threadContext); } }; } void DynamicsTGSContext::setupArticulations(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, PxBaseTask* continuation) { Dy::FeatherstoneArticulation** articulations = islandContext.mThreadContext->mArticulationArray; PxU32 nbArticulations = islandContext.mCounts.articulations; PxU32 maxVelIters = 0; PxU32 maxPosIters = 0; //PxU32 startIdx = 0; for (PxU32 a = 0; a < nbArticulations; a+= ArticulationTask::MaxNbPerTask) { const PxU32 endIdx = PxMin(nbArticulations, a + ArticulationTask::MaxNbPerTask); for (PxU32 b = a; b < endIdx; ++b) { ArticulationSolverDesc& desc = islandContext.mThreadContext->getArticulations()[b]; articulations[b]->getSolverDesc(desc); articulations[b]->mArticulationIndex = PxU16(b); const PxU16 iterWord = articulations[b]->getIterationCounts(); maxVelIters = PxMax<PxU32>(PxU32(iterWord >> 8), maxVelIters); maxPosIters = PxMax<PxU32>(PxU32(iterWord & 0xff), maxPosIters); } Dy::ThreadContext* threadContext = islandContext.mThreadContext; ArticulationTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(ArticulationTask)), ArticulationTask)(*this, threadContext->getArticulations().begin() + a, endIdx - a, gravity, dt, getContextId()); task->setContinuation(continuation); task->removeReference(); //startIdx += descCount; } velIters = PxMax(maxVelIters, velIters); posIters = PxMax(maxPosIters, posIters); } PxU32 DynamicsTGSContext::setupArticulationInternalConstraints(IslandContextStep& islandContext, PxReal dt, PxReal invStepDt) { Dy::FeatherstoneArticulation** articulations = islandContext.mThreadContext->mArticulationArray; PxU32 nbArticulations = islandContext.mCounts.articulations; ThreadContext* threadContext = getThreadContext(); threadContext->mConstraintBlockStream.reset(); PxU32 totalDescCount = 0; for (PxU32 a = 0; a < nbArticulations; ++a) { ArticulationSolverDesc& desc = islandContext.mThreadContext->getArticulations()[a]; articulations[a]->getSolverDesc(desc); PxU32 acCount; PxU32 descCount = ArticulationPImpl::setupSolverInternalConstraintsTGS(desc, islandContext.mStepDt, invStepDt, dt, acCount, threadContext->mZVector.begin()); desc.numInternalConstraints = PxTo8(descCount); totalDescCount += descCount; } putThreadContext(threadContext); islandContext.mThreadContext->contactDescArraySize += totalDescCount; return totalDescCount; } class SetupDescsTask : public Cm::Task { Dy::IslandContextStep& mIslandContext; const SolverIslandObjectsStep& mObjects; PxU32* mBodyRemapTable; PxU32 mSolverBodyOffset; PxsContactManagerOutputIterator& mOutputs; DynamicsTGSContext& mContext; PX_NOCOPY(SetupDescsTask) public: SetupDescsTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, PxU32* bodyRemapTable, PxU32 solverBodyOffset, PxsContactManagerOutputIterator& outputs, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mObjects(objects), mBodyRemapTable(bodyRemapTable), mSolverBodyOffset(solverBodyOffset), mOutputs(outputs), mContext(context) { } virtual const char* getName() const { return "SetupDescsTask"; } virtual void runInternal() { mContext.setupDescs(mIslandContext, mObjects, mBodyRemapTable, mSolverBodyOffset, mOutputs); mIslandContext.mArticulationOffset = mIslandContext.mThreadContext->contactDescArraySize; } }; class PreIntegrateParallelTask : public Cm::Task { PxsBodyCore** mBodyArray; PxsRigidBody** mOriginalBodyArray; PxTGSSolverBodyVel* mSolverBodyVelPool; PxTGSSolverBodyTxInertia* mSolverBodyTxInertia; PxTGSSolverBodyData* mSolverBodyDataPool2; PxU32* mNodeIndexArray; const PxU32 mBodyCount; const PxVec3& mGravity; const PxReal mDt; PxU32& mPosIters; PxU32& mVelIters; DynamicsTGSContext& mContext; PX_NOCOPY(PreIntegrateParallelTask) public: PreIntegrateParallelTask(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray, PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2, PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mBodyArray(bodyArray), mOriginalBodyArray(originalBodyArray), mSolverBodyVelPool(solverBodyVelPool), mSolverBodyTxInertia(solverBodyTxInertia), mSolverBodyDataPool2(solverBodyDataPool2), mNodeIndexArray(nodeIndexArray), mBodyCount(bodyCount), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context) { } virtual const char* getName() const { return "PreIntegrateParallelTask"; } virtual void runInternal() { PxU32 posIters = 0; PxU32 velIters = 0; mContext.preIntegrateBodies(mBodyArray, mOriginalBodyArray, mSolverBodyVelPool, mSolverBodyTxInertia, mSolverBodyDataPool2, mNodeIndexArray, mBodyCount, mGravity, mDt, posIters, velIters, 0); PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters)); PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters)); } }; class PreIntegrateTask : public Cm::Task { PxsBodyCore** mBodyArray; PxsRigidBody** mOriginalBodyArray; PxTGSSolverBodyVel* mSolverBodyVelPool; PxTGSSolverBodyTxInertia* mSolverBodyTxInertia; PxTGSSolverBodyData* mSolverBodyDataPool2; PxU32* mNodeIndexArray; const PxU32 mBodyCount; const PxVec3& mGravity; const PxReal mDt; PxU32& mPosIters; PxU32& mVelIters; DynamicsTGSContext& mContext; PX_NOCOPY(PreIntegrateTask) public: PreIntegrateTask(PxsBodyCore** bodyArray, PxsRigidBody** originalBodyArray, PxTGSSolverBodyVel* solverBodyVelPool, PxTGSSolverBodyTxInertia* solverBodyTxInertia, PxTGSSolverBodyData* solverBodyDataPool2, PxU32* nodeIndexArray, PxU32 bodyCount, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mBodyArray(bodyArray), mOriginalBodyArray(originalBodyArray), mSolverBodyVelPool(solverBodyVelPool), mSolverBodyTxInertia(solverBodyTxInertia), mSolverBodyDataPool2(solverBodyDataPool2), mNodeIndexArray(nodeIndexArray), mBodyCount(bodyCount), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context) { } virtual const char* getName() const { return "PreIntegrateTask"; } virtual void runInternal() { const PxU32 BodiesPerTask = 512; if (mBodyCount <= BodiesPerTask) { PxU32 posIters = 0; PxU32 velIters = 0; mContext.preIntegrateBodies(mBodyArray, mOriginalBodyArray, mSolverBodyVelPool, mSolverBodyTxInertia, mSolverBodyDataPool2, mNodeIndexArray, mBodyCount, mGravity, mDt, posIters, velIters, 0); PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters)); PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters)); } else { for (PxU32 i = 0; i < mBodyCount; i += BodiesPerTask) { const PxU32 nbToProcess = PxMin(mBodyCount - i, BodiesPerTask); PreIntegrateParallelTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PreIntegrateParallelTask)), PreIntegrateParallelTask) (mBodyArray+i, mOriginalBodyArray+i, mSolverBodyVelPool+i, mSolverBodyTxInertia+i, mSolverBodyDataPool2+i,mNodeIndexArray+i, nbToProcess, mGravity, mDt, mPosIters, mVelIters, mContext); task->setContinuation(mCont); task->removeReference(); } } } }; class SetStepperTask : public Cm::Task { Dy::IslandContextStep& mIslandContext; Dy::DynamicsTGSContext& mContext; PxBaseTask* mAdditionalContinuation; PX_NOCOPY(SetStepperTask) public: SetStepperTask(Dy::IslandContextStep& islandContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mContext(context), mAdditionalContinuation(NULL) { } virtual const char* getName() const { return "SetStepperTask"; } void setAdditionalContinuation(PxBaseTask* cont) { mAdditionalContinuation = cont; cont->addReference(); } virtual void runInternal() { PxReal dt = mContext.getDt(); mIslandContext.mStepDt = dt / PxReal(mIslandContext.mPosIters); mIslandContext.mInvStepDt = 1.f/mIslandContext.mStepDt;//PxMin(1000.f, 1.f / mIslandContext.mStepDt); mIslandContext.mBiasCoefficient = 2.f * PxSqrt(1.f/mIslandContext.mPosIters); } virtual void release() { Cm::Task::release(); mAdditionalContinuation->removeReference(); } }; class SetupArticulationTask : public Cm::Task { IslandContextStep& mIslandContext; const PxVec3& mGravity; const PxReal mDt; PxU32& mPosIters; PxU32& mVelIters; DynamicsTGSContext& mContext; PX_NOCOPY(SetupArticulationTask) public: SetupArticulationTask(IslandContextStep& islandContext, const PxVec3& gravity, PxReal dt, PxU32& posIters, PxU32& velIters, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mGravity(gravity), mDt(dt), mPosIters(posIters), mVelIters(velIters), mContext(context) { } virtual const char* getName() const { return "SetupArticulationTask"; } virtual void runInternal() { PxU32 posIters = 0, velIters = 0; mContext.setupArticulations(mIslandContext, mGravity, mDt, posIters, velIters, mCont); PxAtomicMax(reinterpret_cast<PxI32*>(&mPosIters), PxI32(posIters)); PxAtomicMax(reinterpret_cast<PxI32*>(&mVelIters), PxI32(velIters)); } }; class SetupArticulationInternalConstraintsTask : public Cm::Task { IslandContextStep& mIslandContext; const PxReal mDt; const PxReal mInvDt; DynamicsTGSContext& mContext; PX_NOCOPY(SetupArticulationInternalConstraintsTask) public: SetupArticulationInternalConstraintsTask(IslandContextStep& islandContext, PxReal dt, PxReal invDt, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mDt(dt), mInvDt(invDt), mContext(context) { } virtual const char* getName() const { return "SetupArticulationInternalConstraintsTask"; } virtual void runInternal() { mContext.setupArticulationInternalConstraints(mIslandContext, mDt, mIslandContext.mInvStepDt); } }; class SetupSolverConstraintsSubTask : public Cm::Task { PxSolverConstraintDesc* mContactDescPtr; PxConstraintBatchHeader* mHeaders; const PxU32 mNbHeaders; PxsContactManagerOutputIterator& mOutputs; PxReal mStepDt; PxReal mTotalDt; PxReal mInvStepDt; PxReal mInvDtTotal; PxReal mBiasCoefficient; DynamicsTGSContext& mContext; ThreadContext& mIslandThreadContext; PxI32 mVelIters; PX_NOCOPY(SetupSolverConstraintsSubTask) public: static const PxU32 MaxPerTask = 64; SetupSolverConstraintsSubTask(PxSolverConstraintDesc* contactDescPtr, PxConstraintBatchHeader* headers, PxU32 nbHeaders, PxsContactManagerOutputIterator& outputs, PxReal stepDt, PxReal totalDt, PxReal invStepDt, PxReal invDtTotal, PxReal biasCoefficient, ThreadContext& islandThreadContext, DynamicsTGSContext& context, PxI32 velIters) : Cm::Task(context.getContextId()), mContactDescPtr(contactDescPtr), mHeaders(headers), mNbHeaders(nbHeaders), mOutputs(outputs), mStepDt(stepDt), mTotalDt(totalDt), mInvStepDt(invStepDt), mInvDtTotal(invDtTotal), mBiasCoefficient(biasCoefficient), mContext(context), mIslandThreadContext(islandThreadContext), mVelIters(velIters) { } virtual const char* getName() const { return "SetupSolverConstraintsSubTask"; } virtual void runInternal() { ThreadContext* tempContext = mContext.getThreadContext(); tempContext->mConstraintBlockStream.reset(); mContext.createSolverConstraints(mContactDescPtr, mHeaders, mNbHeaders, mOutputs, mIslandThreadContext, *tempContext, mStepDt, mTotalDt, mInvStepDt, mBiasCoefficient, mVelIters); mContext.putThreadContext(tempContext); } }; class PxsCreateArticConstraintsSubTask : public Cm::Task { PxsCreateArticConstraintsSubTask& operator=(const PxsCreateArticConstraintsSubTask&); public: static const PxU32 NbArticsPerTask = 64; PxsCreateArticConstraintsSubTask(Dy::FeatherstoneArticulation** articulations, const PxU32 nbArticulations, PxTGSSolverBodyData* solverBodyData, PxTGSSolverBodyTxInertia* solverBodyTxInertia, ThreadContext& threadContext, DynamicsTGSContext& context, PxsContactManagerOutputIterator& outputs, Dy::IslandContextStep& islandContext) : Cm::Task(context.getContextId()), mArticulations(articulations), mNbArticulations(nbArticulations), mSolverBodyData(solverBodyData), mSolverBodyTxInertia(solverBodyTxInertia), mThreadContext(threadContext), mDynamicsContext(context), mOutputs(outputs), mIslandContext(islandContext) {} virtual void runInternal() { const PxReal correlationDist = mDynamicsContext.getCorrelationDistance(); const PxReal bounceThreshold = mDynamicsContext.getBounceThreshold(); const PxReal frictionOffsetThreshold = mDynamicsContext.getFrictionOffsetThreshold(); const PxReal dt = mDynamicsContext.getDt(); const PxReal invStepDt = PxMin(mDynamicsContext.getMaxBiasCoefficient(), mIslandContext.mInvStepDt); PxReal denom = dt; if (mIslandContext.mVelIters) denom += mIslandContext.mStepDt; PxReal invDt = 1.f / denom; ThreadContext* threadContext = mDynamicsContext.getThreadContext(); threadContext->mConstraintBlockStream.reset(); //ensure there's no left-over memory that belonged to another island /*threadContext->mZVector.forceSize_Unsafe(0); threadContext->mZVector.reserve(mThreadContext.mMaxArticulationLinks); threadContext->mZVector.forceSize_Unsafe(mThreadContext.mMaxArticulationLinks);*/ for (PxU32 i = 0; i < mNbArticulations; ++i) { mArticulations[i]->prepareStaticConstraintsTGS(mIslandContext.mStepDt, dt, invStepDt, invDt, mOutputs, *threadContext, correlationDist, bounceThreshold, frictionOffsetThreshold, mSolverBodyData, mSolverBodyTxInertia, mThreadContext.mConstraintBlockManager, mDynamicsContext.getConstraintWriteBackPool().begin(), mIslandContext.mBiasCoefficient, mDynamicsContext.getLengthScale()); } mDynamicsContext.putThreadContext(threadContext); } virtual const char* getName() const { return "PxsDynamics.PxsCreateArticConstraintsSubTask"; } public: Dy::FeatherstoneArticulation** mArticulations; PxU32 mNbArticulations; PxTGSSolverBodyData* mSolverBodyData; PxTGSSolverBodyTxInertia* mSolverBodyTxInertia; ThreadContext& mThreadContext; DynamicsTGSContext& mDynamicsContext; PxsContactManagerOutputIterator& mOutputs; IslandContextStep& mIslandContext; }; class SetupSolverConstraintsTask : public Cm::Task { IslandContextStep& mIslandContext; PxSolverConstraintDesc* mContactDescPtr; PxsContactManagerOutputIterator& mOutputs; Dy::ThreadContext& mThreadContext; PxReal mTotalDt; DynamicsTGSContext& mContext; PX_NOCOPY(SetupSolverConstraintsTask) public: SetupSolverConstraintsTask(IslandContextStep& islandContext, PxSolverConstraintDesc* contactDescPtr, PxsContactManagerOutputIterator& outputs, Dy::ThreadContext& threadContext, PxReal totalDt, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mContactDescPtr(contactDescPtr), mOutputs(outputs), mThreadContext(threadContext), mTotalDt(totalDt), mContext(context) { } virtual const char* getName() const { return "SetupSolverConstraintsTask"; } virtual void runInternal() { Dy::ThreadContext& threadContext = *mIslandContext.mThreadContext; const PxU32 nbBatches = threadContext.numContactConstraintBatches; PxConstraintBatchHeader* hdr = mIslandContext.mObjects.constraintBatchHeaders; //for (PxU32 a = 0; a < mIslandContext.mArticulationOffset; a += SetupSolverConstraintsSubTask::MaxPerTask) for (PxU32 a = 0; a < nbBatches; a += SetupSolverConstraintsSubTask::MaxPerTask) { const PxU32 nbConstraints = PxMin(nbBatches - a, SetupSolverConstraintsSubTask::MaxPerTask); SetupSolverConstraintsSubTask* task = PX_PLACEMENT_NEW(mContext.mTaskPool.allocate(sizeof(SetupSolverConstraintsSubTask)), SetupSolverConstraintsSubTask) (mContactDescPtr, hdr + a, nbConstraints, mOutputs, mIslandContext.mStepDt, mTotalDt, mIslandContext.mInvStepDt, mContext.mInvDt, mIslandContext.mBiasCoefficient, mThreadContext, mContext, mIslandContext.mVelIters); task->setContinuation(mCont); task->removeReference(); } const PxU32 articCount = mIslandContext.mCounts.articulations; for (PxU32 i = 0; i < articCount; i += PxsCreateArticConstraintsSubTask::NbArticsPerTask) { const PxU32 nbToProcess = PxMin(articCount - i, PxsCreateArticConstraintsSubTask::NbArticsPerTask); PxsCreateArticConstraintsSubTask* task = PX_PLACEMENT_NEW(mContext.getTaskPool().allocate(sizeof(PxsCreateArticConstraintsSubTask)), PxsCreateArticConstraintsSubTask) (mThreadContext.mArticulationArray + i, nbToProcess, mContext.mSolverBodyDataPool2.begin(), mContext.mSolverBodyTxInertiaPool.begin(), mThreadContext, mContext, mOutputs, mIslandContext); task->setContinuation(mCont); task->removeReference(); } } }; class PartitionTask : public Cm::Task { IslandContextStep& mIslandContext; const PxSolverConstraintDesc* mContactDescPtr; PxTGSSolverBodyVel* mSolverBodyData; Dy::ThreadContext& mThreadContext; DynamicsTGSContext& mContext; PX_NOCOPY(PartitionTask) public: PartitionTask(IslandContextStep& islandContext, PxSolverConstraintDesc* contactDescPtr, PxTGSSolverBodyVel* solverBodyData, Dy::ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mContactDescPtr(contactDescPtr), mSolverBodyData(solverBodyData), mThreadContext(threadContext), mContext(context) { } virtual const char* getName() const { return "PartitionTask"; } virtual void runInternal() { const ArticulationSolverDesc* artics = mThreadContext.getArticulations().begin(); PxU32 totalDescCount = mThreadContext.contactDescArraySize; mThreadContext.mConstraintsPerPartition.forceSize_Unsafe(0); mThreadContext.mConstraintsPerPartition.resize(1); mThreadContext.mConstraintsPerPartition[0] = 0; ConstraintPartitionArgs args; args.mBodies = reinterpret_cast<PxU8*>(mSolverBodyData); args.mStride = sizeof(PxTGSSolverBodyVel); args.mArticulationPtrs = artics; args.mContactConstraintDescriptors = mContactDescPtr; args.mNumArticulationPtrs = mThreadContext.getArticulations().size(); args.mNumBodies = mIslandContext.mCounts.bodies; args.mNumContactConstraintDescriptors = totalDescCount; args.mOrderedContactConstraintDescriptors = mIslandContext.mObjects.orderedConstraintDescs; args.mOverflowConstraintDescriptors = mIslandContext.mObjects.tempConstraintDescs; args.mNumDifferentBodyConstraints = args.mNumSelfConstraints = args.mNumStaticConstraints = 0; args.mConstraintsPerPartition = &mThreadContext.mConstraintsPerPartition; args.mNumOverflowConstraints = 0; //args.mBitField = &mThreadContext.mPartitionNormalizationBitmap; // PT: removed, unused args.mEnhancedDeterminism = false; args.mForceStaticConstraintsToSolver = false; args.mMaxPartitions = 64; mThreadContext.mMaxPartitions = partitionContactConstraints(args); mThreadContext.mNumDifferentBodyConstraints = args.mNumDifferentBodyConstraints; mThreadContext.mNumSelfConstraints = args.mNumSelfConstraints; mThreadContext.mNumStaticConstraints = args.mNumStaticConstraints; mThreadContext.mHasOverflowPartitions = args.mNumOverflowConstraints != 0; { PxU32 descCount = mThreadContext.mNumDifferentBodyConstraints; PxU32 selfConstraintDescCount = mThreadContext.contactDescArraySize - (mThreadContext.mNumDifferentBodyConstraints + mThreadContext.mNumStaticConstraints); PxArray<PxU32>& accumulatedConstraintsPerPartition = mThreadContext.mConstraintsPerPartition; PxU32 numHeaders = 0; PxU32 currentPartition = 0; PxU32 maxJ = descCount == 0 ? 0 : accumulatedConstraintsPerPartition[0]; const PxU32 maxBatchPartition = 0xFFFFFFFF; const PxU32 maxBatchSize2 = args.mEnhancedDeterminism ? 1u : 4u; PxConstraintBatchHeader* batchHeaders = mIslandContext.mObjects.constraintBatchHeaders; PxSolverConstraintDesc* orderedConstraints = mIslandContext.mObjects.orderedConstraintDescs; PxU32 headersPerPartition = 0; //KS - if we have overflowed the partition limit, overflow constraints are pushed //into 0th partition. If that's the case, we need to disallow batching of constraints //in 0th partition. PxU32 maxBatchSize = args.mNumOverflowConstraints == 0 ? maxBatchSize2 : 1; for (PxU32 a = 0; a < descCount;) { PxU32 loopMax = PxMin(maxJ - a, maxBatchSize); PxU16 j = 0; if (loopMax > 0) { PxConstraintBatchHeader& header = batchHeaders[numHeaders++]; j = 1; PxSolverConstraintDesc& desc = orderedConstraints[a]; if (!isArticulationConstraint(desc) && (desc.constraintLengthOver16 == DY_SC_TYPE_RB_CONTACT || desc.constraintLengthOver16 == DY_SC_TYPE_RB_1D) && currentPartition < maxBatchPartition) { for (; j < loopMax && desc.constraintLengthOver16 == orderedConstraints[a + j].constraintLengthOver16 && !isArticulationConstraint(orderedConstraints[a + j]); ++j); } header.startIndex = a; header.stride = j; header.constraintType = desc.constraintLengthOver16; headersPerPartition++; } if (maxJ == (a + j) && maxJ != descCount) { //Go to next partition! accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition; headersPerPartition = 0; currentPartition++; maxJ = accumulatedConstraintsPerPartition[currentPartition]; maxBatchSize = maxBatchSize2; } a += j; } if (descCount) accumulatedConstraintsPerPartition[currentPartition] = headersPerPartition; accumulatedConstraintsPerPartition.forceSize_Unsafe(mThreadContext.mMaxPartitions); PxU32 numDifferentBodyBatchHeaders = numHeaders; for (PxU32 a = 0; a < selfConstraintDescCount; ++a) { PxConstraintBatchHeader& header = batchHeaders[numHeaders++]; header.startIndex = a + descCount; header.stride = 1; header.constraintType = DY_SC_TYPE_EXT_1D; } PxU32 numSelfConstraintBatchHeaders = numHeaders - numDifferentBodyBatchHeaders; mThreadContext.numDifferentBodyBatchHeaders = numDifferentBodyBatchHeaders; mThreadContext.numSelfConstraintBatchHeaders = numSelfConstraintBatchHeaders; mThreadContext.numContactConstraintBatches = numHeaders; } } }; class ParallelSolveTask : public Cm::Task { IslandContextStep& mIslandContext; const SolverIslandObjectsStep& mObjects; const PxsIslandIndices& mCounts; ThreadContext& mThreadContext; DynamicsTGSContext& mContext; PX_NOCOPY(ParallelSolveTask) public: ParallelSolveTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mObjects(objects), mCounts(counts), mThreadContext(threadContext), mContext(context) { } virtual const char* getName() const { return "ParallelSolveTask"; } virtual void runInternal() { mContext.iterativeSolveIslandParallel(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt, mIslandContext.mPosIters, mIslandContext.mVelIters, &mIslandContext.mSharedSolverIndex, &mIslandContext.mSharedRigidBodyIndex, &mIslandContext.mSharedArticulationIndex, &mIslandContext.mSolvedCount, &mIslandContext.mRigidBodyIntegratedCount, &mIslandContext.mArticulationIntegratedCount, 4, 128, PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient); } }; class SolveIslandTask : public Cm::Task { IslandContextStep& mIslandContext; const SolverIslandObjectsStep& mObjects; const PxsIslandIndices& mCounts; ThreadContext& mThreadContext; DynamicsTGSContext& mContext; PX_NOCOPY(SolveIslandTask) public: SolveIslandTask(IslandContextStep& islandContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mIslandContext(islandContext), mObjects(objects), mCounts(counts), mThreadContext(threadContext), mContext(context) { } virtual const char* getName() const { return "SolveIslandTask"; } virtual void runInternal() { PxU32 j = 0, i = 0; PxU32 numBatches = 0; PxU32 currIndex = 0; PxU32 totalCount = 0; PxSolverConstraintDesc* contactDescBegin = mObjects.orderedConstraintDescs; PxSolverConstraintDesc* contactDescPtr = contactDescBegin; PxConstraintBatchHeader* headers = mObjects.constraintBatchHeaders; PxU32 totalPartitions = 0; for (PxU32 a = 0; a < mThreadContext.mConstraintsPerPartition.size(); ++a) { PxU32 endIndex = currIndex + mThreadContext.mConstraintsPerPartition[a]; PxU32 numBatchesInPartition = 0; for (PxU32 b = currIndex; b < endIndex; ++b) { PxConstraintBatchHeader& _header = headers[b]; PxU16 stride = _header.stride, newStride = _header.stride; PxU32 startIndex = j; for (PxU16 c = 0; c < stride; ++c) { if (getConstraintLength(contactDescBegin[i]) == 0) { newStride--; i++; } else { if (i != j) contactDescBegin[j] = contactDescBegin[i]; i++; j++; contactDescPtr++; } } if (newStride != 0) { headers[numBatches].startIndex = startIndex; headers[numBatches].stride = newStride; PxU8 type = *contactDescBegin[startIndex].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 < newStride; ++c) { if (*contactDescBegin[startIndex + c].constraint == DY_SC_TYPE_RB_CONTACT) { type = DY_SC_TYPE_RB_CONTACT; } } } headers[numBatches].constraintType = type; numBatches++; numBatchesInPartition++; } } currIndex += mThreadContext.mConstraintsPerPartition[a]; mThreadContext.mConstraintsPerPartition[totalPartitions] = numBatchesInPartition; if (numBatchesInPartition) totalPartitions++; else if (a == 0) mThreadContext.mHasOverflowPartitions = false; //If our first partition is now empty, we have no overflows so clear the overflow flag totalCount += numBatchesInPartition; } currIndex = totalCount; processOverflowConstraints(reinterpret_cast<PxU8*>(mContext.mSolverBodyVelPool.begin() + mObjects.solverBodyOffset+1), sizeof(PxTGSSolverBodyVel), mCounts.bodies, mThreadContext.getArticulations().begin(), mThreadContext.getArticulations().size(), contactDescBegin, mThreadContext.mHasOverflowPartitions ? mThreadContext.mConstraintsPerPartition[0] : 0); //Decision whether to spawn multi-threaded solver or single-threaded solver... mThreadContext.mConstraintsPerPartition.forceSize_Unsafe(totalPartitions); mThreadContext.numContactConstraintBatches = totalCount; PxU32 maxLinks = 0; for (PxU32 a = 0; a < mCounts.articulations; ++a) { ArticulationSolverDesc& desc = mThreadContext.getArticulations()[a]; maxLinks = PxMax(maxLinks, PxU32(desc.linkCount)); } mThreadContext.mZVector.forceSize_Unsafe(0); mThreadContext.mZVector.reserve(maxLinks); mThreadContext.mZVector.forceSize_Unsafe(maxLinks); mThreadContext.mDeltaV.forceSize_Unsafe(0); mThreadContext.mDeltaV.reserve(maxLinks); mThreadContext.mDeltaV.forceSize_Unsafe(maxLinks); SolverContext cache; cache.Z = mThreadContext.mZVector.begin(); cache.deltaV = mThreadContext.mDeltaV.begin(); if (mThreadContext.mConstraintsPerPartition.size()) { const PxU32 threadCount = this->getTaskManager()->getCpuDispatcher()->getWorkerCount(); PxU32 nbHeadersPerPartition; if (mThreadContext.mHasOverflowPartitions) { // jcarius: mitigating potential divide-by-zero problem. It's unclear whether size originally includes // the overflow partition or not. const PxU32 size = mThreadContext.mConstraintsPerPartition.size(); const PxU32 nbPartitionsMinusOverflow = (size > 1) ? (size - 1) : 1; PxU32 nbConstraintsMinusOverflow = currIndex - mThreadContext.mConstraintsPerPartition[0]; nbHeadersPerPartition = ((nbConstraintsMinusOverflow + nbPartitionsMinusOverflow - 1) / nbPartitionsMinusOverflow); } else nbHeadersPerPartition = ((currIndex + mThreadContext.mConstraintsPerPartition.size() - 1) / mThreadContext.mConstraintsPerPartition.size()); const PxU32 NbBatchesPerThread = 8; //const PxU32 NbBatchesPerThread = 4; const PxU32 nbIdealThreads = (nbHeadersPerPartition + NbBatchesPerThread-1) / NbBatchesPerThread; if (threadCount < 2 || nbIdealThreads < 2) mContext.iterativeSolveIsland(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt, mIslandContext.mInvStepDt, mIslandContext.mPosIters, mIslandContext.mVelIters, cache, PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient); else { mIslandContext.mSharedSolverIndex = 0; mIslandContext.mSolvedCount = 0; mIslandContext.mSharedRigidBodyIndex = 0; mIslandContext.mRigidBodyIntegratedCount = 0; mIslandContext.mSharedArticulationIndex = 0; mIslandContext.mArticulationIntegratedCount = 0; PxU32 nbThreads = PxMin(threadCount, nbIdealThreads); ParallelSolveTask* tasks = reinterpret_cast<ParallelSolveTask*>(mContext.getTaskPool().allocate(sizeof(ParallelSolveTask)*nbThreads)); for (PxU32 a = 0; a < nbThreads; ++a) { PX_PLACEMENT_NEW(&tasks[a], ParallelSolveTask)(mIslandContext, mObjects, mCounts, mThreadContext, mContext); tasks[a].setContinuation(mCont); tasks[a].removeReference(); } } } else { mContext.iterativeSolveIsland(mObjects, mCounts, mThreadContext, mIslandContext.mStepDt, mIslandContext.mInvStepDt, mIslandContext.mPosIters, mIslandContext.mVelIters, cache, PxMin(0.5f, mIslandContext.mBiasCoefficient), mIslandContext.mBiasCoefficient); } } }; class EndIslandTask : public Cm::Task { ThreadContext& mThreadContext; DynamicsTGSContext& mContext; PX_NOCOPY(EndIslandTask) public: EndIslandTask(ThreadContext& threadContext, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mThreadContext(threadContext), mContext(context) { } virtual const char* getName() const { return "EndIslandTask"; } virtual void runInternal() { mContext.endIsland(mThreadContext); } }; class FinishSolveIslandTask : public Cm::Task { ThreadContext& mThreadContext; const SolverIslandObjectsStep& mObjects; const PxsIslandIndices& mCounts; IG::SimpleIslandManager& mIslandManager; DynamicsTGSContext& mContext; PX_NOCOPY(FinishSolveIslandTask) public: FinishSolveIslandTask(ThreadContext& threadContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mThreadContext(threadContext), mObjects(objects), mCounts(counts), mIslandManager(islandManager), mContext(context) { } virtual const char* getName() const { return "FinishSolveIslandTask"; } virtual void runInternal() { mContext.finishSolveIsland(mThreadContext, mObjects, mCounts, mIslandManager, mCont); } }; void DynamicsTGSContext::iterativeSolveIsland(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, ThreadContext& mThreadContext, PxReal stepDt, PxReal invStepDt, PxU32 posIters, PxU32 velIters, SolverContext& cache, PxReal ratio, PxReal biasCoefficient) { PX_PROFILE_ZONE("Dynamics:solveIsland", mContextID); PxReal elapsedTime = 0.0f; const PxReal recipStepDt = 1.0f/stepDt; const PxU32 bodyOffset = objects.solverBodyOffset; if (mThreadContext.numContactConstraintBatches == 0) { for (PxU32 i = 0; i < counts.articulations; ++i) { elapsedTime = 0.0f; ArticulationSolverDesc& d = mThreadContext.getArticulations()[i]; for (PxU32 a = 0; a < posIters; a++) { d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient); ArticulationPImpl::updateDeltaMotion(d, stepDt, mThreadContext.mDeltaV.begin(), mInvDt); elapsedTime += stepDt; } ArticulationPImpl::saveVelocityTGS(d.articulation, mInvDt); d.articulation->concludeInternalConstraints(true); for (PxU32 a = 0; a < velIters; ++a) { d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient); } d.articulation->writebackInternalConstraints(true); } integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset, mSolverBodyDataPool2.begin() + bodyOffset, mDt, mInvDt, false, ratio); return; } for (PxU32 a = 1; a < posIters; a++) { solveConstraintsIteration(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches, invStepDt, mSolverBodyTxInertiaPool.begin(), elapsedTime, -PX_MAX_F32, cache); integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset, mSolverBodyDataPool2.begin() + bodyOffset, stepDt, mInvDt, false, ratio); for (PxU32 i = 0; i < counts.articulations; ++i) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[i]; d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient); } stepArticulations(mThreadContext, counts, stepDt, mInvDt); elapsedTime += stepDt; } solveConcludeConstraintsIteration<false>(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches, mSolverBodyTxInertiaPool.begin(), elapsedTime, cache, 0); for (PxU32 i = 0; i < counts.articulations; ++i) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[i]; d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient); d.articulation->concludeInternalConstraints(true); } elapsedTime += stepDt; const PxReal invDt = mInvDt; integrateBodies(objects, counts.bodies, mSolverBodyVelPool.begin() + bodyOffset, mSolverBodyTxInertiaPool.begin() + bodyOffset, mSolverBodyDataPool2.begin() + bodyOffset, stepDt, mInvDt, false, ratio); stepArticulations(mThreadContext, counts, stepDt, mInvDt); for(PxU32 a = 0; a < counts.articulations; ++a) { Dy::ArticulationSolverDesc& desc = mThreadContext.getArticulations()[a]; //ArticulationPImpl::updateDeltaMotion(desc, stepDt, mThreadContext.mDeltaV.begin()); ArticulationPImpl::saveVelocityTGS(desc.articulation, invDt); } for (PxU32 a = 0; a < velIters; ++a) { solveConstraintsIteration(objects.orderedConstraintDescs, objects.constraintBatchHeaders, mThreadContext.numContactConstraintBatches, invStepDt, mSolverBodyTxInertiaPool.begin(), elapsedTime, /*-PX_MAX_F32*/0.f, cache); for (PxU32 i = 0; i < counts.articulations; ++i) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[i]; d.articulation->solveInternalConstraints(stepDt, recipStepDt, mThreadContext.mZVector.begin(), mThreadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient); } } writebackConstraintsIteration(objects.constraintBatchHeaders, objects.orderedConstraintDescs, mThreadContext.numContactConstraintBatches); for (PxU32 i = 0; i < counts.articulations; ++i) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[i]; d.articulation->writebackInternalConstraints(true); } } void DynamicsTGSContext::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) { PX_PROFILE_ZONE("Dynamics:solveIslandParallel", mContextID); Dy::ThreadContext& threadContext = *getThreadContext(); PxU32 startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize; PxU32 nbSolveRemaining = solverUnrollSize; PxU32 startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize; PxU32 nbIntegrateRemaining = integrationUnrollSize; //For now, just do articulations 1 at a time. Might need to tweak this later depending on performance PxU32 startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1; PxU32 targetSolverProgressCount = 0, targetIntegrationProgressCount = 0, targetArticulationProgressCount = 0; const PxU32 nbSolverBatches = mThreadContext.numContactConstraintBatches; const PxU32 nbBodies = counts.bodies;// + mKinematicCount; const PxU32 nbArticulations = counts.articulations; PxSolverConstraintDesc* contactDescs = objects.orderedConstraintDescs; PxConstraintBatchHeader* batchHeaders = objects.constraintBatchHeaders; PxTGSSolverBodyVel* solverVels = mSolverBodyVelPool.begin(); PxTGSSolverBodyTxInertia* solverTxInertias = mSolverBodyTxInertiaPool.begin(); const PxTGSSolverBodyData*const solverBodyData = mSolverBodyDataPool2.begin(); PxU32* constraintsPerPartitions = mThreadContext.mConstraintsPerPartition.begin(); const PxU32 nbPartitions = mThreadContext.mConstraintsPerPartition.size(); const PxU32 bodyOffset = objects.solverBodyOffset; threadContext.mZVector.reserve(mThreadContext.mZVector.size()); threadContext.mDeltaV.reserve(mThreadContext.mZVector.size()); SolverContext cache; cache.Z = threadContext.mZVector.begin(); cache.deltaV = threadContext.mDeltaV.begin(); PxReal elapsedTime = 0.0f; PxReal invStepDt = 1.0f/ stepDt; const bool overflow = mThreadContext.mHasOverflowPartitions; PxU32 iterCount = 0; const PxU32 maxDynamic0 = contactDescs[0].tgsBodyA->maxDynamicPartition; PX_UNUSED(maxDynamic0); for (PxU32 a = 1; a < posIters; ++a, targetIntegrationProgressCount += nbBodies, targetArticulationProgressCount += nbArticulations) { WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount)); WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount)); PxU32 offset = 0; for (PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); //Find the startIdx in the partition to process PxU32 startIdx = startSolveIdx - targetSolverProgressCount; const PxU32 nbBatches = constraintsPerPartitions[b]; PxU32 nbSolved = 0; while (startIdx < nbBatches) { PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining); PX_ASSERT(maxDynamic0 == contactDescs[0].tgsBodyA->maxDynamicPartition); if (b == 0 && overflow) parallelSolveConstraints<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, -PX_MAX_F32, cache, iterCount); else parallelSolveConstraints<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, -PX_MAX_F32, cache, iterCount); PX_ASSERT(maxDynamic0 == contactDescs[0].tgsBodyA->maxDynamicPartition); nbSolveRemaining -= nbToSolve; startSolveIdx += nbToSolve; startIdx += nbToSolve; nbSolved += nbToSolve; if (nbSolveRemaining == 0) { startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize; nbSolveRemaining = solverUnrollSize; startIdx = startSolveIdx - targetSolverProgressCount; } } if (nbSolved) PxAtomicAdd(solverProgressCount, PxI32(nbSolved)); targetSolverProgressCount += nbBatches; offset += nbBatches; } iterCount++; WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); PxU32 integStartIdx = startIntegrateIdx - targetIntegrationProgressCount; PxU32 nbIntegrated = 0; while (integStartIdx < nbBodies) { PxU32 nbToIntegrate = PxMin(nbBodies - integStartIdx, nbIntegrateRemaining); parallelIntegrateBodies(solverVels + integStartIdx + bodyOffset, solverTxInertias + integStartIdx + bodyOffset, solverBodyData + integStartIdx + bodyOffset, nbToIntegrate, stepDt, iterCount, mInvDt, false, ratio); nbIntegrateRemaining -= nbToIntegrate; startIntegrateIdx += nbToIntegrate; integStartIdx += nbToIntegrate; nbIntegrated += nbToIntegrate; if (nbIntegrateRemaining == 0) { startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize; nbIntegrateRemaining = integrationUnrollSize; integStartIdx = startIntegrateIdx - targetIntegrationProgressCount; } } if (nbIntegrated) PxAtomicAdd(integrationProgressCount, PxI32(nbIntegrated)); PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; PxU32 nbArticsProcessed = 0; while (artIcStartIdx < nbArticulations) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx]; d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient); ArticulationPImpl::updateDeltaMotion(d, stepDt, cache.deltaV, mInvDt); nbArticsProcessed++; startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1; artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; } if (nbArticsProcessed) PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed)); elapsedTime += stepDt; } { WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount)); WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount)); PxU32 offset = 0; for (PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); //Find the startIdx in the partition to process PxU32 startIdx = startSolveIdx - targetSolverProgressCount; const PxU32 nbBatches = constraintsPerPartitions[b]; PxU32 nbSolved = 0; while (startIdx < nbBatches) { PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining); if (b == 0 && overflow) solveConcludeConstraintsIteration<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, cache, iterCount); else solveConcludeConstraintsIteration<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, cache, iterCount); nbSolveRemaining -= nbToSolve; startSolveIdx += nbToSolve; startIdx += nbToSolve; nbSolved += nbToSolve; if (nbSolveRemaining == 0) { startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize; nbSolveRemaining = solverUnrollSize; startIdx = startSolveIdx - targetSolverProgressCount; } } if (nbSolved) PxAtomicAdd(solverProgressCount, PxI32(nbSolved)); targetSolverProgressCount += nbBatches; offset += nbBatches; } iterCount++; WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); const PxReal invDt = mInvDt; //const PxReal invDtPt25 = mInvDt * 0.25f; PxU32 integStartIdx = startIntegrateIdx - targetIntegrationProgressCount; PxU32 nbIntegrated = 0; while (integStartIdx < nbBodies) { PxU32 nbToIntegrate = PxMin(nbBodies - integStartIdx, nbIntegrateRemaining); parallelIntegrateBodies(solverVels + integStartIdx + bodyOffset, solverTxInertias + integStartIdx + bodyOffset, solverBodyData + integStartIdx + bodyOffset, nbToIntegrate, stepDt, iterCount, mInvDt, false, ratio); nbIntegrateRemaining -= nbToIntegrate; startIntegrateIdx += nbToIntegrate; integStartIdx += nbToIntegrate; nbIntegrated += nbToIntegrate; if (nbIntegrateRemaining == 0) { startIntegrateIdx = PxU32(PxAtomicAdd(integrationCounts, PxI32(integrationUnrollSize))) - integrationUnrollSize; nbIntegrateRemaining = integrationUnrollSize; integStartIdx = startIntegrateIdx - targetIntegrationProgressCount; } } if (nbIntegrated) PxAtomicAdd(integrationProgressCount, PxI32(nbIntegrated)); PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; PxU32 nbArticsProcessed = 0; while (artIcStartIdx < nbArticulations) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx]; d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), false, true, elapsedTime, biasCoefficient); d.articulation->concludeInternalConstraints(true); ArticulationPImpl::updateDeltaMotion(d, stepDt, cache.deltaV, mInvDt); ArticulationPImpl::saveVelocityTGS(d.articulation, invDt); nbArticsProcessed++; startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1; artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; } if (nbArticsProcessed) PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed)); elapsedTime += stepDt; targetIntegrationProgressCount += nbBodies; targetArticulationProgressCount += nbArticulations; putThreadContext(&threadContext); } //Write back constraints... WAIT_FOR_PROGRESS(integrationProgressCount, PxI32(targetIntegrationProgressCount)); WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount)); for (PxU32 a = 0; a < velIters; ++a) { WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); const bool lastIter = (velIters - a) == 1; PxU32 offset = 0; for (PxU32 b = 0; b < nbPartitions; ++b) { WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); //Find the startIdx in the partition to process PxU32 startIdx = startSolveIdx - targetSolverProgressCount; const PxU32 nbBatches = constraintsPerPartitions[b]; PxU32 nbSolved = 0; while (startIdx < nbBatches) { PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining); if (b == 0 && overflow) parallelSolveConstraints<true>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, 0.f/*-PX_MAX_F32*/, cache, iterCount); else parallelSolveConstraints<false>(contactDescs, batchHeaders + startIdx + offset, nbToSolve, solverTxInertias, elapsedTime, 0.f/*-PX_MAX_F32*/, cache, iterCount); nbSolveRemaining -= nbToSolve; startSolveIdx += nbToSolve; startIdx += nbToSolve; nbSolved += nbToSolve; if (nbSolveRemaining == 0) { startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize; nbSolveRemaining = solverUnrollSize; startIdx = startSolveIdx - targetSolverProgressCount; } } if (nbSolved) PxAtomicAdd(solverProgressCount, PxI32(nbSolved)); targetSolverProgressCount += nbBatches; offset += nbBatches; } WAIT_FOR_PROGRESS(solverProgressCount, PxI32(targetSolverProgressCount)); PxU32 artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; PxU32 nbArticsProcessed = 0; while (artIcStartIdx < nbArticulations) { ArticulationSolverDesc& d = mThreadContext.getArticulations()[artIcStartIdx]; d.articulation->solveInternalConstraints(stepDt, invStepDt, threadContext.mZVector.begin(), threadContext.mDeltaV.begin(), true, true, elapsedTime, biasCoefficient); if (lastIter) d.articulation->writebackInternalConstraints(true); nbArticsProcessed++; startArticulationIdx = PxU32(PxAtomicAdd(articulationIntegrationCounts, PxI32(1))) - 1; artIcStartIdx = startArticulationIdx - targetArticulationProgressCount; } if (nbArticsProcessed) PxAtomicAdd(articulationProgressCount, PxI32(nbArticsProcessed)); targetArticulationProgressCount += nbArticulations; iterCount++; WAIT_FOR_PROGRESS(articulationProgressCount, PxI32(targetArticulationProgressCount)); } { { //Find the startIdx in the partition to process PxU32 startIdx = startSolveIdx - targetSolverProgressCount; const PxU32 nbBatches = nbSolverBatches; PxU32 nbSolved = 0; while (startIdx < nbBatches) { PxU32 nbToSolve = PxMin(nbBatches - startIdx, nbSolveRemaining); parallelWritebackConstraintsIteration(contactDescs, batchHeaders + startIdx, nbToSolve); nbSolveRemaining -= nbToSolve; startSolveIdx += nbToSolve; startIdx += nbToSolve; nbSolved += nbToSolve; if (nbSolveRemaining == 0) { startSolveIdx = PxU32(PxAtomicAdd(solverCounts, PxI32(solverUnrollSize))) - solverUnrollSize; nbSolveRemaining = solverUnrollSize; startIdx = startSolveIdx - targetSolverProgressCount; } } if (nbSolved) PxAtomicAdd(solverProgressCount, PxI32(nbSolved)); targetSolverProgressCount += nbBatches; } } } class CopyBackTask : public Cm::Task { const SolverIslandObjectsStep& mObjects; PxTGSSolverBodyVel* mVels; PxTGSSolverBodyTxInertia* mTxInertias; PxTGSSolverBodyData* mSolverBodyDatas; const PxReal mInvDt; IG::IslandSim& mIslandSim; const PxU32 mStartIdx; const PxU32 mEndIdx; DynamicsTGSContext& mContext; PX_NOCOPY(CopyBackTask) public: CopyBackTask(const SolverIslandObjectsStep& objects, PxTGSSolverBodyVel* vels, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyDatas, PxReal invDt, IG::IslandSim& islandSim, PxU32 startIdx, PxU32 endIdx, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mObjects(objects), mVels(vels), mTxInertias(txInertias), mSolverBodyDatas(solverBodyDatas), mInvDt(invDt), mIslandSim(islandSim), mStartIdx(startIdx), mEndIdx(endIdx), mContext(context) { } virtual const char* getName() const { return "CopyBackTask"; } virtual void runInternal() { mContext.copyBackBodies(mObjects, mVels, mTxInertias, mSolverBodyDatas, mInvDt, mIslandSim, mStartIdx, mEndIdx); } }; class UpdateArticTask : public Cm::Task { Dy::ThreadContext& mThreadContext; PxU32 mStartIdx; PxU32 mEndIdx; PxReal mDt; DynamicsTGSContext& mContext; PX_NOCOPY(UpdateArticTask) public: UpdateArticTask(Dy::ThreadContext& threadContext, PxU32 startIdx, PxU32 endIdx, PxReal dt, DynamicsTGSContext& context) : Cm::Task(context.getContextId()), mThreadContext(threadContext), mStartIdx(startIdx), mEndIdx(endIdx), mDt(dt), mContext(context) { } virtual const char* getName() const { return "UpdateArticTask"; } virtual void runInternal() { mContext.updateArticulations(mThreadContext, mStartIdx, mEndIdx, mDt); } }; void DynamicsTGSContext::finishSolveIsland(ThreadContext& mThreadContext, const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, IG::SimpleIslandManager& islandManager, PxBaseTask* continuation) { mThreadContext.mConstraintBlockManager.reset(); mThreadContext.mConstraintBlockStream.reset(); const PxU32 NbBodiesPerTask = 512; for (PxU32 a = 0; a < counts.bodies; a += NbBodiesPerTask) { CopyBackTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(CopyBackTask)), CopyBackTask) (objects, mSolverBodyVelPool.begin() + objects.solverBodyOffset, mSolverBodyTxInertiaPool.begin() + objects.solverBodyOffset, mSolverBodyDataPool2.begin() + objects.solverBodyOffset, mInvDt, islandManager.getAccurateIslandSim(), a, PxMin(a + NbBodiesPerTask, counts.bodies),*this); task->setContinuation(continuation); task->removeReference(); } const PxU32 NbArticsPerTask = 64; for (PxU32 a = 0; a < counts.articulations; a += NbArticsPerTask) { UpdateArticTask* task = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(UpdateArticTask)), UpdateArticTask) (mThreadContext, a, PxMin(counts.articulations, a+NbArticsPerTask), mDt, *this); task->setContinuation(continuation); task->removeReference(); } } void DynamicsTGSContext::endIsland(ThreadContext& mThreadContext) { putThreadContext(&mThreadContext); } void DynamicsTGSContext::solveIsland(const SolverIslandObjectsStep& objects, const PxsIslandIndices& counts, PxU32 solverBodyOffset, IG::SimpleIslandManager& islandManager, PxU32* bodyRemapTable, PxsMaterialManager* /*materialManager*/, PxsContactManagerOutputIterator& iterator, PxBaseTask* continuation) { ThreadContext& mThreadContext = *getThreadContext(); IslandContextStep& islandContext = *reinterpret_cast<IslandContextStep*>(mTaskPool.allocate(sizeof(IslandContextStep))); islandContext.mThreadContext = &mThreadContext; islandContext.mCounts = counts; islandContext.mObjects = objects; islandContext.mPosIters = 0; islandContext.mVelIters = 0; islandContext.mObjects.solverBodyOffset = solverBodyOffset; prepareBodiesAndConstraints(islandContext.mObjects, islandManager, islandContext); ////Create task chain... SetupDescsTask* descTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupDescsTask)), SetupDescsTask)(islandContext, islandContext.mObjects, bodyRemapTable, solverBodyOffset, iterator, *this); PreIntegrateTask* intTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(PreIntegrateTask)), PreIntegrateTask)(islandContext.mObjects.bodyCoreArray, islandContext.mObjects.bodies, mSolverBodyVelPool.begin() + solverBodyOffset, mSolverBodyTxInertiaPool.begin() + solverBodyOffset, mSolverBodyDataPool2.begin() + solverBodyOffset, mThreadContext.mNodeIndexArray, islandContext.mCounts.bodies, mGravity, mDt, islandContext.mPosIters, islandContext.mVelIters, *this); SetupArticulationTask* articTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupArticulationTask)), SetupArticulationTask)(islandContext, mGravity, mDt, islandContext.mPosIters, islandContext.mVelIters, *this); SetStepperTask* stepperTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetStepperTask)), SetStepperTask)(islandContext, *this); SetupArticulationInternalConstraintsTask* articConTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupArticulationInternalConstraintsTask)), SetupArticulationInternalConstraintsTask) (islandContext, mDt, mInvDt, *this); PartitionTask* partitionTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(PartitionTask)), PartitionTask) (islandContext, islandContext.mObjects.constraintDescs, mSolverBodyVelPool.begin()+solverBodyOffset+1, mThreadContext, *this); SetupSolverConstraintsTask* constraintTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SetupSolverConstraintsTask)), SetupSolverConstraintsTask) (islandContext, islandContext.mObjects.orderedConstraintDescs, iterator, mThreadContext, mDt, *this); SolveIslandTask* solveTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(SolveIslandTask)), SolveIslandTask)(islandContext, islandContext.mObjects, islandContext.mCounts, mThreadContext, *this); FinishSolveIslandTask* finishTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(FinishSolveIslandTask)), FinishSolveIslandTask)(mThreadContext, islandContext.mObjects, islandContext.mCounts, islandManager, *this); EndIslandTask* endTask = PX_PLACEMENT_NEW(mTaskPool.allocate(sizeof(EndIslandTask)), EndIslandTask)(mThreadContext, *this); endTask->setContinuation(continuation); finishTask->setContinuation(endTask); solveTask->setContinuation(finishTask); constraintTask->setContinuation(solveTask); partitionTask->setContinuation(constraintTask); articConTask->setContinuation(partitionTask); //Stepper triggers both articCon and constraintTask stepperTask->setContinuation(articConTask); stepperTask->setAdditionalContinuation(constraintTask); articTask->setContinuation(stepperTask); intTask->setContinuation(stepperTask); descTask->setContinuation(stepperTask); endTask->removeReference(); finishTask->removeReference(); solveTask->removeReference(); constraintTask->removeReference(); partitionTask->removeReference(); articConTask->removeReference(); stepperTask->removeReference(); articTask->removeReference(); intTask->removeReference(); descTask->removeReference(); } void DynamicsTGSContext::mergeResults() { } } }
119,518
C++
36.025713
257
0.769934
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyThreadContext.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_THREAD_CONTEXT_H #define DY_THREAD_CONTEXT_H #include "foundation/PxTransform.h" #include "geomutils/PxContactBuffer.h" #include "PxvConfig.h" #include "PxvDynamics.h" #include "PxcThreadCoherentCache.h" #include "PxcConstraintBlockStream.h" #include "foundation/PxBitMap.h" #include "DyThresholdTable.h" #include "DyVArticulation.h" #include "DyFrictionPatchStreamPair.h" #include "DySolverConstraintDesc.h" #include "DyCorrelationBuffer.h" #include "foundation/PxAllocator.h" namespace physx { struct PxsIndexedContactManager; namespace Dy { /*! Cache information specific to the software implementation(non common). See PxcgetThreadContext. Not thread-safe, so remember to have one object per thread! TODO! refactor this and rename(it is a general per thread cache). Move transform cache into its own class. */ class ThreadContext : public PxcThreadCoherentCache<ThreadContext, PxcNpMemBlockPool>::EntryBase { PX_NOCOPY(ThreadContext) public: #if PX_ENABLE_SIM_STATS struct ThreadSimStats { void clear() { numActiveConstraints = 0; numActiveDynamicBodies = 0; numActiveKinematicBodies = 0; numAxisSolverConstraints = 0; } PxU32 numActiveConstraints; PxU32 numActiveDynamicBodies; PxU32 numActiveKinematicBodies; PxU32 numAxisSolverConstraints; }; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif //TODO: tune cache size based on number of active objects. ThreadContext(PxcNpMemBlockPool* memBlockPool); void reset(); void resizeArrays(PxU32 frictionConstraintDescCount, PxU32 articulationCount); PX_FORCE_INLINE PxArray<ArticulationSolverDesc>& getArticulations() { return mArticulations; } #if PX_ENABLE_SIM_STATS PX_FORCE_INLINE ThreadSimStats& getSimStats() { return mThreadSimStats; } #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif PxContactBuffer mContactBuffer; // temporary buffer for correlation PX_ALIGN(16, CorrelationBuffer mCorrelationBuffer); FrictionPatchStreamPair mFrictionPatchStreamPair; // patch streams PxsConstraintBlockManager mConstraintBlockManager; // for when this thread context is "lead" on an island PxcConstraintBlockStream mConstraintBlockStream; // constraint block pool // this stuff is just used for reformatting the solver data. Hopefully we should have a more // sane format for this when the dust settles - so it's just temporary. If we keep this around // here we should move these from public to private PxU32 mNumDifferentBodyConstraints; PxU32 mNumDifferentBodyFrictionConstraints; PxU32 mNumSelfConstraints; PxU32 mNumStaticConstraints; PxU32 mNumSelfFrictionConstraints; PxU32 mNumSelfConstraintFrictionBlocks; bool mHasOverflowPartitions; PxArray<PxU32> mConstraintsPerPartition; PxArray<PxU32> mFrictionConstraintsPerPartition; PxArray<PxU32> mPartitionNormalizationBitmap; PxsBodyCore** mBodyCoreArray; PxsRigidBody** mRigidBodyArray; FeatherstoneArticulation** mArticulationArray; Cm::SpatialVector* motionVelocityArray; PxU32* bodyRemapTable; PxU32* mNodeIndexArray; //Constraint info for normal constraint sovler PxSolverConstraintDesc* contactConstraintDescArray; PxU32 contactDescArraySize; PxSolverConstraintDesc* orderedContactConstraints; PxConstraintBatchHeader* contactConstraintBatchHeaders; PxU32 numContactConstraintBatches; //Constraint info for partitioning PxSolverConstraintDesc* tempConstraintDescArray; //Additional constraint info for 1d/2d friction model PxArray<PxSolverConstraintDesc> frictionConstraintDescArray; PxArray<PxConstraintBatchHeader> frictionConstraintBatchHeaders; //Info for tracking compound contact managers (temporary data - could use scratch memory!) PxArray<CompoundContactManager> compoundConstraints; //Used for sorting constraints. Temporary, could use scratch memory PxArray<const PxsIndexedContactManager*> orderedContactList; PxArray<const PxsIndexedContactManager*> tempContactList; PxArray<PxU32> sortIndexArray; PxArray<Cm::SpatialVectorF> mZVector; PxArray<Cm::SpatialVectorF> mDeltaV; PxU32 numDifferentBodyBatchHeaders; PxU32 numSelfConstraintBatchHeaders; PxU32 mOrderedContactDescCount; PxU32 mOrderedFrictionDescCount; PxU32 mConstraintSize; PxU32 mAxisConstraintCount; SelfConstraintBlock* mSelfConstraintBlocks; SelfConstraintBlock* mSelfConstraintFrictionBlocks; PxU32 mMaxPartitions; PxU32 mMaxFrictionPartitions; PxU32 mMaxSolverPositionIterations; PxU32 mMaxSolverVelocityIterations; PxU32 mMaxArticulationLinks; PxSolverConstraintDesc* mContactDescPtr; PxSolverConstraintDesc* mStartContactDescPtr; PxSolverConstraintDesc* mFrictionDescPtr; private: PxArray<ArticulationSolverDesc> mArticulations; #if PX_ENABLE_SIM_STATS ThreadSimStats mThreadSimStats; #else PX_CATCH_UNDEFINED_ENABLE_SIM_STATS #endif public: }; } } #endif
6,651
C
30.526066
107
0.78725
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyContactPrepPF.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DySolverContact.h" #include "DySolverContactPF.h" #include "PxcNpWorkUnit.h" #include "DyThreadContext.h" #include "PxcNpContactPrepShared.h" #include "PxsMaterialManager.h" #include "DyContactPrepShared.h" using namespace physx::Gu; using namespace physx::aos; namespace physx { namespace Dy { bool createFinalizeSolverContactsCoulomb(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, PxFrictionType::Enum frictionType, Cm::SpatialVectorF* Z); static bool setupFinalizeSolverConstraintsCoulomb(Sc::ShapeInteraction* shapeInteraction, const PxContactBuffer& 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, PxU32 frictionPerPointCount, const bool hasForceThresholds, const bool staticBody, PxReal invMassScale0, PxReal invInertiaScale0, PxReal invMassScale1, PxReal invInertiaScale1, PxReal restDist, const PxReal maxCCDSeparation, const PxReal solverOffsetSlopF32) { const FloatV ccdMaxSeparation = FLoad(maxCCDSeparation); const Vec3V solverOffsetSlop = V3Load(solverOffsetSlopF32); PxU8* PX_RESTRICT ptr = workspace; const FloatV zero=FZero(); PxU8 flags = PxU8(hasForceThresholds ? SolverContactHeader::eHAS_FORCE_THRESHOLDS : 0); const FloatV restDistance = FLoad(restDist); const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p); const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p); PxPrefetchLine(c.contactID); PxPrefetchLine(c.contactID, 128); const PxU32 frictionPatchCount = c.frictionPatchCount; const PxU32 pointStride = sizeof(SolverContactPoint); const PxU32 frictionStride = sizeof(SolverContactFriction); const PxU8 pointHeaderType = PxTo8(staticBody ? DY_SC_TYPE_STATIC_CONTACT : DY_SC_TYPE_RB_CONTACT); const PxU8 frictionHeaderType = PxTo8(staticBody ? DY_SC_TYPE_STATIC_FRICTION : DY_SC_TYPE_FRICTION); const Vec3V linVel0 = V3LoadU(data0.linearVelocity); const Vec3V linVel1 = V3LoadU(data1.linearVelocity); const Vec3V angVel0 = V3LoadU(data0.angularVelocity); const Vec3V angVel1 = V3LoadU(data1.angularVelocity); const FloatV invMass0 = FLoad(data0.invMass); const FloatV invMass1 = FLoad(data1.invMass); const FloatV maxPenBias = FMax(FLoad(data0.penBiasClamp), FLoad(data1.penBiasClamp)); // PT: the matrix is symmetric so we can read it as a PxMat33! Gets rid of 25000+ LHS. const PxMat33& invIn0 = reinterpret_cast<const PxMat33&>(data0.sqrtInvInertia); PX_ALIGN(16, const Mat33V invSqrtInertia0) ( V3LoadU(invIn0.column0), V3LoadU(invIn0.column1), V3LoadU(invIn0.column2) ); const PxMat33& invIn1 = reinterpret_cast<const PxMat33&>(data1.sqrtInvInertia); PX_ALIGN(16, const Mat33V invSqrtInertia1) ( V3LoadU(invIn1.column0), V3LoadU(invIn1.column1), V3LoadU(invIn1.column2) ); const FloatV invDt = FLoad(invDtF32); const FloatV dt = FLoad(dtF32); const FloatV p8 = FLoad(0.8f); const FloatV bounceThreshold = FLoad(bounceThresholdF32); const FloatV orthoThreshold = FLoad(0.70710678f); const FloatV eps = FLoad(0.00001f); const FloatV invDtp8 = FMul(invDt, p8); const FloatV d0 = FLoad(invMassScale0); const FloatV d1 = FLoad(invMassScale1); const FloatV nDom1fV = FNeg(d1); const FloatV angD0 = FLoad(invInertiaScale0); const FloatV angD1 = FLoad(invInertiaScale1); const FloatV invMass0_dom0fV = FMul(d0, invMass0); const FloatV invMass1_dom1fV = FMul(nDom1fV, invMass1); for(PxU32 i=0;i< frictionPatchCount;i++) { const PxU32 contactCount = c.frictionPatchContactCounts[i]; if(contactCount == 0) continue; const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start; const Vec3V normal = aos::V3LoadA(contactBase0->normal); const FloatV normalLenSq = V3LengthSq(normal); const VecCrossV norCross = V3PrepareCross(normal); const FloatV restitution = FLoad(contactBase0->restitution); const FloatV damping = FLoad(contactBase0->damping); const FloatV norVel = V3SumElems(V3NegMulSub(normal, linVel1, V3Mul(normal, linVel0))); /*const FloatV norVel0 = V3Dot(normal, linVel0); const FloatV norVel1 = V3Dot(normal, linVel1); const FloatV norVel = FSub(norVel0, norVel1);*/ const FloatV invMassNorLenSq0 = FMul(invMass0_dom0fV, normalLenSq); const FloatV invMassNorLenSq1 = FMul(invMass1_dom1fV, normalLenSq); SolverContactCoulombHeader* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader*>(ptr); ptr += sizeof(SolverContactCoulombHeader); PxPrefetchLine(ptr, 128); PxPrefetchLine(ptr, 256); PxPrefetchLine(ptr, 384); header->numNormalConstr = PxU8(contactCount); header->type = pointHeaderType; //header->setRestitution(n.restitution); //header->setRestitution(contactBase0->restitution); header->setDominance0(invMass0_dom0fV); header->setDominance1(FNeg(invMass1_dom1fV)); FStore(angD0, &header->angDom0); FStore(angD1, &header->angDom1); header->setNormal(normal); header->flags = flags; header->shapeInteraction = shapeInteraction; 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.contacts + c.contactPatches[patch].start; PxU8* p = ptr; for(PxU32 j=0;j<count;j++) { 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; } } //construct all the frictions PxU8* PX_RESTRICT ptr2 = workspace; bool hasFriction = false; for(PxU32 i=0;i< frictionPatchCount;i++) { const PxU32 contactCount = c.frictionPatchContactCounts[i]; if(contactCount == 0) continue; const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start; SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(ptr2); header->frictionOffset = PxU16(ptr - ptr2);// + sizeof(SolverFrictionHeader); ptr2 += sizeof(SolverContactCoulombHeader) + header->numNormalConstr * pointStride; const PxReal staticFriction = contactBase0->staticFriction; const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION); const bool haveFriction = (disableStrongFriction == 0); SolverFrictionHeader* frictionHeader = reinterpret_cast<SolverFrictionHeader*>(ptr); frictionHeader->numNormalConstr = PxTo8(c.frictionPatchContactCounts[i]); frictionHeader->numFrictionConstr = PxTo8(haveFriction ? c.frictionPatchContactCounts[i] * frictionPerPointCount : 0); ptr += sizeof(SolverFrictionHeader); PxF32* appliedForceBuffer = reinterpret_cast<PxF32*>(ptr); ptr += frictionHeader->getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]); PxMemZero(appliedForceBuffer, sizeof(PxF32)*contactCount*frictionPerPointCount); PxPrefetchLine(ptr, 128); PxPrefetchLine(ptr, 256); PxPrefetchLine(ptr, 384); const Vec3V normal = V3LoadU(buffer.contacts[c.contactPatches[c.correlationListHeads[i]].start].normal); const FloatV normalX = V3GetX(normal); const FloatV normalY = V3GetY(normal); const FloatV normalZ = V3GetZ(normal); const Vec3V t0Fallback1 = V3Merge(zero, FNeg(normalZ), normalY); const Vec3V t0Fallback2 = V3Merge(FNeg(normalY), normalX, zero); const BoolV con = FIsGrtr(orthoThreshold, FAbs(normalX)); const Vec3V tFallback1 = V3Sel(con, t0Fallback1, t0Fallback2); const Vec3V linVrel = V3Sub(linVel0, linVel1); const Vec3V t0_ = V3Sub(linVrel, V3Scale(normal, V3Dot(normal, linVrel))); const FloatV sqDist = V3Dot(t0_,t0_); const BoolV con1 = FIsGrtr(sqDist, eps); const Vec3V tDir0 = V3Normalize(V3Sel(con1, t0_, tFallback1)); const Vec3V tDir1 = V3Cross(tDir0, normal); Vec3V tFallback = tDir0; Vec3V tFallbackAlt = tDir1; if(haveFriction) { //frictionHeader->setStaticFriction(n.staticFriction); frictionHeader->setStaticFriction(staticFriction); FStore(invMass0_dom0fV, &frictionHeader->invMass0D0); FStore(FNeg(invMass1_dom1fV), &frictionHeader->invMass1D1); FStore(angD0, &frictionHeader->angDom0); FStore(angD1, &frictionHeader->angDom1); frictionHeader->type = frictionHeaderType; for(PxU32 patch=c.correlationListHeads[i]; patch!=CorrelationBuffer::LIST_END; patch = c.contactPatches[patch].next) { const PxU32 count = c.contactPatches[patch].count; const PxU32 start = c.contactPatches[patch].start; const PxContactPoint* contactBase = buffer.contacts + start; PxU8* p = ptr; for(PxU32 j =0; j < count; j++) { hasFriction = true; const PxContactPoint& contact = contactBase[j]; const Vec3V point = V3LoadU(contact.point); Vec3V ra = V3Sub(point, bodyFrame0p); Vec3V rb = V3Sub(point, bodyFrame1p); ra = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(ra)), V3Zero(), ra); rb = V3Sel(V3IsGrtr(solverOffsetSlop, V3Abs(rb)), V3Zero(), rb); const Vec3V targetVel = V3LoadU(contact.targetVel); for(PxU32 k = 0; k < frictionPerPointCount; ++k) { const Vec3V t0 = tFallback; tFallback = tFallbackAlt; tFallbackAlt = t0; SolverContactFriction* PX_RESTRICT f0 = reinterpret_cast<SolverContactFriction*>(p); p += frictionStride; //f0->brokenOrContactIndex = contactId; const Vec3V raXn = V3Cross(ra, t0); const Vec3V rbXn = V3Cross(rb, t0); const Vec3V delAngVel0 = M33MulV3(invSqrtInertia0, raXn); const Vec3V delAngVel1 = M33MulV3(invSqrtInertia1, rbXn); const FloatV resp0 = FAdd(invMass0_dom0fV, FMul(angD0, V3Dot(delAngVel0, delAngVel0))); const FloatV resp1 = FSub(FMul(angD1, V3Dot(delAngVel1, delAngVel1)), invMass1_dom1fV); const FloatV resp = FAdd(resp0, resp1); const FloatV velMultiplier = FNeg(FSel(FIsGrtr(resp, zero), FRecip(resp), zero)); 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); f0->normalXYZ_appliedForceW = V4SetW(Vec4V_From_Vec3V(t0), zero); f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(delAngVel0), velMultiplier); //f0->rbXnXYZ_targetVelocityW = V4SetW(Vec4V_From_Vec3V(delAngVel1), FSub(V3Dot(targetVel, t0), vrel)); f0->rbXnXYZ_biasW = Vec4V_From_Vec3V(delAngVel1); FStore(FSub(V3Dot(targetVel, t0), vrel), &f0->targetVel); } } ptr = p; } } } *ptr = 0; return hasFriction; } static void computeBlockStreamByteSizesCoulomb( const CorrelationBuffer& c, const PxU32 frictionCountPerPoint, PxU32& _solverConstraintByteSize, PxU32& _axisConstraintCount, bool useExtContacts) { PX_ASSERT(0 == _solverConstraintByteSize); 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(SolverContactCoulombHeader); solverConstraintByteSize += useExtContacts ? c.frictionPatchContactCounts[i] * sizeof(SolverContactPointExt) : c.frictionPatchContactCounts[i] * sizeof(SolverContactPoint); axisConstraintCount += c.frictionPatchContactCounts[i]; //We always need the friction headers to write the accumulated if(haveFriction) { //4 bytes solverConstraintByteSize += sizeof(SolverFrictionHeader); //buffer to store applied forces in solverConstraintByteSize += SolverFrictionHeader::getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]); const PxU32 nbFrictionConstraints = c.frictionPatchContactCounts[i] * frictionCountPerPoint; solverConstraintByteSize += useExtContacts ? nbFrictionConstraints * sizeof(SolverContactFrictionExt) : nbFrictionConstraints * sizeof(SolverContactFriction); axisConstraintCount += c.frictionPatchContactCounts[i]; } else { //reserve buffers for storing accumulated impulses solverConstraintByteSize += sizeof(SolverFrictionHeader); solverConstraintByteSize += SolverFrictionHeader::getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]); } } } _axisConstraintCount = axisConstraintCount; //16-byte alignment. _solverConstraintByteSize = ((solverConstraintByteSize + 0x0f) & ~0x0f); PX_ASSERT(0 == (_solverConstraintByteSize & 0x0f)); } static bool reserveBlockStreamsCoulomb(const CorrelationBuffer& c, PxU8*& solverConstraint, PxU32 frictionCountPerPoint, PxU32& solverConstraintByteSize, PxU32& axisConstraintCount, PxConstraintAllocator& constraintAllocator, bool useExtContacts) { PX_ASSERT(NULL == solverConstraint); PX_ASSERT(0 == solverConstraintByteSize); PX_ASSERT(0 == axisConstraintCount); //From constraintBlockStream we need to reserve contact points, contact forces, and a char buffer for the solver constraint data (already have a variable for this). //From frictionPatchStream we just need to reserve a single buffer. //Compute the sizes of all the buffers. computeBlockStreamByteSizesCoulomb( c, frictionCountPerPoint, solverConstraintByteSize, axisConstraintCount, useExtContacts); //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; } } } //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)); } bool createFinalizeSolverContactsCoulomb1D(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, Cm::SpatialVectorF* Z) { return createFinalizeSolverContactsCoulomb(contactDesc, output, threadContext, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eONE_DIRECTIONAL, Z); } bool createFinalizeSolverContactsCoulomb2D(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, Cm::SpatialVectorF* Z) { return createFinalizeSolverContactsCoulomb(contactDesc, output, threadContext, invDtF32, dtF32, bounceThresholdF32, frictionOffsetThreshold, correlationDistance, constraintAllocator, PxFrictionType::eTWO_DIRECTIONAL, Z); } bool createFinalizeSolverContactsCoulomb(PxSolverContactDesc& contactDesc, PxsContactManagerOutput& output, ThreadContext& threadContext, const PxReal invDtF32, const PxReal dtF32, PxReal bounceThresholdF32, PxReal frictionOffsetThreshold, PxReal correlationDistance, PxConstraintAllocator& constraintAllocator, PxFrictionType::Enum frictionType, Cm::SpatialVectorF* Z) { PX_UNUSED(frictionOffsetThreshold); PX_UNUSED(correlationDistance); PxSolverConstraintDesc& desc = *contactDesc.desc; desc.constraintLengthOver16 = 0; 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. PxPrefetchLine(contactDesc.frictionPtr); PxReal invMassScale0 = 1.f; PxReal invMassScale1 = 1.f; PxReal invInertiaScale0 = 1.f; PxReal invInertiaScale1 = 1.f; bool hasMaxImpulse = false, hasTargetVelocity = false; PxU32 numContacts = extractContacts(buffer, output, hasMaxImpulse, hasTargetVelocity, invMassScale0, invMassScale1, invInertiaScale0, invInertiaScale1, PxMin(contactDesc.data0->maxContactImpulse, contactDesc.data1->maxContactImpulse)); if(numContacts == 0) { contactDesc.frictionPtr = NULL; contactDesc.frictionCount = 0; return true; } PxPrefetchLine(contactDesc.body0); PxPrefetchLine(contactDesc.body1); PxPrefetchLine(contactDesc.data0); PxPrefetchLine(contactDesc.data1); CorrelationBuffer& c = threadContext.mCorrelationBuffer; c.frictionPatchCount = 0; c.contactPatchCount = 0; createContactPatches(c, buffer.contacts, buffer.count, PXC_SAME_NORMAL); PxU32 numFrictionPerPatch = PxU32(frictionType == PxFrictionType::eONE_DIRECTIONAL ? 1 : 2); bool overflow = correlatePatches(c, buffer.contacts, contactDesc.bodyFrame0, contactDesc.bodyFrame1, PXC_SAME_NORMAL, 0, 0); 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 //PX_ASSERT(patchCount == c.frictionPatchCount); PxU8* solverConstraint = NULL; PxU32 solverConstraintByteSize = 0; PxU32 axisConstraintCount = 0; const bool useExtContacts = !!((contactDesc.bodyState0 | contactDesc.bodyState1) & PxSolverContactDesc::eARTICULATION); const bool successfulReserve = reserveBlockStreamsCoulomb( c, solverConstraint, numFrictionPerPatch, solverConstraintByteSize, axisConstraintCount, constraintAllocator, useExtContacts); // initialise the work unit's ptrs to the various buffers. contactDesc.frictionPtr = NULL; desc.constraint = NULL; desc.constraintLengthOver16 = 0; contactDesc.frictionCount = 0; // patch up the work unit with the reserved buffers and set the reserved buffer data as appropriate. if(successfulReserve) { desc.constraint = solverConstraint; output.nbContacts = PxTo16(numContacts); desc.constraintLengthOver16 = PxTo16(solverConstraintByteSize/16); //Initialise solverConstraint buffer. if(solverConstraint) { bool hasFriction = false; 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); hasFriction = setupFinalizeExtSolverContactsCoulomb(buffer, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint, invDtF32, dtF32, bounceThresholdF32, b0, b1, numFrictionPerPatch, invMassScale0, invInertiaScale0, invMassScale1, invInertiaScale1, contactDesc.restDistance, contactDesc.maxCCDSeparation, Z, contactDesc.offsetSlop); } else { hasFriction = setupFinalizeSolverConstraintsCoulomb(getInteraction(contactDesc), buffer, c, contactDesc.bodyFrame0, contactDesc.bodyFrame1, solverConstraint, data0, data1, invDtF32, dtF32, bounceThresholdF32, numFrictionPerPatch, contactDesc.hasForceThresholds, contactDesc.bodyState1 == PxSolverContactDesc::eSTATIC_BODY, invMassScale0, invInertiaScale0, invMassScale1, invInertiaScale1, contactDesc.restDistance, contactDesc.maxCCDSeparation, contactDesc.offsetSlop); } *(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize)) = 0; *(reinterpret_cast<PxU32*>(solverConstraint + solverConstraintByteSize + 4)) = hasFriction ? 0xFFFFFFFF : 0; } } return successfulReserve; } } }
23,559
C++
37
169
0.75572
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraintTypes.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_TYPES_H #define DY_SOLVER_CONSTRAINT_TYPES_H #include "foundation/PxSimpleTypes.h" #include "PxvConfig.h" namespace physx { enum SolverConstraintType { DY_SC_TYPE_NONE = 0, DY_SC_TYPE_RB_CONTACT, // RB-only contact DY_SC_TYPE_RB_1D, // RB-only 1D constraint DY_SC_TYPE_EXT_CONTACT, // contact involving articulations DY_SC_TYPE_EXT_1D, // 1D constraint involving articulations DY_SC_TYPE_STATIC_CONTACT, // RB-only contact where body b is static DY_SC_TYPE_NOFRICTION_RB_CONTACT, //RB-only contact with no friction patch DY_SC_TYPE_BLOCK_RB_CONTACT, DY_SC_TYPE_BLOCK_STATIC_RB_CONTACT, DY_SC_TYPE_BLOCK_1D, // PT: the following types are only used in the PGS PF solver DY_SC_TYPE_FRICTION, DY_SC_TYPE_STATIC_FRICTION, DY_SC_TYPE_EXT_FRICTION, DY_SC_TYPE_BLOCK_FRICTION, DY_SC_TYPE_BLOCK_STATIC_FRICTION, DY_SC_CONSTRAINT_TYPE_COUNT //Count of the number of different constraint types in the solver }; enum SolverConstraintFlags { DY_SC_FLAG_OUTPUT_FORCE = (1<<1), DY_SC_FLAG_KEEP_BIAS = (1<<2), DY_SC_FLAG_ROT_EQ = (1<<3), DY_SC_FLAG_ORTHO_TARGET = (1<<4), DY_SC_FLAG_SPRING = (1<<5), DY_SC_FLAG_INEQUALITY = (1<<6) }; } #endif
2,910
C
38.337837
94
0.741581
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFeatherstoneInverseDynamic.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "CmConeLimitHelper.h" #include "DySolverConstraint1D.h" #include "DyFeatherstoneArticulation.h" #include "PxsRigidBody.h" #include "PxcConstraintBlockStream.h" #include "DyArticulationContactPrep.h" #include "DyDynamics.h" #include "DyArticulationPImpl.h" #include "foundation/PxProfiler.h" #include "extensions/PxContactJoint.h" #include "DyFeatherstoneArticulationLink.h" #include "DyFeatherstoneArticulationJointData.h" #include "DyConstraint.h" #include "DyConstraintPrep.h" #include "DySolverContext.h" namespace physx { namespace Dy { void PxcFsFlushVelocity(FeatherstoneArticulation& articulation, Cm::SpatialVectorF* deltaV, bool doConstraintForce); void FeatherstoneArticulation::computeLinkAccelerationInv(ArticulationData& data, ScratchData& scratchData) { Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; Cm::SpatialVectorF* coriolisVectors = scratchData.coriolisVectors; PxReal* jointAccelerations = scratchData.jointAccelerations; motionAccelerations[0] = Cm::SpatialVectorF::Zero(); for (PxU32 linkID = 1; linkID < data.getLinkCount(); ++linkID) { ArticulationLink& link = data.getLink(linkID); Cm::SpatialVectorF pMotionAcceleration = translateSpatialVector(-data.getRw(linkID), motionAccelerations[link.parent]); Cm::SpatialVectorF motionAcceleration(PxVec3(0.f), PxVec3(0.f)); if (jointAccelerations) { ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const PxU32 jointOffset = jointDatum.jointOffset; const PxReal* jAcceleration = &jointAccelerations[jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { motionAcceleration.top += data.mWorldMotionMatrix[jointOffset + ind].top * jAcceleration[ind]; motionAcceleration.bottom += data.mWorldMotionMatrix[jointOffset + ind].bottom * jAcceleration[ind]; } } motionAccelerations[linkID] = pMotionAcceleration + coriolisVectors[linkID] + motionAcceleration; } } //generalized force void FeatherstoneArticulation::computeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData) { const PxU32 linkCount = data.getLinkCount(); Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors; PxReal* jointForces = scratchData.jointForces; for (PxU32 linkID = (linkCount - 1); linkID > 0; --linkID) { ArticulationLink& link = data.getLink(linkID); //joint force spatialZAForces[link.parent] += translateSpatialVector(data.getRw(linkID), spatialZAForces[linkID]); ArticulationJointCoreData& jointDatum = data.getJointData(linkID); //compute generalized force const PxU32 jointOffset = jointDatum.jointOffset; PxReal* force = &jointForces[jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { force[ind] = data.mWorldMotionMatrix[jointOffset + ind].innerProduct(spatialZAForces[linkID]); } } } void FeatherstoneArticulation::computeZAForceInv(ArticulationData& data, ScratchData& scratchData) { const PxU32 linkCount = data.getLinkCount(); Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; Cm::SpatialVectorF* biasForce = scratchData.spatialZAVectors; for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ArticulationLink& link = data.getLink(linkID); PxsBodyCore& core = *link.bodyCore; const PxVec3& ii = core.inverseInertia; const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass; const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z)); Cm::SpatialVectorF Ia; Ia.bottom = core.body2World.rotate(core.body2World.rotateInv(motionAccelerations[linkID].top).multiply(inertiaTensor)); Ia.top = motionAccelerations[linkID].bottom * m; biasForce[linkID] +=Ia; } } void FeatherstoneArticulation::initCompositeSpatialInertia(ArticulationData& data, Dy::SpatialMatrix* compositeSpatialInertia) { const PxU32 linkCount = data.getLinkCount(); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { SpatialMatrix& spatialInertia = compositeSpatialInertia[linkID]; ArticulationLink& link = data.getLink(linkID); PxsBodyCore& core = *link.bodyCore; const PxVec3& ii = core.inverseInertia; const PxReal m = core.inverseMass == 0.f ? 0.f : 1.0f / core.inverseMass; //construct mass matric spatialInertia.topLeft = PxMat33(PxZero); spatialInertia.topRight = PxMat33::createDiagonal(PxVec3(m)); //construct inertia matrix PxMat33 rot(data.getLink(linkID).bodyCore->body2World.q); PxMat33& I = spatialInertia.bottomLeft; const PxVec3 inertiaTensor = PxVec3(ii.x == 0.f ? 0.f : (1.f / ii.x), ii.y == 0.f ? 0.f : (1.f / ii.y), ii.z == 0.f ? 0.f : (1.f / ii.z)); Cm::transformInertiaTensor(inertiaTensor, rot, I); } } void FeatherstoneArticulation::computeCompositeSpatialInertiaAndZAForceInv(ArticulationData& data, ScratchData& scratchData) { ArticulationLink* links = data.getLinks(); const PxU32 linkCount = data.getLinkCount(); const PxU32 startIndex = PxU32(linkCount - 1); Dy::SpatialMatrix* compositeSpatialInertia = scratchData.compositeSpatialInertias; Cm::SpatialVectorF* zaForce = scratchData.spatialZAVectors; initCompositeSpatialInertia(data, compositeSpatialInertia); for (PxU32 linkID = startIndex; linkID > 0; --linkID) { ArticulationLink& link = links[linkID]; Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[linkID]; translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(data.getRw(linkID)), cSpatialInertia); //compute parent's composite spatial inertia compositeSpatialInertia[link.parent] += cSpatialInertia; //compute zero acceleration force. This is the force that would be required to support the //motion of all the bodies in childen set if root node acceleration happened to be zero zaForce[link.parent] += translateSpatialVector(data.getRw(linkID), zaForce[linkID]); } } void FeatherstoneArticulation::computeRelativeGeneralizedForceInv(ArticulationData& data, ScratchData& scratchData) { Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; Dy::SpatialMatrix* compositeSpatialInertia = scratchData.compositeSpatialInertias; Cm::SpatialVectorF* zaForce = scratchData.spatialZAVectors; PxReal* jointForces = scratchData.jointForces; Dy::SpatialMatrix invInertia = compositeSpatialInertia[0].invertInertia(); motionAccelerations[0] = -(invInertia * zaForce[0]); const PxU32 linkCount = data.getLinkCount(); ArticulationLink* links = data.getLinks(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = links[linkID]; //const SpatialTransform p2c = data.mChildToParent[linkID].getTranspose(); motionAccelerations[linkID] = translateSpatialVector(-data.getRw(linkID), motionAccelerations[link.parent]); zaForce[linkID] = compositeSpatialInertia[linkID] * motionAccelerations[linkID] + zaForce[linkID]; ArticulationJointCoreData& jointDatum = data.getJointData(linkID); //compute generalized force const PxU32 jointOffset = jointDatum.jointOffset; PxReal* jForce = &jointForces[jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { jForce[ind] = data.mWorldMotionMatrix[jointOffset+ind].innerProduct(zaForce[linkID]); } } } void FeatherstoneArticulation::inverseDynamic(ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData, bool computeCoriolis) { //pass 1 computeLinkVelocities(data, scratchData); if(computeCoriolis) computeC(data, scratchData); else PxMemZero(scratchData.coriolisVectors, sizeof(Cm::SpatialVectorF)*data.getLinkCount()); computeZ(data, gravity, scratchData); computeLinkAccelerationInv(data, scratchData); computeZAForceInv(data, scratchData); //pass 2 computeGeneralizedForceInv(data, scratchData); } void FeatherstoneArticulation::inverseDynamicFloatingBase(ArticulationData& data, const PxVec3& gravity, ScratchData& scratchData, bool computeCoriolis) { //pass 1 computeLinkVelocities(data, scratchData); if(computeCoriolis) computeC(data, scratchData); else PxMemZero(scratchData.coriolisVectors, sizeof(Cm::SpatialVectorF)*data.getLinkCount()); computeZ(data, gravity, scratchData); //no gravity, no external accelerations because we have turned those in force in //computeZ computeLinkAccelerationInv(data, scratchData); computeZAForceInv(data, scratchData); //pass 2 computeCompositeSpatialInertiaAndZAForceInv(data, scratchData); //pass 3 computeRelativeGeneralizedForceInv(data, scratchData); } bool FeatherstoneArticulation::applyCacheToDest(ArticulationData& data, PxArticulationCache& cache, PxReal* jVelocities, PxReal* jPositions, PxReal* jointForces, PxReal* jointTargetPositions, PxReal* jointTargetVelocities, const PxArticulationCacheFlags flag, bool& shouldWake) { bool needsScheduling = !mGPUDirtyFlags; bool localShouldWake = false; if (flag & PxArticulationCacheFlag::eVELOCITY) { const PxU32 dofCount = data.getDofs(); for (PxU32 i = 0; i < dofCount; ++i) { const PxReal jv = cache.jointVelocity[i]; localShouldWake = localShouldWake || jv != 0.f; jVelocities[i] = jv; } mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_VELOCITIES; } if (flag & PxArticulationCacheFlag::eROOT_TRANSFORM) { ArticulationLink& rLink = mArticulationData.getLink(0); // PT:: tag: scalar transform*transform rLink.bodyCore->body2World = cache.rootLinkData->transform * rLink.bodyCore->getBody2Actor(); mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_TRANSFORM; } if(flag & PxArticulationCacheFlag::eROOT_VELOCITIES) { ArticulationLink& rLink = mArticulationData.getLink(0); rLink.bodyCore->linearVelocity = cache.rootLinkData->worldLinVel; rLink.bodyCore->angularVelocity = cache.rootLinkData->worldAngVel; localShouldWake = localShouldWake || (!cache.rootLinkData->worldLinVel.isZero()) || (!cache.rootLinkData->worldAngVel.isZero()); mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_ROOT_VELOCITIES; } if (flag & PxArticulationCacheFlag::ePOSITION) { copyJointData(data, jPositions, cache.jointPosition); //When we update the joint positions, we also have to update the link state, so need to make links //dirty! mGPUDirtyFlags |= (ArticulationDirtyFlag::eDIRTY_POSITIONS); } if (flag & PxArticulationCacheFlag::eFORCE) { const PxU32 dofCount = data.getDofs(); for (PxU32 i = 0; i < dofCount; ++i) { const PxReal jf = cache.jointForce[i]; localShouldWake = localShouldWake || jf != 0.f; jointForces[i] = jf; } mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_FORCES; } if (flag & PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS) { const PxU32 dofCount = data.getDofs(); for (PxU32 i = 0; i < dofCount; ++i) { const PxReal jt = cache.jointTargetPositions[i]; localShouldWake = localShouldWake || jt != jPositions[i]; jointTargetPositions[i] = jt; } mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_POS; } if (flag & PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES) { const PxU32 dofCount = data.getDofs(); for (PxU32 i = 0; i < dofCount; ++i) { const PxReal jv = cache.jointTargetVelocities[i]; localShouldWake = localShouldWake || jv != jVelocities[i]; jointTargetVelocities[i] = jv; } mGPUDirtyFlags |= ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_VEL; } // the updateKinematic functions rely on updated joint frames. if (mJcalcDirty) { jcalc(data); } mJcalcDirty = false; if (flag & (PxArticulationCacheFlag::ePOSITION | PxArticulationCacheFlag::eROOT_TRANSFORM)) { //update link's position based on the joint position teleportLinks(data); } if (flag & (PxArticulationCacheFlag::eVELOCITY | PxArticulationCacheFlag::ePOSITION | PxArticulationCacheFlag::eROOT_VELOCITIES | PxArticulationCacheFlag::eROOT_TRANSFORM)) { computeLinkVelocities(data); } shouldWake = localShouldWake; return needsScheduling; } void FeatherstoneArticulation::packJointData(const PxReal* maximum, PxReal* reduced) { const PxU32 linkCount = mArticulationData.getLinkCount(); for (PxU32 linkID = 1; linkID < linkCount; linkID++) { ArticulationLink& linkDatum = mArticulationData.getLink(linkID); ArticulationJointCore* joint = linkDatum.inboundJoint; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); const PxReal* maxJointData = &maximum[(linkID - 1) * DY_MAX_DOF]; PxReal* reducedJointData = &reduced[jointDatum.jointOffset]; PxU32 count = 0; for (PxU32 j = 0; j < DY_MAX_DOF; ++j) { PxArticulationMotions motion = PxArticulationMotions(joint->motion[j]); if (motion != PxArticulationMotion::eLOCKED) { reducedJointData[count] = maxJointData[j]; count++; } } PX_ASSERT(count == jointDatum.dof); } } void FeatherstoneArticulation::unpackJointData(const PxReal* reduced, PxReal* maximum) { const PxU32 linkCount = mArticulationData.getLinkCount(); for (PxU32 linkID = 1; linkID < linkCount; linkID++) { ArticulationLink& linkDatum = mArticulationData.getLink(linkID); ArticulationJointCore* joint = linkDatum.inboundJoint; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); PxReal* maxJointData = &maximum[(linkID - 1) * DY_MAX_DOF]; const PxReal* reducedJointData = &reduced[jointDatum.jointOffset]; PxU32 count = 0; for (PxU32 j = 0; j < DY_MAX_DOF; ++j) { PxArticulationMotions motion = PxArticulationMotions(joint->motion[j]); if (motion != PxArticulationMotion::eLOCKED) { maxJointData[j] = reducedJointData[count]; count++; } else { maxJointData[j] = 0.f; } } PX_ASSERT(count == jointDatum.dof); } } void FeatherstoneArticulation::initializeCommonData() { if (mJcalcDirty) { jcalc(mArticulationData); mJcalcDirty = false; } { //constants const ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); const ArticulationJointCoreData* jointCoreDatas = mArticulationData.getJointData(); const Cm::UnAlignedSpatialVector* motionMatrices = mArticulationData.getMotionMatrix(); //outputs PxTransform* accumulatedPoses = mArticulationData.getAccumulatedPoses(); PxVec3* rws = mArticulationData.getRw(); Cm::UnAlignedSpatialVector* motionMatricesW = mArticulationData.getWorldMotionMatrix(); computeRelativeTransformC2P( links, linkCount, jointCoreDatas, motionMatrices, accumulatedPoses, rws, motionMatricesW); } computeRelativeTransformC2B(mArticulationData); computeSpatialInertia(mArticulationData); mArticulationData.setDataDirty(false); } void FeatherstoneArticulation::getGeneralizedGravityForce(const PxVec3& gravity, PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getGeneralisedGravityForce() commonInit need to be called first to initialize data!"); return; } #if FEATHERSTONE_DEBUG PxReal* jointForce = reinterpret_cast<PxReal*>(PX_ALLOC(sizeof(PxReal) * mArticulationData.getDofs(), "jointForce")); { const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = NULL; scratchData.jointAccelerations = NULL; scratchData.jointForces = jointForce; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) inverseDynamic(mArticulationData, gravity, scratchData, false); else inverseDynamicFloatingBase(mArticulationData, gravity, scratchData, false); allocator->free(tempMemory); } #endif const PxVec3 tGravity = -gravity; PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); const PxU32 linkCount = mArticulationData.getLinkCount(); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) { Cm::SpatialVectorF* spatialZAForces = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount)); for (PxU32 linkID = 0; linkID < linkCount; ++linkID) { ArticulationLink& link = mArticulationData.getLink(linkID); PxsBodyCore& core = *link.bodyCore; const PxReal m = 1.0f / core.inverseMass; const PxVec3 linkGravity = tGravity; spatialZAForces[linkID].top = m*linkGravity; spatialZAForces[linkID].bottom = PxVec3(0.f); } ScratchData scratchData; scratchData.spatialZAVectors = spatialZAForces; scratchData.jointForces = cache.jointForce; computeGeneralizedForceInv(mArticulationData, scratchData); //release spatialZA vectors allocator->free(spatialZAForces); } else { ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = NULL; scratchData.jointAccelerations = NULL; scratchData.jointForces = cache.jointForce; scratchData.externalAccels = NULL; inverseDynamicFloatingBase(mArticulationData, tGravity, scratchData, false); allocator->free(tempMemory); } #if FEATHERSTONE_DEBUG //compare joint force const PxU32 totalDofs = mArticulationData.getDofs(); for (PxU32 i = 0; i < totalDofs; ++i) { const PxReal dif = jointForce[i] - cache.jointForce[i]; PX_ASSERT(PxAbs(dif) < 5e-3f); } PX_FREE(jointForce); #endif } //gravity, acceleration and external force(external acceleration) are zero void FeatherstoneArticulation::getCoriolisAndCentrifugalForce(PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getCoriolisAndCentrifugalForce() commonInit need to be called first to initialize data!"); return; } const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = cache.jointVelocity; scratchData.jointAccelerations = NULL; scratchData.jointForces = cache.jointForce; scratchData.externalAccels = NULL; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, true); else inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, true); allocator->free(tempMemory); } //gravity, joint acceleration and joint velocity are zero void FeatherstoneArticulation::getGeneralizedExternalForce(PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Articulation::getCoriolisAndCentrifugalForce() commonInit need to be called first to initialize data!"); return; } const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); scratchData.jointVelocities = NULL; scratchData.jointAccelerations = NULL; scratchData.jointForces = cache.jointForce; Cm::SpatialVector* accels = reinterpret_cast<Cm::SpatialVector*>(allocator->alloc(sizeof(Cm::SpatialVector) * linkCount)); //turn external forces to external accels for (PxU32 i = 0; i < linkCount; ++i) { ArticulationLink& link = mArticulationData.getLink(i); PxsBodyCore& core = *link.bodyCore; const PxSpatialForce& force = cache.externalForces[i]; Cm::SpatialVector& accel = accels[i]; accel.linear = force.force * core.inverseMass; PxMat33 inverseInertiaWorldSpace; Cm::transformInertiaTensor(core.inverseInertia, PxMat33(core.body2World.q), inverseInertiaWorldSpace); accel.angular = inverseInertiaWorldSpace * force.torque; } scratchData.externalAccels = accels; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false); else inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false); allocator->free(tempMemory); allocator->free(accels); } //provided joint acceleration, calculate joint force void FeatherstoneArticulation::getJointForce(PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getJointForce() commonInit need to be called first to initialize data!"); return; } //const PxU32 size = sizeof(PxReal) * mArticulationData.getDofs(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); //PxReal* jointVelocities = reinterpret_cast<PxReal*>(allocator->alloc(size)); ScratchData scratchData; scratchData.jointVelocities = NULL;//jont velocity will be zero scratchData.jointAccelerations = cache.jointAcceleration; //input scratchData.jointForces = cache.jointForce; //output scratchData.externalAccels = NULL; PxU8* tempMemory = allocateScratchSpatialData(allocator, mArticulationData.getLinkCount(), scratchData); //make sure joint velocity be zero //PxMemZero(jointVelocities, sizeof(PxReal) * mArticulationData.getDofs()); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false); else inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false); //allocator->free(jointVelocities); allocator->free(tempMemory); } void FeatherstoneArticulation::jcalcLoopJointSubspace(ArticulationJointCore* joint, ArticulationJointCoreData& jointDatum, SpatialSubspaceMatrix& T, const Cm::UnAlignedSpatialVector* jointAxis) { PX_UNUSED(jointDatum); const PxVec3 childOffset = -joint->childPose.p; const PxVec3 zero(0.f); //if the column is free, we put zero for it, this is for computing K(coefficient matrix) T.setNumColumns(6); //transpose(Tc)*S = 0 //transpose(Ta)*S = 1 switch (joint->jointType) { case PxArticulationJointType::ePRISMATIC: { PX_ASSERT(jointDatum.dof == 1); const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized(); const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized(); const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized(); //joint->activeForceSubspace.setNumColumns(1); if (jointAxis[0][3] == 1.f) { //x is the free translation axis T.setColumn(0, rx, zero); T.setColumn(1, ry, zero); T.setColumn(2, rz, zero); T.setColumn(3, zero, zero); T.setColumn(4, zero, ry); T.setColumn(5, zero, rz); //joint->activeForceSubspace.setColumn(0, PxVec3(0.f), rx); } else if (jointAxis[0][4] == 1.f) { //y is the free translation axis T.setColumn(0, rx, zero); T.setColumn(1, ry, zero); T.setColumn(2, rz, zero); T.setColumn(3, zero, rx); T.setColumn(4, zero, zero); T.setColumn(5, zero, rz); //joint->activeForceSubspace.setColumn(0, PxVec3(0.f), ry); } else if (jointAxis[0][5] == 1.f) { //z is the free translation axis T.setColumn(0, rx, zero); T.setColumn(1, ry, zero); T.setColumn(2, rx, zero); T.setColumn(3, zero, rx); T.setColumn(4, zero, ry); T.setColumn(5, zero, zero); //joint->activeForceSubspace.setColumn(0, PxVec3(0.f), rz); } break; } case PxArticulationJointType::eREVOLUTE: case PxArticulationJointType::eREVOLUTE_UNWRAPPED: { //joint->activeForceSubspace.setNumColumns(1); const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized(); const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized(); const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized(); const PxVec3 rxXd = rx.cross(childOffset); const PxVec3 ryXd = ry.cross(childOffset); const PxVec3 rzXd = rz.cross(childOffset); if (jointAxis[0][0] == 1.f) { //x is the free rotation axis T.setColumn(0, zero, zero); T.setColumn(1, ry, zero); T.setColumn(2, rz, zero); //joint->activeForceSubspace.setColumn(0, rx, PxVec3(0.f)); } else if (jointAxis[0][1] == 1.f) { //y is the free rotation axis T.setColumn(0, rx, zero); T.setColumn(1, zero, zero); T.setColumn(2, rz, zero); //joint->activeForceSubspace.setColumn(0, ry, PxVec3(0.f)); } else if (jointAxis[0][2] == 1.f) { //z is the rotation axis T.setColumn(0, rx, zero); T.setColumn(1, ry, zero); T.setColumn(2, zero, zero); //joint->activeForceSubspace.setColumn(0, rz, PxVec3(0.f)); } T.setColumn(3, rxXd, rx); T.setColumn(4, ryXd, ry); T.setColumn(5, rzXd, rz); break; } case PxArticulationJointType::eSPHERICAL: { //joint->activeForceSubspace.setNumColumns(3); const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized(); const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized(); const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized(); const PxVec3 rxXd = rx.cross(childOffset); const PxVec3 ryXd = ry.cross(childOffset); const PxVec3 rzXd = rz.cross(childOffset); T.setColumn(0, zero, zero); T.setColumn(1, zero, zero); T.setColumn(2, zero, zero); T.setColumn(3, rxXd, rx); T.setColumn(4, ryXd, ry); T.setColumn(5, rzXd, rz); //need to implement constraint force subspace matrix and active force subspace matrix break; } case PxArticulationJointType::eFIX: { //joint->activeForceSubspace.setNumColumns(0); //T.setNumColumns(6); /* const PxVec3 rx = (joint->childPose.rotate(PxVec3(1.f, 0.f, 0.f))).getNormalized(); const PxVec3 ry = (joint->childPose.rotate(PxVec3(0.f, 1.f, 0.f))).getNormalized(); const PxVec3 rz = (joint->childPose.rotate(PxVec3(0.f, 0.f, 1.f))).getNormalized(); T.setColumn(0, rx, PxVec3(0.f)); T.setColumn(1, ry, PxVec3(0.f)); T.setColumn(2, rz, PxVec3(0.f)); T.setColumn(3, PxVec3(0.f), rx); T.setColumn(4, PxVec3(0.f), ry); T.setColumn(5, PxVec3(0.f), rz); */ T.setColumn(0, PxVec3(1.f, 0.f, 0.f), zero); T.setColumn(1, PxVec3(0.f, 1.f, 0.f), zero); T.setColumn(2, PxVec3(0.f, 0.f, 1.f), zero); T.setColumn(3, zero, PxVec3(1.f, 0.f, 0.f)); T.setColumn(4, zero, PxVec3(0.f, 1.f, 0.f)); T.setColumn(5, zero, PxVec3(0.f, 0.f, 1.f)); PX_ASSERT(jointDatum.dof == 0); break; } default: break; } } //This method supports just one loopJoint void FeatherstoneArticulation::getKMatrix(ArticulationJointCore* loopJoint, const PxU32 parentIndex, const PxU32 childIndex, PxArticulationCache& cache) { PX_UNUSED(loopJoint); PX_UNUSED(parentIndex); PX_UNUSED(childIndex); PX_UNUSED(cache); ////initialize all tree links motion subspace matrix //jcalc(mArticulationData); ////linkID is the parent link, ground is the child link so child link is the fix base //ArticulationLinkData& pLinkDatum = mArticulationData.getLinkData(parentIndex); //ArticulationLink& cLink = mArticulationData.getLink(childIndex); //ArticulationLinkData& cLinkDatum = mArticulationData.getLinkData(childIndex); // //ArticulationJointCoreData loopJointDatum; //loopJointDatum.computeJointDof(loopJoint); ////this is constraintForceSubspace in child body space(T) //SpatialSubspaceMatrix T; ////loop joint constraint subspace matrix(T) //jcalcLoopJointSubspace(loopJoint, loopJointDatum, T); //const PxU32 linkCount = mArticulationData.getLinkCount(); ////set Jacobian matrix to be zero //PxMemZero(cache.jacobian, sizeof(PxKinematicJacobian) * linkCount); ////transform T to world space //PxTransform& body2World = cLink.bodyCore->body2World; //for (PxU32 ind = 0; ind < T.getNumColumns(); ++ind) //{ // Cm::SpatialVectorF& column = T[ind]; // T.setColumn(ind, body2World.rotate(column.top), body2World.rotate(column.bottom)); //} //const Cm::SpatialVectorF& pAccel = pLinkDatum.motionAcceleration; //const Cm::SpatialVectorF& cAccel = cLinkDatum.motionAcceleration; //const Cm::SpatialVectorF& pVel = pLinkDatum.motionVelocity; //const Cm::SpatialVectorF& cVel = cLinkDatum.motionVelocity; //Cm::SpatialVectorF k = (pAccel - cAccel) + pVel.cross(cVel); //k = T.transposeMultiply(k); //k = -k; //PxU32 i = childIndex; //PxU32 j = parentIndex; //PxU32* index = NULL; //while (i != j) //{ // if (i > j) // index = &i; // else // index = &j; // const PxU32 linkIndex = *index; // PxKinematicJacobian* K = cache.jacobian + linkIndex; // ArticulationLink& link = mArticulationData.getLink(linkIndex); // ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkIndex); // SpatialSubspaceMatrix& S = jointDatum.motionMatrix; // PxTransform& tBody2World = link.bodyCore->body2World; // Cm::SpatialVectorF res; // for (PxU32 ind = 0; ind < S.getNumColumns(); ++ind) // { // Cm::SpatialVectorF& sCol = S[ind]; // //transform spatial axis into world space // sCol.top = tBody2World.rotate(sCol.top); // sCol.bottom = tBody2World.rotate(sCol.bottom); // res = T.transposeMultiply(sCol); // res = -res; // PxReal* kSubMatrix = K->j[ind]; // kSubMatrix[0] = res.top.x; kSubMatrix[1] = res.top.y; kSubMatrix[2] = res.top.z; // kSubMatrix[3] = res.bottom.x; kSubMatrix[4] = res.bottom.y; kSubMatrix[5] = res.bottom.z; // } // //overwrite either i or j to its parent index // *index = link.parent; //} } void FeatherstoneArticulation::getCoefficientMatrix(const PxReal dt, const PxU32 linkID, const PxContactJoint* contactJoints, const PxU32 nbContacts, PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getCoefficientMatrix() commonInit need to be called first to initialize data!"); return; } computeArticulatedSpatialInertia(mArticulationData); ArticulationLink* links = mArticulationData.getLinks(); const PxU32 linkCount = mArticulationData.getLinkCount(); PxReal* coefficientMatrix = cache.coefficientMatrix; const PxU32 elementCount = mArticulationData.getDofs(); //zero coefficient matrix PxMemZero(coefficientMatrix, sizeof(PxReal) * elementCount * nbContacts); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; for (PxU32 a = 0; a < nbContacts; ++a) { PxJacobianRow row; contactJoints[a].computeJacobians(&row); //impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body //| R(t), 0 | //| R(t)*r, R(t)| //r is the vector from center of mass to contact point //p(impluse) = |n| // |0| //transform p(impluse) from work space to the local space of link ArticulationLink& link = links[linkID]; PxTransform& body2World = link.bodyCore->body2World; PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); Cm::SpatialVectorF* Z = scratchData.spatialZAVectors; //make sure all links' spatial zero acceleration impulse are zero PxMemZero(Z, sizeof(Cm::SpatialVectorF) * linkCount); const Cm::SpatialVectorF impl(body2World.rotateInv(row.linear0), body2World.rotateInv(row.angular0)); getZ(linkID, mArticulationData, Z, impl); const PxU32 totalDofs = mArticulationData.getDofs(); const PxU32 size = sizeof(PxReal) * totalDofs; PxU8* tData = reinterpret_cast<PxU8*>(allocator->alloc(size * 2)); PxReal* jointVelocities = reinterpret_cast<PxReal*>(tData); PxReal* jointAccelerations = reinterpret_cast<PxReal*>(tData + size); //zero joint Velocites PxMemZero(jointVelocities, size); getDeltaVWithDeltaJV(fixBase, linkID, mArticulationData, Z, jointVelocities); const PxReal invDt = 1.f / dt; //calculate joint acceleration due to velocity change for (PxU32 i = 0; i < totalDofs; ++i) { jointAccelerations[i] = jointVelocities[i] * invDt; } //compute individual link's spatial inertia tensor. This is very important computeSpatialInertia(mArticulationData); PxReal* coeCol = &coefficientMatrix[elementCount * a]; //this means the joint force calculated by the inverse dynamic //will be just influenced by joint acceleration change scratchData.jointVelocities = NULL; scratchData.externalAccels = NULL; //Input scratchData.jointAccelerations = jointAccelerations; //a column of the coefficient matrix is the joint force scratchData.jointForces = coeCol; if (fixBase) { inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false); } else { inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false); } allocator->free(tData); allocator->free(tempMemory); } } void FeatherstoneArticulation::getImpulseResponseSlowInv(Dy::ArticulationLink* links, const ArticulationData& data, PxU32 linkID0_, const Cm::SpatialVector& impulse0, Cm::SpatialVector& deltaV0, PxU32 linkID1_, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV1, PxReal* jointVelocities, Cm::SpatialVectorF* Z) { PX_UNUSED(jointVelocities); const PxU32 numLinks = data.getLinkCount(); PX_ALLOCA(_stack, PxU32, numLinks); PxU32* stack = _stack; PxU32 i0, i1, ic; PxU32 linkID0 = linkID0_; PxU32 linkID1 = linkID1_; for (i0 = linkID0, i1 = linkID1; i0 != i1;) // find common path { if (i0<i1) i1 = links[i1].parent; else i0 = links[i0].parent; } PxU32 common = i0; Cm::SpatialVectorF Z0(-impulse0.linear, -impulse0.angular); Cm::SpatialVectorF Z1(-impulse1.linear, -impulse1.angular); Z[linkID0] = Z0; Z[linkID1] = Z1; //for (i0 = linkID0; i0 != common; i0 = links[i0].parent) for (i0 = 0; linkID0 != common; linkID0 = links[linkID0].parent) { const PxU32 jointOffset = mArticulationData.getJointData(linkID0).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID0).dof; Z0 = FeatherstoneArticulation::propagateImpulseW( data.getRw(linkID0), Z0, &data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset),dofCount); Z[links[linkID0].parent] = Z0; stack[i0++] = linkID0; } for (i1 = i0; linkID1 != common; linkID1 = links[linkID1].parent) { const PxU32 jointOffset = mArticulationData.getJointData(linkID1).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID1).dof; Z1 = FeatherstoneArticulation::propagateImpulseW( data.getRw(linkID1), Z1, &data.getWorldIsInvD(jointOffset), &data.getWorldMotionMatrix(jointOffset), dofCount); Z[links[linkID1].parent] = Z1; stack[i1++] = linkID1; } //KS - we can replace the following section of code with the impulse response matrix - until next comment! Cm::SpatialVectorF ZZ = Z0 + Z1; Z[common] = ZZ; for (ic = i1; common; common = links[common].parent) { const PxU32 jointOffset = mArticulationData.getJointData(common).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(common).dof; Z[links[common].parent] = FeatherstoneArticulation::propagateImpulseW( data.getRw(common), Z[common], &data.getWorldIsInvD(jointOffset), &data.getMotionMatrix(jointOffset), dofCount); stack[ic++] = common; } if(data.getArticulationFlags() & PxArticulationFlag::eFIX_BASE) Z[0] = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); //SpatialMatrix inverseArticulatedInertia = data.getLinkData(0).spatialArticulatedInertia.getInverse(); const SpatialMatrix& inverseArticulatedInertia = data.getBaseInvSpatialArticulatedInertiaW(); Cm::SpatialVectorF v = inverseArticulatedInertia * (-Z[0]); for (PxU32 index = ic; (index--) > i1;) { const PxU32 id = stack[index]; const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(id).dof; v = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id], data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount); } //Replace everything to here with the impulse response matrix multiply Cm::SpatialVectorF dv1 = v; for (PxU32 index = i1; (index--) > i0;) { const PxU32 id = stack[index]; const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(id).dof; dv1 = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id], data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount); } Cm::SpatialVectorF dv0 = v; for (PxU32 index = i0; (index--) > 0;) { const PxU32 id = stack[index]; const PxU32 jointOffset = mArticulationData.getJointData(id).jointOffset; const PxU32 dofCount = mArticulationData.getJointData(id).dof; dv0 = FeatherstoneArticulation::propagateVelocityW(data.getRw(id), data.mWorldSpatialArticulatedInertia[id], data.mInvStIs[id], &data.getWorldMotionMatrix(jointOffset), Z[id], jointVelocities, v, dofCount); } deltaV0.linear = dv0.bottom; deltaV0.angular = dv0.top; deltaV1.linear = dv1.bottom; deltaV1.angular = dv1.top; } void FeatherstoneArticulation::getImpulseSelfResponseInv(const bool fixBase, PxU32 linkID0, PxU32 linkID1, Cm::SpatialVectorF* Z, const Cm::SpatialVector& impulse0, const Cm::SpatialVector& impulse1, Cm::SpatialVector& deltaV0, Cm::SpatialVector& deltaV1, PxReal* jointVelocities) { ArticulationLink* links = mArticulationData.getLinks(); //transform p(impluse) from work space to the local space of link ArticulationLink& link = links[linkID1]; //ArticulationLinkData& linkDatum = mArticulationData.getLinkData(linkID1); if (link.parent == linkID0) { PX_ASSERT(linkID0 == link.parent); PX_ASSERT(linkID0 < linkID1); //impulse is in world space const Cm::SpatialVector& imp1 = impulse1; const Cm::SpatialVector& imp0 = impulse0; Cm::SpatialVectorF pImpulse(imp0.linear, imp0.angular); PX_ASSERT(linkID0 == link.parent); const PxU32 jointOffset = mArticulationData.getJointData(linkID1).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(linkID1).dof; //initialize child link spatial zero acceleration impulse Cm::SpatialVectorF Z1(-imp1.linear, -imp1.angular); //this calculate parent link spatial zero acceleration impulse Cm::SpatialVectorF Z0 = FeatherstoneArticulation::propagateImpulseW( mArticulationData.getRw(linkID1), Z1, &mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount); //in parent space const Cm::SpatialVectorF impulseDif = pImpulse - Z0; Cm::SpatialVectorF delV0(PxVec3(0.f), PxVec3(0.f)); Cm::SpatialVectorF delV1(PxVec3(0.f), PxVec3(0.f)); //calculate velocity change start from the parent link to the root delV0 = FeatherstoneArticulation::getImpulseResponseWithJ(linkID0, fixBase, mArticulationData, Z, impulseDif, jointVelocities); //calculate velocity change for child link delV1 = FeatherstoneArticulation::propagateVelocityW(mArticulationData.getRw(linkID1), mArticulationData.mWorldSpatialArticulatedInertia[linkID1], mArticulationData.mInvStIs[linkID1], &mArticulationData.mWorldMotionMatrix[jointOffset], Z1, jointVelocities, delV0, dofCount); //translate delV0 and delV1 into world space again deltaV0.linear = delV0.bottom; deltaV0.angular = delV0.top; deltaV1.linear = delV1.bottom; deltaV1.angular = delV1.top; } else { getImpulseResponseSlowInv(links, mArticulationData, linkID0, impulse0, deltaV0, linkID1,impulse1, deltaV1, jointVelocities, Z); } } Cm::SpatialVectorF FeatherstoneArticulation::getImpulseResponseInv( const bool fixBase, const PxU32 linkID, Cm::SpatialVectorF* Z, const Cm::SpatialVector& impulse, PxReal* jointVelocities) { //impulse lin is contact normal, and ang is raxn. R is body2World, R(t) is world2Body //| R(t), 0 | //| R(t)*r, R(t)| //r is the vector from center of mass to contact point //p(impluse) = |n| // |0| ArticulationLink* links = mArticulationData.getLinks(); //ArticulationLinkData* linkData = mArticulationData.getLinkData(); ArticulationJointCoreData* jointData = mArticulationData.getJointData(); const PxU32 linkCount = mArticulationData.getLinkCount(); //make sure all links' spatial zero acceleration impulse are zero PxMemZero(Z, sizeof(Cm::SpatialVectorF) * linkCount); Z[linkID] = Cm::SpatialVectorF(-impulse.linear, -impulse.angular); for (PxU32 i = linkID; i; i = links[i].parent) { ArticulationLink& tLink = links[i]; const PxU32 jointOffset = mArticulationData.getJointData(i).jointOffset; const PxU8 dofCount = mArticulationData.getJointData(i).dof; //ArticulationLinkData& tLinkDatum = linkData[i]; Z[tLink.parent] = propagateImpulseW( mArticulationData.getRw(i), Z[i], &mArticulationData.mISInvStIS[jointOffset], &mArticulationData.mWorldMotionMatrix[jointOffset], dofCount); } //set velocity change of the root link to be zero Cm::SpatialVectorF deltaV = Cm::SpatialVectorF(PxVec3(0.f), PxVec3(0.f)); if (!fixBase) deltaV = mArticulationData.mBaseInvSpatialArticulatedInertiaW * (-Z[0]); const PxU32 startIndex = links[linkID].mPathToRootStartIndex; const PxU32 numElems = links[linkID].mPathToRootCount; const PxU32* pathToRoot = &mArticulationData.mPathToRootElements[startIndex]; for(PxU32 i = 0; i < numElems; ++i) { const PxU32 index = pathToRoot[i]; PX_ASSERT(links[index].parent < index); ArticulationJointCoreData& tJointDatum = jointData[index]; PxReal* jVelocity = &jointVelocities[tJointDatum.jointOffset]; deltaV = propagateVelocityW(mArticulationData.getRw(index), mArticulationData.mWorldSpatialArticulatedInertia[index], mArticulationData.mInvStIs[index], &mArticulationData.mWorldMotionMatrix[tJointDatum.jointOffset], Z[index], jVelocity, deltaV, tJointDatum.dof); } return deltaV; } void FeatherstoneArticulation::getCoefficientMatrixWithLoopJoints(ArticulationLoopConstraint* lConstraints, const PxU32 nbConstraints, PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getCoefficientMatrix() commonInit need to be called first to initialize data!"); return; } computeArticulatedSpatialInertia(mArticulationData); const PxU32 linkCount = mArticulationData.getLinkCount(); PxReal* coefficientMatrix = cache.coefficientMatrix; const PxU32 elementCount = mArticulationData.getDofs(); //zero coefficient matrix PxMemZero(coefficientMatrix, sizeof(PxReal) * elementCount * nbConstraints); const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); Cm::SpatialVectorF* Z = scratchData.spatialZAVectors; const PxU32 totalDofs = mArticulationData.getDofs(); const PxU32 size = sizeof(PxReal) * totalDofs; PxU8* tData = reinterpret_cast<PxU8*>(allocator->alloc(size * 2)); const PxReal invDt = 1.f / mArticulationData.getDt(); PxReal* jointVelocities = reinterpret_cast<PxReal*>(tData); PxReal* jointAccelerations = reinterpret_cast<PxReal*>(tData + size); for (PxU32 a = 0; a < nbConstraints; ++a) { ArticulationLoopConstraint& lConstraint = lConstraints[a]; Constraint* aConstraint = lConstraint.constraint; Px1DConstraint rows[MAX_CONSTRAINT_ROWS]; setupConstraintRows(rows, MAX_CONSTRAINT_ROWS); const PxTransform idt(PxIdentity); const PxTransform& body2World0 = aConstraint->body0 ? aConstraint->bodyCore0->body2World : idt; const PxTransform& body2World1 = aConstraint->body1 ? aConstraint->bodyCore1->body2World : idt; PxVec3p unused_body0WorldOffset(0.0f); PxVec3p unused_ra, unused_rb; PxConstraintInvMassScale unused_invMassScales; //TAG:solverprepcall PxU32 constraintCount = (*aConstraint->solverPrep)(rows, unused_body0WorldOffset, MAX_CONSTRAINT_ROWS, unused_invMassScales, aConstraint->constantBlock, body2World0, body2World1, !!(aConstraint->flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS), unused_ra, unused_rb); const PxU32 linkIndex0 = lConstraint.linkIndex0; const PxU32 linkIndex1 = lConstraint.linkIndex1; //zero joint Velocites PxMemZero(jointVelocities, size); for (PxU32 j = 0; j < constraintCount; ++j) { Px1DConstraint& row = rows[j]; if (linkIndex0 != 0x80000000 && linkIndex1 != 0x80000000) { const bool flip = linkIndex0 > linkIndex1; Cm::SpatialVector impulse0(row.linear0, row.angular0); Cm::SpatialVector impulse1(row.linear1, row.angular1); Cm::SpatialVector deltaV0, deltaV1; if (flip) { getImpulseSelfResponseInv(fixBase, linkIndex1, linkIndex0, Z, impulse1, impulse0, deltaV1, deltaV0, jointVelocities); } else { getImpulseSelfResponseInv(fixBase, linkIndex0, linkIndex1, Z, impulse0, impulse1, deltaV0, deltaV1, jointVelocities); } } else { if (linkIndex0 == 0x80000000) { Cm::SpatialVector impulse1(row.linear1, row.angular1); getImpulseResponseInv(fixBase, linkIndex1, Z, impulse1, jointVelocities); } else { Cm::SpatialVector impulse0(row.linear0, row.angular0); getImpulseResponseInv(fixBase, linkIndex0, Z, impulse0, jointVelocities); } } } //calculate joint acceleration due to velocity change for (PxU32 i = 0; i < totalDofs; ++i) { jointAccelerations[i] = jointVelocities[i] * invDt; } //reset spatial inertia computeSpatialInertia(mArticulationData); PxReal* coeCol = &coefficientMatrix[elementCount * a]; //this means the joint force calculated by the inverse dynamic //will be just influenced by joint acceleration change scratchData.jointVelocities = NULL; scratchData.externalAccels = NULL; //Input scratchData.jointAccelerations = jointAccelerations; //a column of the coefficient matrix is the joint force scratchData.jointForces = coeCol; if (fixBase) { inverseDynamic(mArticulationData, PxVec3(0.f), scratchData, false); } else { inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false); } allocator->free(tData); allocator->free(tempMemory); } } void FeatherstoneArticulation::constraintPrep(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints, Cm::SpatialVectorF* Z, PxSolverConstraintPrepDesc& prepDesc, PxSolverBody& sBody, PxSolverBodyData& sBodyData, PxSolverConstraintDesc* descs, PxConstraintAllocator& allocator) { const PxReal dt = mArticulationData.getDt(); const PxReal invDt = 1.f / dt; //constraint prep for (PxU32 a = 0; a < nbJoints; ++a) { ArticulationLoopConstraint& lConstraint = lConstraints[a]; Constraint* aConstraint = lConstraint.constraint; PxSolverConstraintDesc& desc = descs[a]; prepDesc.desc = &desc; prepDesc.linBreakForce = aConstraint->linBreakForce; prepDesc.angBreakForce = aConstraint->angBreakForce; prepDesc.writeback = &mContext->getConstraintWriteBackPool()[aConstraint->index]; setupConstraintFlags(prepDesc, aConstraint->flags); prepDesc.minResponseThreshold = aConstraint->minResponseThreshold; 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); const PxTransform idt(PxIdentity); const PxTransform& body2World0 = aConstraint->body0 ? aConstraint->bodyCore0->body2World : idt; const PxTransform& body2World1 = aConstraint->body1 ? aConstraint->bodyCore1->body2World : idt; PxVec3p unused_ra, unused_rb; PxConstraintInvMassScale unused_invMassScales; //TAG:solverprepcall prepDesc.numRows = (*aConstraint->solverPrep)(rows, prepDesc.body0WorldOffset, MAX_CONSTRAINT_ROWS, unused_invMassScales, aConstraint->constantBlock, body2World0, body2World1, !!(aConstraint->flags & PxConstraintFlag::eENABLE_EXTENDED_LIMITS), unused_ra, unused_rb); prepDesc.bodyFrame0 = body2World0; prepDesc.bodyFrame1 = body2World1; prepDesc.rows = rows; const PxU32 linkIndex0 = lConstraint.linkIndex0; const PxU32 linkIndex1 = lConstraint.linkIndex1; if (linkIndex0 != 0x80000000 && linkIndex1 != 0x80000000) { desc.articulationA = this; desc.articulationB = this; desc.linkIndexA = PxTo8(linkIndex0); desc.linkIndexB = PxTo8(linkIndex1); desc.bodyA = reinterpret_cast<PxSolverBody*>(this); desc.bodyB = reinterpret_cast<PxSolverBody*>(this); prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eARTICULATION; prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eARTICULATION; } else if (linkIndex0 == 0x80000000) { desc.articulationA = NULL; desc.articulationB = this; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; desc.linkIndexB = PxTo8(linkIndex1); desc.bodyA = &sBody; desc.bodyB = reinterpret_cast<PxSolverBody*>(this); prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eSTATIC_BODY; prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eARTICULATION; } else if (linkIndex1 == 0x80000000) { desc.articulationA = this; desc.articulationB = NULL; desc.linkIndexA = PxTo8(linkIndex0); desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; desc.bodyA = reinterpret_cast<PxSolverBody*>(this); desc.bodyB = &sBody; prepDesc.bodyState0 = PxSolverConstraintPrepDescBase::eARTICULATION; prepDesc.bodyState1 = PxSolverConstraintPrepDescBase::eSTATIC_BODY; } prepDesc.body0 = desc.bodyA; prepDesc.body1 = desc.bodyB; prepDesc.data0 = &sBodyData; prepDesc.data1 = &sBodyData; ConstraintHelper::setupSolverConstraint(prepDesc, allocator, dt, invDt, Z); } } class BlockBasedAllocator { struct AllocationPage { static const PxU32 PageSize = 32 * 1024; PxU8 mPage[PageSize]; PxU32 currentIndex; AllocationPage() : currentIndex(0) {} PxU8* allocate(const PxU32 size) { PxU32 alignedSize = (size + 15)&(~15); if ((currentIndex + alignedSize) < PageSize) { PxU8* ret = &mPage[currentIndex]; currentIndex += alignedSize; return ret; } return NULL; } }; AllocationPage* currentPage; physx::PxArray<AllocationPage*> mAllocatedBlocks; PxU32 mCurrentIndex; public: BlockBasedAllocator() : currentPage(NULL), mCurrentIndex(0) { } virtual PxU8* allocate(const PxU32 byteSize) { if (currentPage) { PxU8* data = currentPage->allocate(byteSize); if (data) return data; } if (mCurrentIndex < mAllocatedBlocks.size()) { currentPage = mAllocatedBlocks[mCurrentIndex++]; currentPage->currentIndex = 0; return currentPage->allocate(byteSize); } currentPage = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(AllocationPage), "AllocationPage"), AllocationPage)(); mAllocatedBlocks.pushBack(currentPage); mCurrentIndex = mAllocatedBlocks.size(); return currentPage->allocate(byteSize); } void release() { for (PxU32 a = 0; a < mAllocatedBlocks.size(); ++a) PX_FREE(mAllocatedBlocks[a]); mAllocatedBlocks.clear(); currentPage = NULL; mCurrentIndex = 0; } void reset() { currentPage = NULL; mCurrentIndex = 0; } virtual ~BlockBasedAllocator() { release(); } }; class ArticulationBlockAllocator : public PxConstraintAllocator { BlockBasedAllocator mConstraintAllocator; BlockBasedAllocator mFrictionAllocator[2]; PxU32 currIdx; public: ArticulationBlockAllocator() : currIdx(0) { } virtual ~ArticulationBlockAllocator() {} virtual PxU8* reserveConstraintData(const PxU32 size) { return reinterpret_cast<PxU8*>(mConstraintAllocator.allocate(size)); } virtual PxU8* reserveFrictionData(const PxU32 byteSize) { return reinterpret_cast<PxU8*>(mFrictionAllocator[currIdx].allocate(byteSize)); } void release() { currIdx = 1 - currIdx; mConstraintAllocator.release(); mFrictionAllocator[currIdx].release(); } PX_NOCOPY(ArticulationBlockAllocator) }; void solveExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache); void writeBack1D(const PxSolverConstraintDesc& desc, SolverContext&, PxSolverBodyData&, PxSolverBodyData&); void conclude1D(const PxSolverConstraintDesc& desc, SolverContext& /*cache*/); void clearExt1D(const PxSolverConstraintDesc& desc, SolverContext& cache); bool FeatherstoneArticulation::getLambda(ArticulationLoopConstraint* lConstraints, const PxU32 nbJoints, PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* jointTorque, const PxVec3& gravity, const PxU32 maxIter, const PxReal invLengthScale) { const PxReal dt = mArticulationData.getDt(); const PxReal invDt = 1.f / dt; const PxU32 totalDofs = mArticulationData.getDofs(); const PxU32 linkCount = mArticulationData.getLinkCount(); ArticulationBlockAllocator bAlloc; PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); Cm::SpatialVectorF* Z = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount, true)); Cm::SpatialVectorF* deltaV = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * linkCount, true)); PxReal* prevoiusLambdas =reinterpret_cast<PxReal*>(allocator->alloc(sizeof(PxReal)*nbJoints * 2, true)); PxReal* lambdas = cache.lambda; //this is the joint force changed caused by contact force based on impulse strength is 1 PxReal* J = cache.coefficientMatrix; PxSolverBody staticSolverBody; PxMemZero(&staticSolverBody, sizeof(PxSolverBody)); PxSolverBodyData staticSolverBodyData; PxMemZero(&staticSolverBodyData, sizeof(PxSolverBodyData)); staticSolverBodyData.maxContactImpulse = PX_MAX_F32; staticSolverBodyData.penBiasClamp = -PX_MAX_F32; staticSolverBodyData.body2World = PxTransform(PxIdentity); Dy::SolverContext context; context.Z = Z; context.deltaV = deltaV; context.doFriction = false; PxSolverConstraintDesc* desc = reinterpret_cast<PxSolverConstraintDesc*>(allocator->alloc(sizeof(PxSolverConstraintDesc) * nbJoints, true)); ArticulationSolverDesc artiDesc; PxSolverConstraintDesc* constraintDescs = reinterpret_cast<PxSolverConstraintDesc*>(allocator->alloc(sizeof(PxSolverConstraintDesc) * mArticulationData.getLinkCount()-1, true)); //run forward dynamic to calculate the lamba artiDesc.articulation = this; PxU32 acCount = 0; computeUnconstrainedVelocities(artiDesc, dt, acCount, gravity, Z, deltaV, invLengthScale); ScratchData scratchData; scratchData.motionVelocities = mArticulationData.getMotionVelocities(); scratchData.motionAccelerations = mArticulationData.getMotionAccelerations(); scratchData.coriolisVectors = mArticulationData.getCorioliseVectors(); scratchData.spatialZAVectors = mArticulationData.getSpatialZAVectors(); scratchData.jointAccelerations = mArticulationData.getJointAccelerations(); scratchData.jointVelocities = mArticulationData.getJointVelocities(); scratchData.jointPositions = mArticulationData.getJointPositions(); scratchData.jointForces = mArticulationData.getJointForces(); scratchData.externalAccels = mArticulationData.getExternalAccelerations(); //prepare constraint data PxSolverConstraintPrepDesc prepDesc; constraintPrep(lConstraints, nbJoints, Z, prepDesc, staticSolverBody, staticSolverBodyData, desc, bAlloc); for (PxU32 i = 0; i < nbJoints; ++i) { prevoiusLambdas[i] = PX_MAX_F32; } bool found = true; for (PxU32 iter = 0; iter < maxIter; ++iter) { found = true; for (PxU32 i = 0; i < nbJoints; ++i) { clearExt1D(desc[i], context); } //solve for (PxU32 itr = 0; itr < 4; itr++) { for (PxU32 i = 0; i < nbJoints; ++i) { solveExt1D(desc[i], context); } } for (PxU32 i = 0; i < nbJoints; ++i) { conclude1D(desc[i], context); } PxcFsFlushVelocity(*this, deltaV, false); for (PxU32 i = 0; i < nbJoints; ++i) { solveExt1D(desc[i], context); writeBack1D(desc[i], context, staticSolverBodyData, staticSolverBodyData); } PxReal eps = 1e-5f; for (PxU32 i = 0; i < nbJoints; ++i) { Dy::Constraint* constraint = lConstraints->constraint; Dy::ConstraintWriteback& solverOutput = mContext->getConstraintWriteBackPool()[constraint->index]; PxVec3 linearForce = solverOutput.linearImpulse * invDt; //linear force is normalize so lambda is the magnitude of linear force lambdas[i] = linearForce.magnitude() * dt; const PxReal dif = PxAbs(prevoiusLambdas[i] - lambdas[i]); if (dif > eps) found = false; prevoiusLambdas[i] = lambdas[i]; } if (found) break; //joint force PxReal* jf3 = cache.jointForce; //zero the joint force buffer PxMemZero(jf3, sizeof(PxReal)*totalDofs); for (PxU32 colInd = 0; colInd < nbJoints; ++colInd) { PxReal* col = &J[colInd * totalDofs]; for (PxU32 j = 0; j < totalDofs; ++j) { jf3[j] += col[j] * lambdas[colInd]; } } //jointTorque is M(q)*qddot + C(q,qdot)t - g(q) //jointTorque - J*lambda. for (PxU32 j = 0; j < totalDofs; ++j) { jf3[j] = jointTorque[j] - jf3[j]; } bool shouldWake = false; //reset all joint velocities/ applyCache(initialState, PxArticulationCacheFlag::eALL, shouldWake); //copy constraint torque to internal data applyCache(cache, PxArticulationCacheFlag::eFORCE, shouldWake); mArticulationData.init(); computeLinkVelocities(mArticulationData, scratchData); computeZ(mArticulationData, gravity, scratchData); computeArticulatedSpatialZ(mArticulationData, scratchData); { //Constant terms. const bool doIC = true; const PxArticulationFlags articulationFlags = mArticulationData.getArticulationFlags(); const ArticulationLink* links = mArticulationData.getLinks(); const ArticulationJointCoreData* jointDatas = mArticulationData.getJointData(); const Cm::SpatialVectorF* linkSpatialZAExtForces = scratchData.spatialZAVectors; const Cm::SpatialVectorF* linkCoriolisForces = scratchData.coriolisVectors; const PxVec3* linkRws = mArticulationData.getRw(); const Cm::UnAlignedSpatialVector* jointDofMotionMatrices = mArticulationData.getWorldMotionMatrix(); const SpatialMatrix& baseInvSpatialArticulatedInertiaW = mArticulationData.getBaseInvSpatialArticulatedInertiaW(); //Cached constant terms. const InvStIs* linkInvStIs = mArticulationData.getInvStIS(); const Cm::SpatialVectorF* jointDofIsWs = mArticulationData.getIsW(); const PxReal* jointDofQstZics = mArticulationData.getQstZIc(); //Output Cm::SpatialVectorF* linkMotionVelocities = scratchData.motionVelocities; Cm::SpatialVectorF* linkMotionAccelerations = scratchData.motionAccelerations; PxReal* jointAccelerations = scratchData.jointAccelerations; PxReal* jointVelocities = scratchData.jointVelocities; PxReal* jointNewVelocities = mArticulationData.getJointNewVelocities(); computeLinkAcceleration( doIC, dt, articulationFlags, links, linkCount, jointDatas, linkSpatialZAExtForces, linkCoriolisForces, linkRws, jointDofMotionMatrices, baseInvSpatialArticulatedInertiaW, linkInvStIs, jointDofIsWs, jointDofQstZics, linkMotionAccelerations, linkMotionVelocities, jointAccelerations, jointVelocities, jointNewVelocities); } //zero zero acceleration vector in the articulation data so that we can use this buffer to accumulated //impulse for the contacts/constraints in the PGS/TGS solvers PxMemZero(mArticulationData.getSpatialZAVectors(), sizeof(Cm::SpatialVectorF) * linkCount); PxMemZero(mArticulationData.getSolverSpatialForces(), sizeof(Cm::SpatialVectorF) * linkCount); } allocator->free(constraintDescs); allocator->free(prevoiusLambdas); allocator->free(Z); allocator->free(deltaV); allocator->free(desc); bAlloc.release(); bool shouldWake = false; //roll back to the current stage applyCache(initialState, PxArticulationCacheFlag::eALL, shouldWake); return found; } //i is the current link ID, we need to compute the row/column related to the joint i with all the other joints PxU32 computeHi(ArticulationData& data, const PxU32 linkID, PxReal* massMatrix, Cm::SpatialVectorF* f) { ArticulationLink* links = data.getLinks(); ArticulationJointCoreData& jointDatum = data.getJointData(linkID); const PxU32 totalDofs = data.getDofs(); //Hii for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { const PxU32 row = (jointDatum.jointOffset + ind)* totalDofs; const Cm::SpatialVectorF& tf = f[ind]; for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2) { const PxU32 col = jointDatum.jointOffset + ind2; const Cm::UnAlignedSpatialVector& sa = data.getWorldMotionMatrix(jointDatum.jointOffset + ind2); massMatrix[row + col] = sa.innerProduct(tf); } } PxU32 j = linkID; ArticulationLink* jLink = &links[j]; while (jLink->parent != 0) { for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { //f[ind] = data.getChildToParent(j) * f[ind]; f[ind] = FeatherstoneArticulation::translateSpatialVector(data.getRw(j), f[ind]); } //assign j to the parent link j = jLink->parent; jLink = &links[j]; //Hij ArticulationJointCoreData& pJointDatum = data.getJointData(j); for (PxU32 ind = 0; ind < pJointDatum.dof; ++ind) { const Cm::UnAlignedSpatialVector& sa = data.getWorldMotionMatrix(pJointDatum.jointOffset + ind); const PxU32 col = pJointDatum.jointOffset + ind; for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2) { const PxU32 row = (jointDatum.jointOffset + ind2)* totalDofs; Cm::SpatialVectorF& fcol = f[ind2]; massMatrix[row + col] = sa.innerProduct(fcol); } } //Hji = transpose(Hij) { for (PxU32 ind = 0; ind < pJointDatum.dof; ++ind) { const PxU32 pRow = (pJointDatum.jointOffset + ind)* totalDofs; const PxU32 col = pJointDatum.jointOffset + ind; for (PxU32 ind2 = 0; ind2 < jointDatum.dof; ++ind2) { const PxU32 pCol = jointDatum.jointOffset + ind2; const PxU32 row = (jointDatum.jointOffset + ind2) * totalDofs; massMatrix[pRow + pCol] = massMatrix[row + col]; } } } } return j; } void FeatherstoneArticulation::calculateHFixBase(PxArticulationCache& cache) { const PxU32 elementCount = mArticulationData.getDofs(); PxReal* massMatrix = cache.massMatrix; PxMemZero(massMatrix, sizeof(PxReal) * elementCount * elementCount); const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ArticulationLink* links = mArticulationData.getLinks(); const PxU32 startIndex = PxU32(linkCount - 1); Dy::SpatialMatrix* compositeSpatialInertia = reinterpret_cast<Dy::SpatialMatrix*>(allocator->alloc(sizeof(Dy::SpatialMatrix) * linkCount)); //initialize composite spatial inertial initCompositeSpatialInertia(mArticulationData, compositeSpatialInertia); Cm::SpatialVectorF F[6]; for (PxU32 i = startIndex; i > 0; --i) { ArticulationLink& link = links[i]; Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[i]; //transform current link's spatial inertia to parent's space PxVec3 rw = link.bodyCore->body2World.p - links[link.parent].bodyCore->body2World.p; FeatherstoneArticulation::translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(rw), cSpatialInertia); //compute parent's composite spatial inertia compositeSpatialInertia[link.parent] += cSpatialInertia; Dy::SpatialMatrix& tSpatialInertia = compositeSpatialInertia[i]; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(i); for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { Cm::UnAlignedSpatialVector& sa = mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind]; Cm::UnAlignedSpatialVector tmp = tSpatialInertia* sa; F[ind].top = tmp.top; F[ind].bottom = tmp.bottom; } //Hii, Hij, Hji computeHi(mArticulationData, i, massMatrix, F); } allocator->free(compositeSpatialInertia); } void FeatherstoneArticulation::calculateHFloatingBase(PxArticulationCache& cache) { const PxU32 elementCount = mArticulationData.getDofs(); PxReal* massMatrix = cache.massMatrix; PxMemZero(massMatrix, sizeof(PxReal) * elementCount * elementCount); const PxU32 linkCount = mArticulationData.getLinkCount(); PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ArticulationLink* links = mArticulationData.getLinks(); //ArticulationLinkData* linkData = mArticulationData.getLinkData(); const PxU32 startIndex = PxU32(linkCount - 1); Dy::SpatialMatrix* compositeSpatialInertia = reinterpret_cast<Dy::SpatialMatrix*>(allocator->alloc(sizeof(Dy::SpatialMatrix) * linkCount)); Cm::SpatialVectorF* F = reinterpret_cast<Cm::SpatialVectorF*>(allocator->alloc(sizeof(Cm::SpatialVectorF) * elementCount)); //initialize composite spatial inertial initCompositeSpatialInertia(mArticulationData, compositeSpatialInertia); for (PxU32 i = startIndex; i > 0; --i) { ArticulationLink& link = links[i]; Dy::SpatialMatrix cSpatialInertia = compositeSpatialInertia[i]; //transform current link's spatial inertia to parent's space PxVec3 rw = link.bodyCore->body2World.p - links[link.parent].bodyCore->body2World.p; FeatherstoneArticulation::translateInertia(FeatherstoneArticulation::constructSkewSymmetricMatrix(rw), cSpatialInertia); //compute parent's composite spatial inertia compositeSpatialInertia[link.parent] += cSpatialInertia; Dy::SpatialMatrix& tSpatialInertia = compositeSpatialInertia[i]; ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(i); Cm::SpatialVectorF* f = &F[jointDatum.jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { Cm::UnAlignedSpatialVector& sa = mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind]; Cm::UnAlignedSpatialVector tmp = tSpatialInertia* sa; f[ind].top = tmp.top; f[ind].bottom = tmp.bottom; } //Hii, Hij, Hji const PxU32 j = computeHi(mArticulationData, i, massMatrix, f); //transform F to the base link space //ArticulationLinkData& fDatum = linkData[j]; PxVec3 brw = links[j].bodyCore->body2World.p - links[0].bodyCore->body2World.p; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { f[ind] = translateSpatialVector(brw, f[ind]); } } //Ib = base link composite inertia tensor //compute transpose(F) * inv(Ib) *F Dy::SpatialMatrix invI0 = compositeSpatialInertia[0].invertInertia(); //H - transpose(F) * inv(Ib) * F; for (PxU32 row = 0; row < elementCount; ++row) { const Cm::SpatialVectorF& f = F[row]; for (PxU32 col = 0; col < elementCount; ++col) { const Cm::SpatialVectorF invIf = invI0 * F[col]; const PxReal v = f.innerProduct(invIf); const PxU32 index = row * elementCount + col; massMatrix[index] = massMatrix[index] - v; } } allocator->free(compositeSpatialInertia); allocator->free(F); } //calculate a single column of H, jointForce is equal to a single column of H void FeatherstoneArticulation::calculateMassMatrixColInv(ScratchData& scratchData) { const PxU32 linkCount = mArticulationData.getLinkCount(); Cm::SpatialVectorF* motionAccelerations = scratchData.motionAccelerations; Cm::SpatialVectorF* spatialZAForces = scratchData.spatialZAVectors; //Input PxReal* jointAccelerations = scratchData.jointAccelerations; //set base link motion acceleration to be zero because H should //be just affected by joint position/link position motionAccelerations[0] = Cm::SpatialVectorF::Zero(); spatialZAForces[0] = Cm::SpatialVectorF::Zero(); for (PxU32 linkID = 1; linkID < linkCount; ++linkID) { ArticulationLink& link = mArticulationData.getLink(linkID); ArticulationJointCoreData& jointDatum = mArticulationData.getJointData(linkID); //parent motion accelerations into child space Cm::SpatialVectorF accel = translateSpatialVector(-mArticulationData.getRw(linkID), motionAccelerations[link.parent]); const PxReal* jAcceleration = &jointAccelerations[jointDatum.jointOffset]; for (PxU32 ind = 0; ind < jointDatum.dof; ++ind) { accel.top += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].top * jAcceleration[ind]; accel.bottom += mArticulationData.mWorldMotionMatrix[jointDatum.jointOffset + ind].bottom * jAcceleration[ind]; } motionAccelerations[linkID] = accel; spatialZAForces[linkID] = mArticulationData.mWorldSpatialArticulatedInertia[linkID] * accel; } computeGeneralizedForceInv(mArticulationData, scratchData); } void FeatherstoneArticulation::getGeneralizedMassMatrixCRB(PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getGeneralizedMassMatrix() commonInit need to be called first to initialize data!"); return; } const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; if (fixBase) { calculateHFixBase(cache); } else { calculateHFloatingBase(cache); } } void FeatherstoneArticulation::getGeneralizedMassMatrix( PxArticulationCache& cache) { if (mArticulationData.getDataDirty()) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "ArticulationHelper::getGeneralizedMassMatrix() commonInit need to be called first to initialize data!"); return; } //calculate each column for mass matrix PxReal* massMatrix = cache.massMatrix; const PxU32 linkCount = mArticulationData.getLinkCount(); const PxU32 elementCount = mArticulationData.getDofs(); const PxU32 size = sizeof(PxReal) * elementCount; PxcScratchAllocator* allocator = reinterpret_cast<PxcScratchAllocator*>(cache.scratchAllocator); ScratchData scratchData; PxU8* tempMemory = allocateScratchSpatialData(allocator, linkCount, scratchData); PxReal* jointAccelerations = reinterpret_cast<PxReal*>(allocator->alloc(size)); scratchData.jointAccelerations = jointAccelerations; scratchData.jointVelocities = NULL; scratchData.externalAccels = NULL; const bool fixBase = mArticulationData.getArticulationFlags() & PxArticulationFlag::eFIX_BASE; //initialize jointAcceleration to be zero PxMemZero(jointAccelerations, size); for (PxU32 colInd = 0; colInd < elementCount; ++colInd) { PxReal* col = &massMatrix[colInd * elementCount]; scratchData.jointForces = col; //set joint acceleration 1 in the col + 1 and zero elsewhere jointAccelerations[colInd] = 1; if (fixBase) { //jointAcceleration is Q, HQ = ID(model, qdot, Q). calculateMassMatrixColInv(scratchData); } else { inverseDynamicFloatingBase(mArticulationData, PxVec3(0.f), scratchData, false); } //reset joint acceleration to be zero jointAccelerations[colInd] = 0; } allocator->free(jointAccelerations); allocator->free(tempMemory); } } //namespace Dy }
74,561
C++
32.738462
179
0.730529
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySleep.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DySleep.h" using namespace physx; // PT: TODO: refactor this, parts of the two codepaths are very similar static PX_FORCE_INLINE PxReal updateWakeCounter(PxsRigidBody* originalBody, PxReal dt, bool enableStabilization, const Cm::SpatialVector& motionVelocity, bool hasStaticTouch) { PxsBodyCore& bodyCore = originalBody->getCore(); // update the body's sleep state and const PxReal wakeCounterResetTime = 20.0f*0.02f; PxReal wc = bodyCore.wakeCounter; if (enableStabilization) { const PxTransform& body2World = bodyCore.body2World; // calculate normalized energy: kinetic energy divided by mass const PxVec3& t = bodyCore.inverseInertia; const PxVec3 inertia( t.x > 0.0f ? 1.0f / t.x : 1.0f, t.y > 0.0f ? 1.0f / t.y : 1.0f, t.z > 0.0f ? 1.0f / t.z : 1.0f); const PxVec3& sleepLinVelAcc = motionVelocity.linear; const PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular); // scale threshold by cluster factor (more contacts => higher sleep threshold) //const PxReal clusterFactor = PxReal(1u + getNumUniqueInteractions()); PxReal invMass = bodyCore.inverseMass; if (invMass == 0.0f) invMass = 1.0f; const PxReal angular = sleepAngVelAcc.multiply(sleepAngVelAcc).dot(inertia) * invMass; const PxReal linear = sleepLinVelAcc.magnitudeSquared(); const PxReal frameNormalizedEnergy = 0.5f * (angular + linear); const PxReal cf = hasStaticTouch ? PxReal(PxMin(10u, bodyCore.numCountedInteractions)) : 0.0f; const PxReal freezeThresh = cf*bodyCore.freezeThreshold; originalBody->freezeCount = PxMax(originalBody->freezeCount - dt, 0.0f); bool settled = true; PxReal accelScale = PxMin(1.0f, originalBody->accelScale + dt); if (frameNormalizedEnergy >= freezeThresh) { settled = false; originalBody->freezeCount = PXD_FREEZE_INTERVAL; } if (!hasStaticTouch) { accelScale = 1.0f; settled = false; } bool freeze = false; if (settled) { //Dampen bodies that are just about to go to sleep if (cf > 1.0f) { const PxReal sleepDamping = PXD_SLEEP_DAMPING; const PxReal sleepDampingTimesDT = sleepDamping*dt; const PxReal d = 1.0f - sleepDampingTimesDT; bodyCore.linearVelocity = bodyCore.linearVelocity * d; bodyCore.angularVelocity = bodyCore.angularVelocity * d; accelScale = accelScale * 0.75f + 0.25f*PXD_FREEZE_SCALE; } freeze = originalBody->freezeCount == 0.0f && frameNormalizedEnergy < (bodyCore.freezeThreshold * PXD_FREEZE_TOLERANCE); } originalBody->accelScale = accelScale; const PxU32 wasFrozen = originalBody->mInternalFlags & PxsRigidBody::eFROZEN; PxU16 flags; if(freeze) { //current flag isn't frozen but freeze flag raise so we need to raise the frozen flag in this frame flags = PxU16(PxsRigidBody::eFROZEN); if(!wasFrozen) flags |= PxsRigidBody::eFREEZE_THIS_FRAME; bodyCore.body2World = originalBody->getLastCCDTransform(); } else { flags = 0; if(wasFrozen) flags |= PxsRigidBody::eUNFREEZE_THIS_FRAME; } originalBody->mInternalFlags = flags; /*KS: New algorithm for sleeping when using stabilization: * Energy *this frame* must be higher than sleep threshold and accumulated energy over previous frames * must be higher than clusterFactor*energyThreshold. */ if (wc < wakeCounterResetTime * 0.5f || wc < dt) { //Accumulate energy originalBody->sleepLinVelAcc += sleepLinVelAcc; originalBody->sleepAngVelAcc += sleepAngVelAcc; //If energy this frame is high if (frameNormalizedEnergy >= bodyCore.sleepThreshold) { //Compute energy over sleep preparation time const PxReal sleepAngular = originalBody->sleepAngVelAcc.multiply(originalBody->sleepAngVelAcc).dot(inertia) * invMass; const PxReal sleepLinear = originalBody->sleepLinVelAcc.magnitudeSquared(); const PxReal normalizedEnergy = 0.5f * (sleepAngular + sleepLinear); const PxReal sleepClusterFactor = PxReal(1u + bodyCore.numCountedInteractions); // scale threshold by cluster factor (more contacts => higher sleep threshold) const PxReal threshold = sleepClusterFactor*bodyCore.sleepThreshold; //If energy over sleep preparation time is high if (normalizedEnergy >= threshold) { //Wake up //PX_ASSERT(isActive()); originalBody->resetSleepFilter(); const float factor = bodyCore.sleepThreshold == 0.0f ? 2.0f : PxMin(normalizedEnergy / threshold, 2.0f); PxReal oldWc = wc; wc = factor * 0.5f * wakeCounterResetTime + dt * (sleepClusterFactor - 1.0f); bodyCore.solverWakeCounter = wc; //if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well // notifyNotReadyForSleeping(bodyCore.nodeIndex); if (oldWc == 0.0f) originalBody->mInternalFlags |= PxsRigidBody::eACTIVATE_THIS_FRAME; return wc; } } } } else { if (wc < wakeCounterResetTime * 0.5f || wc < dt) { const PxTransform& body2World = bodyCore.body2World; // calculate normalized energy: kinetic energy divided by mass const PxVec3& t = bodyCore.inverseInertia; const PxVec3 inertia( t.x > 0.0f ? 1.0f / t.x : 1.0f, t.y > 0.0f ? 1.0f / t.y : 1.0f, t.z > 0.0f ? 1.0f / t.z : 1.0f); const PxVec3& sleepLinVelAcc = motionVelocity.linear; const PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular); originalBody->sleepLinVelAcc += sleepLinVelAcc; originalBody->sleepAngVelAcc += sleepAngVelAcc; PxReal invMass = bodyCore.inverseMass; if (invMass == 0.0f) invMass = 1.0f; const PxReal angular = originalBody->sleepAngVelAcc.multiply(originalBody->sleepAngVelAcc).dot(inertia) * invMass; const PxReal linear = originalBody->sleepLinVelAcc.magnitudeSquared(); const PxReal normalizedEnergy = 0.5f * (angular + linear); // scale threshold by cluster factor (more contacts => higher sleep threshold) const PxReal clusterFactor = PxReal(1 + bodyCore.numCountedInteractions); const PxReal threshold = clusterFactor*bodyCore.sleepThreshold; if (normalizedEnergy >= threshold) { //PX_ASSERT(isActive()); originalBody->resetSleepFilter(); const float factor = threshold == 0.0f ? 2.0f : PxMin(normalizedEnergy / threshold, 2.0f); PxReal oldWc = wc; wc = factor * 0.5f * wakeCounterResetTime + dt * (clusterFactor - 1.0f); bodyCore.solverWakeCounter = wc; PxU16 flags = 0; if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well { flags |= PxsRigidBody::eACTIVATE_THIS_FRAME; //notifyNotReadyForSleeping(bodyCore.nodeIndex); } originalBody->mInternalFlags = flags; return wc; } } } wc = PxMax(wc - dt, 0.0f); bodyCore.solverWakeCounter = wc; return wc; } void Dy::sleepCheck(PxsRigidBody* originalBody, PxReal dt, bool enableStabilization, const Cm::SpatialVector& motionVelocity, bool hasStaticTouch) { const PxReal wc = updateWakeCounter(originalBody, dt, enableStabilization, motionVelocity, hasStaticTouch); if(wc == 0.0f) { //PxsBodyCore& bodyCore = originalBody->getCore(); originalBody->mInternalFlags |= PxsRigidBody::eDEACTIVATE_THIS_FRAME; // notifyReadyForSleeping(bodyCore.nodeIndex); originalBody->resetSleepFilter(); } }
9,071
C++
37.278481
174
0.722192
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyConstraintPartition.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_CONSTRAINT_PARTITION_H #define DY_CONSTRAINT_PARTITION_H #include "DyDynamics.h" namespace physx { namespace Dy { #define MAX_NUM_PARTITIONS 32u // PT: introduced base classes to start sharing code between the SDK's and the immediate mode's versions. class RigidBodyClassificationBase { PX_NOCOPY(RigidBodyClassificationBase) PxU8* const mBodies; const PxU32 mBodySize; const PxU32 mBodyStride; const PxU32 mBodyCount; public: RigidBodyClassificationBase(PxU8* bodies, PxU32 bodyCount, PxU32 bodyStride) : mBodies (bodies), mBodySize (bodyCount*bodyStride), mBodyStride (bodyStride), mBodyCount (bodyCount) { } //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 { indexA = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyA) - mBodies) / mBodyStride; indexB = uintptr_t(reinterpret_cast<PxU8*>(desc.bodyB) - mBodies) / mBodyStride; activeA = indexA < mBodyCount; activeB = indexB < mBodyCount; bodyAProgress = desc.bodyA->solverProgress; bodyBProgress = desc.bodyB->solverProgress; return activeA && activeB; } PX_FORCE_INLINE PxU32 getStaticContactWriteIndex(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const { if(activeA) return PxU32(desc.bodyA->maxSolverNormalProgress + desc.bodyA->maxSolverFrictionProgress++); else if(activeB) return PxU32(desc.bodyB->maxSolverNormalProgress + desc.bodyB->maxSolverFrictionProgress++); return 0xffffffff; } PX_FORCE_INLINE void recordStaticConstraint(const PxSolverConstraintDesc& desc, bool activeA, bool activeB) const { if(activeA) desc.bodyA->maxSolverFrictionProgress++; if(activeB) desc.bodyB->maxSolverFrictionProgress++; } PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress) { desc.bodyA->solverProgress = bodyAProgress; desc.bodyB->solverProgress = bodyBProgress; } PX_FORCE_INLINE void storeProgress(const PxSolverConstraintDesc& desc, PxU32 bodyAProgress, PxU32 bodyBProgress, PxU16 availablePartition) { desc.bodyA->solverProgress = bodyAProgress; desc.bodyA->maxSolverNormalProgress = PxMax(desc.bodyA->maxSolverNormalProgress, availablePartition); desc.bodyB->solverProgress = bodyBProgress; desc.bodyB->maxSolverNormalProgress = PxMax(desc.bodyB->maxSolverNormalProgress, availablePartition); } }; class ExtendedRigidBodyClassificationBase { PX_NOCOPY(ExtendedRigidBodyClassificationBase) PxU8* const mBodies; const PxU32 mBodyCount; const PxU32 mBodySize; const PxU32 mStride; Dy::FeatherstoneArticulation** mArticulations; const PxU32 mNumArticulations; public: ExtendedRigidBodyClassificationBase(PxU8* bodies, PxU32 numBodies, PxU32 stride, Dy::FeatherstoneArticulation** articulations, PxU32 numArticulations) : mBodies (bodies), mBodyCount (numBodies), mBodySize (numBodies*stride), mStride (stride), mArticulations (articulations), mNumArticulations (numArticulations) { } }; struct ConstraintPartitionArgs { //Input PxU8* mBodies; PxU32 mNumBodies; PxU32 mStride; const ArticulationSolverDesc* mArticulationPtrs; PxU32 mNumArticulationPtrs; const PxSolverConstraintDesc* mContactConstraintDescriptors; PxU32 mNumContactConstraintDescriptors; //output PxSolverConstraintDesc* mOrderedContactConstraintDescriptors; PxSolverConstraintDesc* mOverflowConstraintDescriptors; PxU32 mNumDifferentBodyConstraints; PxU32 mNumSelfConstraints; PxU32 mNumStaticConstraints; PxU32 mNumOverflowConstraints; PxArray<PxU32>* mConstraintsPerPartition; //PxArray<PxU32>* mBitField; // PT: removed, unused PxU32 mMaxPartitions; bool mEnhancedDeterminism; bool mForceStaticConstraintsToSolver; }; PxU32 partitionContactConstraints(ConstraintPartitionArgs& args); void processOverflowConstraints(PxU8* bodies, PxU32 bodyStride, PxU32 numBodies, ArticulationSolverDesc* articulations, PxU32 numArticulations, PxSolverConstraintDesc* constraints, PxU32 numConstraints); } // namespace physx } #endif
6,032
C
35.125748
153
0.775696
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverExt.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_EXT_H #define DY_SOLVER_EXT_H #include "foundation/PxVec3.h" #include "foundation/PxTransform.h" #include "CmSpatialVector.h" #include "foundation/PxVecMath.h" namespace physx { class PxsRigidBody; struct PxsBodyCore; struct PxSolverBody; struct PxSolverBodyData; namespace Dy { class FeatherstoneArticulation; struct SolverConstraint1D; class SolverExtBody { public: union { const FeatherstoneArticulation* mArticulation; const PxSolverBody* mBody; }; const PxSolverBodyData* mBodyData; PxU32 mLinkIndex; SolverExtBody(const void* bodyOrArticulationOrSoftBody, const void* bodyData, PxU32 linkIndex): mBody(reinterpret_cast<const PxSolverBody*>(bodyOrArticulationOrSoftBody)), mBodyData(reinterpret_cast<const PxSolverBodyData*>(bodyData)), mLinkIndex(linkIndex) {} void getResponse(const PxVec3& linImpulse, const PxVec3& angImpulse, PxVec3& linDeltaV, PxVec3& angDeltaV, PxReal dominance) const; void getResponse(const aos::Vec3V& linImpulse, const aos::Vec3V& angImpulse, aos::Vec3V& linDeltaV, aos::Vec3V& angDeltaV, aos::FloatV dominance) const; PxReal projectVelocity(const PxVec3& linear, const PxVec3& angular) const; aos::FloatV projectVelocity(const aos::Vec3V& linear, const aos::Vec3V& angular) const; PxVec3 getLinVel() const; PxVec3 getAngVel() const; aos::Vec3V getLinVelV() const; aos::Vec3V getAngVelV() const; Cm::SpatialVectorV getVelocity() const; PxReal getCFM() const; }; } } #endif
3,206
C
33.117021
97
0.761697
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationContactPrepPF.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 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 "DyCorrelationBuffer.h" #include "DySolverConstraintExtShared.h" #include "DyFeatherstoneArticulation.h" using namespace physx; using namespace Gu; // constraint-gen only, since these use getVelocityFast methods // which aren't valid during the solver phase namespace physx { namespace Dy { bool setupFinalizeExtSolverContactsCoulomb( const PxContactBuffer& buffer, const CorrelationBuffer& c, const PxTransform& bodyFrame0, const PxTransform& bodyFrame1, PxU8* workspace, PxReal invDt, PxReal dtF32, PxReal bounceThresholdF32, const SolverExtBody& b0, const SolverExtBody& b1, PxU32 frictionCountPerPoint, PxReal invMassScale0, PxReal invInertiaScale0, PxReal invMassScale1, PxReal invInertiaScale1, PxReal restDist, PxReal ccdMaxDistance, Cm::SpatialVectorF* Z, const PxReal solverOffsetSlop) { // 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 FloatV ccdMaxSeparation = FLoad(ccdMaxDistance); const Vec3V offsetSlop = V3Load(solverOffsetSlop); PxU8* PX_RESTRICT ptr = workspace; //KS - TODO - this should all be done in SIMD to avoid LHS PxF32 maxPenBias0 = b0.mBodyData->penBiasClamp; PxF32 maxPenBias1 = b1.mBodyData->penBiasClamp; if (b0.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY) { maxPenBias0 = b0.mArticulation->getLinkMaxPenBias(b0.mLinkIndex); } if (b1.mLinkIndex != PxSolverConstraintDesc::RIGID_BODY) { maxPenBias1 = b1.mArticulation->getLinkMaxPenBias(b1.mLinkIndex); } const FloatV maxPenBias = FLoad(PxMax(maxPenBias0, maxPenBias1)/invDt); const FloatV restDistance = FLoad(restDist); const FloatV bounceThreshold = FLoad(bounceThresholdF32); const Cm::SpatialVectorV vel0 = b0.getVelocity(); const Cm::SpatialVectorV vel1 = b1.getVelocity(); const FloatV invDtV = FLoad(invDt); const FloatV pt8 = FLoad(0.8f); const FloatV invDtp8 = FMul(invDtV, pt8); const FloatV dt = FLoad(dtF32); const Vec3V bodyFrame0p = V3LoadU(bodyFrame0.p); const Vec3V bodyFrame1p = V3LoadU(bodyFrame1.p); PxPrefetchLine(c.contactID); PxPrefetchLine(c.contactID, 128); const PxU32 frictionPatchCount = c.frictionPatchCount; const PxU32 pointStride = sizeof(SolverContactPointExt); const PxU32 frictionStride = sizeof(SolverContactFrictionExt); const PxU8 pointHeaderType = DY_SC_TYPE_EXT_CONTACT; const PxU8 frictionHeaderType = DY_SC_TYPE_EXT_FRICTION; const FloatV d0 = FLoad(invMassScale0); const FloatV d1 = FLoad(invMassScale1); const FloatV angD0 = FLoad(invInertiaScale0); const FloatV angD1 = FLoad(invInertiaScale1); PxU8 flags = 0; const FloatV cfm = FLoad(PxMax(b0.getCFM(), b1.getCFM())); for(PxU32 i=0;i< frictionPatchCount;i++) { const PxU32 contactCount = c.frictionPatchContactCounts[i]; if(contactCount == 0) continue; const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start; const Vec3V normalV = aos::V3LoadA(contactBase0->normal); const Vec3V normal = V3LoadA(contactBase0->normal); const PxReal combinedRestitution = contactBase0->restitution; SolverContactCoulombHeader* PX_RESTRICT header = reinterpret_cast<SolverContactCoulombHeader*>(ptr); ptr += sizeof(SolverContactCoulombHeader); PxPrefetchLine(ptr, 128); PxPrefetchLine(ptr, 256); PxPrefetchLine(ptr, 384); const FloatV restitution = FLoad(combinedRestitution); const FloatV damping = FLoad(contactBase0->damping); header->numNormalConstr = PxU8(contactCount); header->type = pointHeaderType; //header->setRestitution(combinedRestitution); header->setDominance0(d0); header->setDominance1(d1); header->angDom0 = invInertiaScale0; header->angDom1 = invInertiaScale1; header->flags = flags; header->setNormal(normalV); const FloatV norVel0 = V3Dot(normalV, vel0.linear); const FloatV norVel1 = V3Dot(normalV, vel1.linear); 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.contacts + c.contactPatches[patch].start; PxU8* p = ptr; for(PxU32 j=0;j<count;j++) { const PxContactPoint& contact = contactBase[j]; SolverContactPointExt* PX_RESTRICT solverContact = reinterpret_cast<SolverContactPointExt*>(p); p += pointStride; setupExtSolverContact(b0, b1, d0, d1, angD0, angD1, bodyFrame0p, bodyFrame1p, normal, invDtV, invDtp8, dt, restDistance, maxPenBias, restitution, bounceThreshold, contact, *solverContact, ccdMaxSeparation, Z, vel0, vel1, cfm, offsetSlop, norVel0, norVel1, damping); } ptr = p; } } //construct all the frictions PxU8* PX_RESTRICT ptr2 = workspace; const PxF32 orthoThreshold = 0.70710678f; const PxF32 eps = 0.00001f; bool hasFriction = false; for(PxU32 i=0;i< frictionPatchCount;i++) { const PxU32 contactCount = c.frictionPatchContactCounts[i]; if(contactCount == 0) continue; SolverContactCoulombHeader* header = reinterpret_cast<SolverContactCoulombHeader*>(ptr2); header->frictionOffset = PxU16(ptr - ptr2); ptr2 += sizeof(SolverContactCoulombHeader) + header->numNormalConstr * pointStride; const PxContactPoint* contactBase0 = buffer.contacts + c.contactPatches[c.correlationListHeads[i]].start; PxVec3 normal = contactBase0->normal; const PxReal staticFriction = contactBase0->staticFriction; const bool disableStrongFriction = !!(contactBase0->materialFlags & PxMaterialFlag::eDISABLE_FRICTION); const bool haveFriction = (disableStrongFriction == 0); SolverFrictionHeader* frictionHeader = reinterpret_cast<SolverFrictionHeader*>(ptr); frictionHeader->numNormalConstr = PxTo8(c.frictionPatchContactCounts[i]); frictionHeader->numFrictionConstr = PxTo8(haveFriction ? c.frictionPatchContactCounts[i] * frictionCountPerPoint : 0); frictionHeader->flags = flags; ptr += sizeof(SolverFrictionHeader); PxF32* forceBuffer = reinterpret_cast<PxF32*>(ptr); ptr += frictionHeader->getAppliedForcePaddingSize(c.frictionPatchContactCounts[i]); PxMemZero(forceBuffer, sizeof(PxF32) * c.frictionPatchContactCounts[i]); PxPrefetchLine(ptr, 128); PxPrefetchLine(ptr, 256); PxPrefetchLine(ptr, 384); const PxVec3 t0Fallback1(0.f, -normal.z, normal.y); const PxVec3 t0Fallback2(-normal.y, normal.x, 0.f); const PxVec3 tFallback1 = orthoThreshold > PxAbs(normal.x) ? t0Fallback1 : t0Fallback2; const PxVec3 vrel = b0.getLinVel() - b1.getLinVel(); const PxVec3 t0_ = vrel - normal * (normal.dot(vrel)); const PxReal sqDist = t0_.dot(t0_); const PxVec3 tDir0 = (sqDist > eps ? t0_: tFallback1).getNormalized(); const PxVec3 tDir1 = tDir0.cross(normal); PxVec3 tFallback[2] = {tDir0, tDir1}; PxU32 ind = 0; if(haveFriction) { hasFriction = true; frictionHeader->setStaticFriction(staticFriction); frictionHeader->invMass0D0 = invMassScale0; frictionHeader->invMass1D1 = invMassScale1; frictionHeader->angDom0 = invInertiaScale0; frictionHeader->angDom1 = invInertiaScale1; frictionHeader->type = frictionHeaderType; for(PxU32 patch=c.correlationListHeads[i]; patch!=CorrelationBuffer::LIST_END; patch = c.contactPatches[patch].next) { const PxU32 count = c.contactPatches[patch].count; const PxU32 start = c.contactPatches[patch].start; const PxContactPoint* contactBase = buffer.contacts + start; PxU8* p = ptr; for(PxU32 j =0; j < count; j++) { const PxContactPoint& contact = contactBase[j]; const Vec3V ra = V3Sub(V3LoadA(contact.point), bodyFrame0p); const Vec3V rb = V3Sub(V3LoadA(contact.point), bodyFrame1p); const Vec3V targetVel = V3LoadA(contact.targetVel); const Vec3V pVRa = V3Add(vel0.linear, V3Cross(vel0.angular, ra)); const Vec3V pVRb = V3Add(vel1.linear, V3Cross(vel1.angular, rb)); //const PxVec3 vrel = pVRa - pVRb; for(PxU32 k = 0; k < frictionCountPerPoint; ++k) { SolverContactFrictionExt* PX_RESTRICT f0 = reinterpret_cast<SolverContactFrictionExt*>(p); p += frictionStride; Vec3V t0 = V3LoadU(tFallback[ind]); ind = 1 - ind; const Vec3V raXn = V3Cross(ra, t0); const Vec3V rbXn = V3Cross(rb, t0); Cm::SpatialVectorV deltaV0, deltaV1; const Cm::SpatialVectorV resp0 = createImpulseResponseVector(t0, raXn, b0); const Cm::SpatialVectorV resp1 = createImpulseResponseVector(V3Neg(t0), V3Neg(rbXn), b1); FloatV unitResponse = getImpulseResponse(b0, resp0, deltaV0, d0, angD0, b1, resp1, deltaV1, d1, angD1, reinterpret_cast<Cm::SpatialVectorV*>(Z)); FloatV tv = V3Dot(targetVel, t0); if(b0.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) tv = FAdd(tv, V3Dot(pVRa, t0)); else if(b1.mLinkIndex == PxSolverConstraintDesc::RIGID_BODY) tv = FSub(tv, V3Dot(pVRb, t0)); const FloatV recipResponse = FSel(FIsGrtr(unitResponse, FZero()), FRecip(unitResponse), FZero()); f0->raXnXYZ_velMultiplierW = V4SetW(Vec4V_From_Vec3V(resp0.angular), recipResponse); f0->rbXnXYZ_biasW = V4SetW(V4Neg(Vec4V_From_Vec3V(resp1.angular)), FZero()); f0->normalXYZ_appliedForceW = V4SetW(Vec4V_From_Vec3V(t0), FZero()); FStore(tv, &f0->targetVel); f0->linDeltaVA = deltaV0.linear; f0->angDeltaVA = deltaV0.angular; f0->linDeltaVB = deltaV1.linear; f0->angDeltaVB = deltaV1.angular; } } ptr = p; } } } //PX_ASSERT(ptr - workspace == n.solverConstraintSize); return hasFriction; } } }
11,579
C++
35.30094
149
0.727783
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1DStep.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_1D_STEP_H #define DY_SOLVER_CONSTRAINT_1D_STEP_H #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "DyArticulationUtils.h" #include "DySolverConstraintTypes.h" #include "DySolverBody.h" #include "PxConstraintDesc.h" #include "DySolverConstraintDesc.h" namespace physx { namespace Dy { struct SolverContactHeaderStep { enum DySolverContactFlags { eHAS_FORCE_THRESHOLDS = 0x1 }; PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 flags; PxU8 numNormalConstr; PxU8 numFrictionConstr; //4 PxReal angDom0; //8 PxReal angDom1; //12 PxReal invMass0; //16 Vec4V staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W; //32 PxVec3 normal; //48 PxReal maxPenBias; //52 PxReal invMass1; //56 PxReal minNormalForce; //60 PxU32 broken; //64 PxU8* frictionBrokenWritebackByte; //68 72 Sc::ShapeInteraction* shapeInteraction; //72 80 #if !PX_P64_FAMILY PxU32 pad[2]; //80 #endif PX_FORCE_INLINE FloatV getStaticFriction() const { return V4GetX(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); } PX_FORCE_INLINE FloatV getDynamicFriction() const { return V4GetY(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); } PX_FORCE_INLINE FloatV getDominance0() const { return V4GetZ(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); } PX_FORCE_INLINE FloatV getDominance1() const { return V4GetW(staticFrictionX_dynamicFrictionY_dominance0Z_dominance1W); } }; struct SolverContactPointStep { PxVec3 raXnI; PxF32 separation; PxVec3 rbXnI; PxF32 velMultiplier; PxF32 targetVelocity; PxF32 biasCoefficient; PxF32 recipResponse; PxF32 maxImpulse; }; struct SolverContactPointStepExt : public SolverContactPointStep { Vec3V linDeltaVA; Vec3V linDeltaVB; Vec3V angDeltaVA; Vec3V angDeltaVB; }; struct SolverContactFrictionStep { Vec4V normalXYZ_ErrorW; //16 Vec4V raXnI_targetVelW; Vec4V rbXnI_velMultiplierW; PxReal biasScale; PxReal appliedForce; PxReal frictionScale; PxU32 pad[1]; PX_FORCE_INLINE void setAppliedForce(const FloatV f) { FStore(f, &appliedForce); } }; struct SolverContactFrictionStepExt : public SolverContactFrictionStep { Vec3V linDeltaVA; Vec3V linDeltaVB; Vec3V angDeltaVA; Vec3V angDeltaVB; }; struct SolverConstraint1DHeaderStep { PxU8 type; // enum SolverConstraintType - must be first byte PxU8 count; // count of following 1D constraints PxU8 dominance; PxU8 breakable; // indicate whether this constraint is breakable or not PxReal linBreakImpulse; PxReal angBreakImpulse; PxReal invMass0D0; PxVec3 body0WorldOffset; PxReal invMass1D1; PxVec3 rAWorld; PxReal linearInvMassScale0; // only used by articulations PxVec3 rBWorld; PxReal angularInvMassScale0; PxReal linearInvMassScale1; // only used by articulations PxReal angularInvMassScale1; PxU32 pad[2]; //Ortho axes for body 0, recipResponse in W component PxVec4 angOrthoAxis0_recipResponseW[3]; //Ortho axes for body 1, error of body in W component PxVec4 angOrthoAxis1_Error[3]; }; PX_FORCE_INLINE void init(SolverConstraint1DHeaderStep& h, PxU8 count, bool isExtended, const PxConstraintInvMassScale& ims) { h.type = PxU8(isExtended ? DY_SC_TYPE_EXT_1D : DY_SC_TYPE_RB_1D); h.count = count; h.dominance = 0; h.linearInvMassScale0 = ims.linear0; h.angularInvMassScale0 = ims.angular0; h.linearInvMassScale1 = -ims.linear1; h.angularInvMassScale1 = -ims.angular1; } PX_ALIGN_PREFIX(16) struct SolverConstraint1DStep { public: PxVec3 lin0; //!< linear velocity projection (body 0) PxReal error; //!< constraint error term - must be scaled by biasScale. Can be adjusted at run-time PxVec3 lin1; //!< linear velocity projection (body 1) PxReal biasScale; //!< constraint constant bias scale. Constant PxVec3 ang0; //!< angular velocity projection (body 0) PxReal velMultiplier; //!< constraint velocity multiplier PxVec3 ang1; //!< angular velocity projection (body 1) PxReal velTarget; //!< Scaled target velocity of the constraint drive PxReal minImpulse; //!< Lower bound on impulse magnitude PxReal maxImpulse; //!< Upper bound on impulse magnitude PxReal appliedForce; //!< applied force to correct velocity+bias PxReal maxBias; PxU32 flags; PxReal recipResponse; //Constant. Only used for articulations; PxReal angularErrorScale; //Constant PxU32 pad; } PX_ALIGN_SUFFIX(16); struct SolverConstraint1DExtStep : public SolverConstraint1DStep { public: Cm::SpatialVectorV deltaVA; Cm::SpatialVectorV deltaVB; }; PX_FORCE_INLINE void init(SolverConstraint1DStep& c, const PxVec3& _linear0, const PxVec3& _linear1, const PxVec3& _angular0, const PxVec3& _angular1, PxReal _minImpulse, PxReal _maxImpulse) { PX_ASSERT(_linear0.isFinite()); PX_ASSERT(_linear1.isFinite()); c.lin0 = _linear0; c.lin1 = _linear1; c.ang0 = _angular0; c.ang1 = _angular1; c.minImpulse = _minImpulse; c.maxImpulse = _maxImpulse; c.flags = 0; c.appliedForce = 0; c.angularErrorScale = 1.f; } }//namespace Dy } #endif
7,199
C
31.432432
129
0.714266
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyPGS.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_PGS_H #define DY_PGS_H #include "foundation/PxPreprocessor.h" #include "foundation/PxSimpleTypes.h" namespace physx { struct PxSolverConstraintDesc; namespace Dy { struct SolverContext; // PT: using defines like we did in Gu (GU_OVERLAP_FUNC_PARAMS, etc). Additionally this gives a // convenient way to find the PGS solver methods, which are scattered in different files and use // the same function names as other functions (with a different signature). #define DY_PGS_SOLVE_METHOD_PARAMS const PxSolverConstraintDesc* desc, PxU32 constraintCount, SolverContext& cache typedef void (*SolveBlockMethod) (DY_PGS_SOLVE_METHOD_PARAMS); typedef void (*SolveWriteBackBlockMethod) (DY_PGS_SOLVE_METHOD_PARAMS); typedef void (*WriteBackBlockMethod) (DY_PGS_SOLVE_METHOD_PARAMS); } } #endif
2,523
C
44.071428
117
0.764566
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1D4.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_1D4_H #define DY_SOLVER_CONSTRAINT_1D4_H #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "DyArticulationUtils.h" #include "DySolverConstraint1D.h" namespace physx { namespace Dy { struct SolverConstraint1DHeader4 { PxU8 type; // enum SolverConstraintType - must be first byte PxU8 pad0[3]; //These counts are the max of the 4 sets of data. //When certain pairs have fewer constraints than others, they are padded with 0s so that no work is performed but //calculations are still shared (afterall, they're computationally free because we're doing 4 things at a time in SIMD) PxU32 count; PxU8 count0, count1, count2, count3; PxU8 break0, break1, break2, break3; Vec4V linBreakImpulse; Vec4V angBreakImpulse; Vec4V invMass0D0; Vec4V invMass1D1; Vec4V angD0; Vec4V angD1; Vec4V body0WorkOffsetX; Vec4V body0WorkOffsetY; Vec4V body0WorkOffsetZ; }; struct SolverConstraint1DBase4 { public: Vec4V lin0X; Vec4V lin0Y; Vec4V lin0Z; Vec4V ang0X; Vec4V ang0Y; Vec4V ang0Z; Vec4V ang0WritebackX; Vec4V ang0WritebackY; Vec4V ang0WritebackZ; Vec4V constant; Vec4V unbiasedConstant; Vec4V velMultiplier; Vec4V impulseMultiplier; Vec4V minImpulse; Vec4V maxImpulse; Vec4V appliedForce; PxU32 flags[4]; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DBase4) == 272); struct SolverConstraint1DDynamic4 : public SolverConstraint1DBase4 { Vec4V lin1X; Vec4V lin1Y; Vec4V lin1Z; Vec4V ang1X; Vec4V ang1Y; Vec4V ang1Z; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DDynamic4) == 368); } } #endif
3,304
C
30.179245
120
0.763015
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyFrictionPatch.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_FRICTION_PATCH_H #define DY_FRICTION_PATCH_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec3.h" #include "PxvConfig.h" namespace physx { namespace Dy { struct FrictionPatch { PxU8 broken; // PT: must be first byte of struct, see "frictionBrokenWritebackByte" PxU8 materialFlags; PxU16 anchorCount; PxReal restitution; PxReal staticFriction; PxReal dynamicFriction; PxVec3 body0Normal; PxVec3 body1Normal; PxVec3 body0Anchors[2]; PxVec3 body1Anchors[2]; PxQuat relativeQuat; PX_FORCE_INLINE void operator = (const FrictionPatch& other) { broken = other.broken; materialFlags = other.materialFlags; anchorCount = other.anchorCount; body0Normal = other.body0Normal; body1Normal = other.body1Normal; body0Anchors[0] = other.body0Anchors[0]; body0Anchors[1] = other.body0Anchors[1]; body1Anchors[0] = other.body1Anchors[0]; body1Anchors[1] = other.body1Anchors[1]; relativeQuat = other.relativeQuat; restitution = other.restitution; staticFriction = other.staticFriction; dynamicFriction = other.dynamicFriction; } }; //PX_COMPILE_TIME_ASSERT(sizeof(FrictionPatch)==80); } } #endif
2,894
C
34.74074
90
0.752246
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverConstraint1D.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_1D_H #define DY_SOLVER_CONSTRAINT_1D_H #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "DyArticulationUtils.h" #include "DySolverConstraintTypes.h" #include "DySolverBody.h" #include "PxConstraintDesc.h" #include "DySolverConstraintDesc.h" namespace physx { namespace Dy { // dsequeira: we should probably fork these structures for constraints and extended constraints, // since there's a few things that are used for one but not the other struct SolverConstraint1DHeader { PxU8 type; // enum SolverConstraintType - must be first byte PxU8 count; // count of following 1D constraints PxU8 dominance; PxU8 breakable; // indicate whether this constraint is breakable or not PxReal linBreakImpulse; PxReal angBreakImpulse; PxReal invMass0D0; PxVec3 body0WorldOffset; PxReal invMass1D1; PxReal linearInvMassScale0; // only used by articulations PxReal angularInvMassScale0; // only used by articulations PxReal linearInvMassScale1; // only used by articulations PxReal angularInvMassScale1; // only used by articulations }; PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DHeader) == 48); PX_ALIGN_PREFIX(16) struct SolverConstraint1D { public: PxVec3 lin0; //!< linear velocity projection (body 0) PxReal constant; //!< constraint constant term PxVec3 lin1; //!< linear velocity projection (body 1) PxReal unbiasedConstant; //!< constraint constant term without bias PxVec3 ang0; //!< angular velocity projection (body 0) PxReal velMultiplier; //!< constraint velocity multiplier PxVec3 ang1; //!< angular velocity projection (body 1) PxReal impulseMultiplier; //!< constraint impulse multiplier PxVec3 ang0Writeback; //!< unscaled angular velocity projection (body 0) PxU32 pad; PxReal minImpulse; //!< Lower bound on impulse magnitude PxReal maxImpulse; //!< Upper bound on impulse magnitude PxReal appliedForce; //!< applied force to correct velocity+bias PxU32 flags; } PX_ALIGN_SUFFIX(16); PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1D) == 96); struct SolverConstraint1DExt : public SolverConstraint1D { public: Cm::SpatialVectorV deltaVA; Cm::SpatialVectorV deltaVB; }; PX_COMPILE_TIME_ASSERT(sizeof(SolverConstraint1DExt) == 160); PX_FORCE_INLINE void init(SolverConstraint1DHeader& h, PxU8 count, bool isExtended, const PxConstraintInvMassScale& ims) { h.type = PxU8(isExtended ? DY_SC_TYPE_EXT_1D : DY_SC_TYPE_RB_1D); h.count = count; h.dominance = 0; h.linearInvMassScale0 = ims.linear0; h.angularInvMassScale0 = ims.angular0; h.linearInvMassScale1 = -ims.linear1; h.angularInvMassScale1 = -ims.angular1; } PX_FORCE_INLINE void init(SolverConstraint1D& c, const PxVec3& _linear0, const PxVec3& _linear1, const PxVec3& _angular0, const PxVec3& _angular1, PxReal _minImpulse, PxReal _maxImpulse) { PX_ASSERT(_linear0.isFinite()); PX_ASSERT(_linear1.isFinite()); c.lin0 = _linear0; c.lin1 = _linear1; c.ang0 = _angular0; c.ang1 = _angular1; c.minImpulse = _minImpulse; c.maxImpulse = _maxImpulse; c.flags = 0; c.appliedForce = 0; } PX_FORCE_INLINE bool needsNormalVel(const Px1DConstraint &c) { return c.flags & Px1DConstraintFlag::eRESTITUTION || (c.flags & Px1DConstraintFlag::eSPRING && c.flags & Px1DConstraintFlag::eACCELERATION_SPRING); } PX_FORCE_INLINE void setSolverConstants(PxReal& constant, PxReal& unbiasedConstant, PxReal& velMultiplier, PxReal& impulseMultiplier, const Px1DConstraint& c, PxReal normalVel, PxReal unitResponse, PxReal minRowResponse, PxReal erp, PxReal dt, PxReal recipdt) { PX_ASSERT(PxIsFinite(unitResponse)); PxReal recipResponse = unitResponse <= minRowResponse ? 0 : 1.0f/unitResponse; if(c.flags & Px1DConstraintFlag::eSPRING) { PxReal a = dt * dt * c.mods.spring.stiffness + dt * c.mods.spring.damping; PxReal b = dt * (c.mods.spring.damping * c.velocityTarget - c.mods.spring.stiffness * c.geometricError); if(c.flags & Px1DConstraintFlag::eACCELERATION_SPRING) { PxReal x = 1.0f/(1.0f+a); constant = unbiasedConstant = x * recipResponse * b; velMultiplier = -x * recipResponse * a; impulseMultiplier = 1.0f-x; } else { PxReal x = unitResponse == 0.f ? 0.f : 1.0f/(1.0f+a*unitResponse); constant = unbiasedConstant = x * b; velMultiplier = -x*a; impulseMultiplier = 1.0f-x; } } else { PxReal geomError = c.geometricError * erp; velMultiplier = -recipResponse; impulseMultiplier = 1.0f; if(c.flags & Px1DConstraintFlag::eRESTITUTION && -normalVel>c.mods.bounce.velocityThreshold) { unbiasedConstant = constant = recipResponse * c.mods.bounce.restitution*-normalVel; } else { // see usage of 'for internal use' in preprocessRows() constant = recipResponse * (c.velocityTarget - geomError*recipdt); unbiasedConstant = recipResponse * (c.velocityTarget - c.forInternalUse*recipdt); } } } } } #endif
6,791
C
32.294117
106
0.722721
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DyArticulationCpuGpu.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_CPUGPU_H #define DY_ARTICULATION_CPUGPU_H #include "foundation/PxSimpleTypes.h" #include "PxArticulationJointReducedCoordinate.h" #include "DyFeatherstoneArticulation.h" #define DY_ARTICULATION_MIN_RESPONSE 1e-5f #define DY_ARTICULATION_CFM 2e-4f #define DY_ARTICULATION_PGS_BIAS_COEFFICIENT 0.8f namespace physx { namespace Dy { PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParamsForceDrive (const PxReal stiffness, const PxReal damping, const PxReal dt, const PxReal unitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver) { ArticulationImplicitDriveDesc driveDesc(PxZero); const PxReal a = dt * (dt*stiffness + damping); const PxReal b = dt * (damping * targetVelocity); const PxReal x = unitResponse > 0.f ? 1.0f / (1.0f + a*unitResponse) : 0.f; const PxReal driveBiasCoefficient = stiffness * x * dt; driveDesc.driveTargetVelPlusInitialBias = (x * b) + (geomError * driveBiasCoefficient); driveDesc.driveVelMultiplier = -x * a; driveDesc.driveBiasCoefficient = driveBiasCoefficient; driveDesc.driveImpulseMultiplier = isTGSSolver ? 1.f : 1.0f - x; return driveDesc; } PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParamsAccelerationDrive (const PxReal stiffness, const PxReal damping, const PxReal dt, const PxReal recipUnitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver) { ArticulationImplicitDriveDesc driveDesc(PxZero); const PxReal a = dt * (dt*stiffness + damping); const PxReal b = dt * (damping * targetVelocity); const PxReal x = 1.0f / (1.0f + a); const PxReal driveBiasCoefficient = stiffness * x * recipUnitResponse * dt; driveDesc.driveTargetVelPlusInitialBias = (x * b * recipUnitResponse) + (geomError * driveBiasCoefficient); driveDesc.driveVelMultiplier = -x * a * recipUnitResponse; driveDesc.driveBiasCoefficient = driveBiasCoefficient; driveDesc.driveImpulseMultiplier = isTGSSolver ? 1.f : 1.0f - x; return driveDesc; } /** \brief Compute the parameters for an implicitly integrated spring. \param[in] driveType is the type of drive. \param[in] stiffness is the drive stiffness (force per unit position bias) \param[in] damping is the drive damping (force per unit velocity bias) \param[in] dt is the timestep that will be used to forward integrate the spring position bias. \param[in] unitResponse is the multiplier that converts impulse to velocity change. \param[in] recipUnitResponse is the reciprocal of unitResponse \param[in] geomError is the position bias with value (targetPos - currentPos) \param[in] targetVelocity is the target velocity of the drive. \param[in] isTGSSolver should be set true when computing implicit spring params for TGS and false for PGS. \return The implicit spring parameters. */ PX_CUDA_CALLABLE PX_FORCE_INLINE ArticulationImplicitDriveDesc computeImplicitDriveParams (const PxArticulationDriveType::Enum driveType, const PxReal stiffness, const PxReal damping, const PxReal dt, const PxReal unitResponse, const PxReal recipUnitResponse, const PxReal geomError, const PxReal targetVelocity, const bool isTGSSolver) { ArticulationImplicitDriveDesc driveDesc(PxZero); switch (driveType) { case PxArticulationDriveType::eFORCE: { driveDesc = computeImplicitDriveParamsForceDrive(stiffness, damping, dt, unitResponse, geomError, targetVelocity, isTGSSolver); } break; case PxArticulationDriveType::eACCELERATION: { driveDesc = computeImplicitDriveParamsAccelerationDrive(stiffness, damping, dt, recipUnitResponse, geomError, targetVelocity, isTGSSolver); } break; case PxArticulationDriveType::eTARGET: { driveDesc = computeImplicitDriveParamsForceDrive(1e+25f, 0.0f, dt, unitResponse, geomError, targetVelocity, isTGSSolver); } break; case PxArticulationDriveType::eVELOCITY: { driveDesc = computeImplicitDriveParamsForceDrive(0.0f, 1e+25f, dt, unitResponse, geomError, targetVelocity, isTGSSolver); } break; case PxArticulationDriveType::eNONE: { PX_ASSERT(false); } break; } return driveDesc; } /** \brief Compute the drive impulse for an implicitly integrated spring. \param[in] accumulatedDriveImpulse is the drive impulse that has accumulated since the the solver started on the current simulation step. \param[in] jointVel is the current velocity of the joint. \param[in] jointDeltaPos is the change in joint position that has accumulated since the the solver started on the current simulation step. \param[in] driveDesc is the implicit spring params. \return The impulse for the implicitly integrated spring. */ PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal computeDriveImpulse (const PxReal accumulatedDriveImpulse, const PxReal jointVel, const PxReal jointDeltaPos, const ArticulationImplicitDriveDesc& driveDesc) { const PxReal unclampedForce = accumulatedDriveImpulse * driveDesc.driveImpulseMultiplier + jointVel * driveDesc.driveVelMultiplier + driveDesc.driveTargetVelPlusInitialBias - jointDeltaPos * driveDesc.driveBiasCoefficient; return unclampedForce; } } //namespace Dy } //namespace physx #endif //DY_ARTICULATION_CPUGPU_H
6,854
C
45.006711
141
0.788882
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverContactPF.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_CONTACT_PF_H #define DY_SOLVER_CONTACT_PF_H #include "foundation/PxSimpleTypes.h" #include "foundation/PxVec3.h" #include "PxvConfig.h" #include "foundation/PxVecMath.h" namespace physx { using namespace aos; namespace Dy { struct SolverContactCoulombHeader { PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU16 frictionOffset; //4 //PxF32 restitution; PxF32 angDom0; //8 PxF32 dominance0; //12 PxF32 dominance1; //16 PX_ALIGN(16, PxVec3 normalXYZ); //28 PxF32 angDom1; //32 Sc::ShapeInteraction* shapeInteraction; //36 40 PxU8 flags; //37 41 PxU8 pad0[3]; //40 44 #if !PX_P64_FAMILY PxU32 pad1[2]; //48 #else PxU32 pad1; // 48 #endif PX_FORCE_INLINE void setDominance0(const FloatV f) {FStore(f, &dominance0);} PX_FORCE_INLINE void setDominance1(const FloatV f) {FStore(f, &dominance1);} PX_FORCE_INLINE void setNormal(const Vec3V n) {V3StoreA(n, normalXYZ);} PX_FORCE_INLINE FloatV getDominance0() const {return FLoad(dominance0);} PX_FORCE_INLINE FloatV getDominance1() const {return FLoad(dominance1);} //PX_FORCE_INLINE FloatV getRestitution() const {return FLoad(restitution);} PX_FORCE_INLINE Vec3V getNormal()const {return V3LoadA(normalXYZ);} PX_FORCE_INLINE void setDominance0(PxF32 f) { dominance0 = f; } PX_FORCE_INLINE void setDominance1(PxF32 f) { dominance1 = f;} //PX_FORCE_INLINE void setRestitution(PxF32 f) { restitution = f;} PX_FORCE_INLINE PxF32 getDominance0PxF32() const {return dominance0;} PX_FORCE_INLINE PxF32 getDominance1PxF32() const {return dominance1;} //PX_FORCE_INLINE PxF32 getRestitutionPxF32() const {return restitution;} }; PX_COMPILE_TIME_ASSERT(sizeof(SolverContactCoulombHeader) == 48); struct SolverFrictionHeader { PxU8 type; //Note: mType should be first as the solver expects a type in the first byte. PxU8 numNormalConstr; PxU8 numFrictionConstr; PxU8 flags; PxF32 staticFriction; PxF32 invMass0D0; PxF32 invMass1D1; PxF32 angDom0; PxF32 angDom1; PxU32 pad2[2]; PX_FORCE_INLINE void setStaticFriction(const FloatV f) {FStore(f, &staticFriction);} PX_FORCE_INLINE FloatV getStaticFriction() const {return FLoad(staticFriction);} PX_FORCE_INLINE void setStaticFriction(PxF32 f) {staticFriction = f;} PX_FORCE_INLINE PxF32 getStaticFrictionPxF32() const {return staticFriction;} PX_FORCE_INLINE PxU32 getAppliedForcePaddingSize() const {return sizeof(PxU32)*((4 * ((numNormalConstr + 3)/4)));} static PX_FORCE_INLINE PxU32 getAppliedForcePaddingSize(const PxU32 numConstr) {return sizeof(PxU32)*((4 * ((numConstr + 3)/4)));} }; PX_COMPILE_TIME_ASSERT(sizeof(SolverFrictionHeader) == 32); } } #endif
4,499
C
36.190082
131
0.738831
NVIDIA-Omniverse/PhysX/physx/source/lowleveldynamics/src/DySolverBody.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 DY_SOLVER_BODY_H #define DY_SOLVER_BODY_H #include "foundation/PxVec3.h" #include "foundation/PxTransform.h" #include "foundation/PxMat33.h" #include "CmSpatialVector.h" #include "solver/PxSolverDefs.h" namespace physx { class PxsRigidBody; struct PxsBodyCore; namespace Dy { // PT: TODO: make sure this is still needed / replace with V4sqrt //This method returns values of 0 when the inertia is 0. This is a bit of a hack but allows us to //represent kinematic objects' velocities in our new format PX_FORCE_INLINE PxVec3 computeSafeSqrtInertia(const PxVec3& v) { return PxVec3( v.x == 0.0f ? 0.0f : PxSqrt(v.x), v.y == 0.0f ? 0.0f : PxSqrt(v.y), v.z == 0.0f ? 0.0f : PxSqrt(v.z)); } void copyToSolverBodyData(const PxVec3& linearVelocity, const PxVec3& angularVelocity, PxReal invMass, const PxVec3& invInertia, const PxTransform& globalPose, PxReal maxDepenetrationVelocity, PxReal maxContactImpulse, PxU32 nodeIndex, PxReal reportThreshold, PxSolverBodyData& solverBodyData, PxU32 lockFlags, PxReal dt, bool gyroscopicForces); // PT: TODO: using PxsBodyCore in the interface makes us write less data to the stack for passing arguments, and we can take advantage of the class layout // (we know what is aligned or not, we know if it is safe to V4Load vectors, etc). Note that this is what we previously had, which is why PxsBodyCore was still // forward-referenced above. //void copyToSolverBodyData(PxSolverBodyData& solverBodyData, const PxsBodyCore& core, const PxU32 nodeIndex); } } #endif
3,092
C
43.826086
159
0.765201