file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2tankdrive/SnippetVehicleTankDrive.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a tank with a fully featured drivetrain comprising engine, // clutch, tank differential and gears. The snippet uses only parameters, states and // components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a drivetrain model that forwards input controls to wheel torques via a drivetrain model // that includes engine, clutch, differential and gears. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/EngineDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicle with engine drivetrain EngineDriveVehicle gVehicle; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicle a name so it can be identified in PVD. const char gVehicleName[] = "engineDrive"; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake0; //Tanks have two brake controllers: PxF32 brake1; // one brake controller for the left track and one for the right track. PxF32 thrust0; //Tanks have two thrust controllers that divert engine torque to the left and right tracks: PxF32 thrust1; // one thrust controller for the left track and one for the right track. PxF32 throttle; //Tanks are driven by an engine that requires a throttle to generate engine drive torque. PxU32 gear; //Tanks are geared and may use automatic gearing. PxF32 duration; }; const PxU32 gTargetGearCommand = 2; Command gCommands[] = { {0.5f, 0.5f, 0.0f, 0.0f, 1.0f, gTargetGearCommand, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.0f, 0.5f, 0.5f, 1.0f, gTargetGearCommand, 5.0f}, //drive forwards: symmetric forward thrust for 5 seconds {1.0f, 0.0f, 0.0f, 1.0f, 1.0f, gTargetGearCommand, 5.0f}, //sharp turn: brake on track 0, forward thrust on track 1 for 5 seconds {0.0f, 0.0f, 1.0f, -1.0f,1.0f, gTargetGearCommand, 5.0f}, //turn on spot: forward thrust on track 0, reverse thrust on track track 1 for 5 seconds {0.0f, 0.0f, 1.0f, 0.25f,1.0f, gTargetGearCommand, 5.0f}, //gentle steer: asymmetric forward thrust for 5 seconds {0.0f, 0.0f, -1.0f,-1.0f, 1.0f, gTargetGearCommand, 5.0f} //drive backwards: symmetric negative thrust for 5 seconds }; const PxReal gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gVehicle.mBaseParams); setPhysXIntegrationParams(gVehicle.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gVehicle.mPhysXParams); readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", gVehicle.mEngineDriveParams); //Set the states to default. if (!gVehicle.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, EngineDriveVehicle::eDIFFTYPE_TANKDRIVE)) { return false; } //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(0.000000000f, -0.0500000119f, -1.59399998f), PxQuat(PxIdentity)); gVehicle.setUpActor(*gScene, pose, gVehicleName); //Set the vehicle in 1st gear. gVehicle.mEngineDriveState.gearboxState.currentGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; gVehicle.mEngineDriveState.gearboxState.targetGear = gVehicle.mEngineDriveParams.gearBoxParams.neutralGear + 1; //Set the vehicle to use automatic gears. gVehicle.mTankDriveTransmissionCommandState.targetGear = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gVehicle.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; const PxReal timestep = 1.0f/60.0f; //Apply the brake, throttle and thrusts to the command state of the tank. const Command& command = gCommands[gCommandProgress]; gVehicle.mCommandState.brakes[0] = command.brake0; gVehicle.mCommandState.brakes[1] = command.brake1; gVehicle.mCommandState.nbBrakes = 2; gVehicle.mCommandState.throttle = command.throttle; gVehicle.mCommandState.steer = 0.0f; gVehicle.mTankDriveTransmissionCommandState.thrusts[0] = command.thrust0; gVehicle.mTankDriveTransmissionCommandState.thrusts[1] = command.thrust1; gVehicle.mTankDriveTransmissionCommandState.targetGear = command.gear; //Forward integrate the vehicle by a single timestep. //Apply substepping at low forward speed to improve simulation fidelity. const PxVec3 linVel = gVehicle.mPhysXState.physxActor.rigidBody->getLinearVelocity(); const PxVec3 forwardDir = gVehicle.mPhysXState.physxActor.rigidBody->getGlobalPose().q.getBasisVector2(); const PxReal forwardSpeed = linVel.dot(forwardDir); const PxU8 nbSubsteps = (forwardSpeed < 5.0f ? 3 : 1); gVehicle.mComponentSequence.setSubsteps(gVehicle.mComponentSequenceSubstepGroupHandle, nbSubsteps); gVehicle.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2TankDrive", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. EngineDrivetrainParams engineDrivetrainParams; if (!readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", engineDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { while (gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
15,721
C++
40.702918
147
0.767445
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customsuspension/CustomSuspension.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; struct CustomSuspensionParams { PxReal phase; PxReal frequency; PxReal amplitude; }; struct CustomSuspensionState { PxReal theta; PX_FORCE_INLINE void setToDefault() { PxMemZero(this, sizeof(CustomSuspensionState)); } }; void addCustomSuspensionForce (const PxReal dt, const PxVehicleSuspensionParams& suspParams, const CustomSuspensionParams& customParams, const PxVec3& groundNormal, bool isWheelOnGround, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState, PxVehicleSuspensionForce& suspForce, CustomSuspensionState& customState); class CustomSuspensionComponent : public PxVehicleComponent { public: CustomSuspensionComponent() : PxVehicleComponent() {} virtual void getDataForCustomSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, const PxReal*& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleWheelParams*& wheelParams, const PxVehicleSuspensionParams*& suspensionParams, const CustomSuspensionParams*& customSuspensionParams, const PxVehicleSuspensionComplianceParams*& suspensionComplianceParams, const PxVehicleSuspensionForceParams*& suspensionForceParams, const PxVehicleRoadGeometryState*& wheelRoadGeomStates, PxVehicleSuspensionState*& suspensionStates, CustomSuspensionState*& customSuspensionStates, PxVehicleSuspensionComplianceState*& suspensionComplianceStates, PxVehicleSuspensionForce*& suspensionForces) = 0; virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) { const PxVehicleAxleDescription* axleDescription; const PxVehicleRigidBodyParams* rigidBodyParams; const PxVehicleSuspensionStateCalculationParams* suspensionStateCalculationParams; const PxReal* steerResponseStates; const PxVehicleRigidBodyState* rigidBodyState; const PxVehicleWheelParams* wheelParams; const PxVehicleSuspensionParams* suspensionParams; const CustomSuspensionParams* customSuspensionParams; const PxVehicleSuspensionComplianceParams* suspensionComplianceParams; const PxVehicleSuspensionForceParams* suspensionForceParams; const PxVehicleRoadGeometryState* wheelRoadGeomStates; PxVehicleSuspensionState* suspensionStates; CustomSuspensionState* customSuspensionStates; PxVehicleSuspensionComplianceState* suspensionComplianceStates; PxVehicleSuspensionForce* suspensionForces; getDataForCustomSuspensionComponent(axleDescription, rigidBodyParams, suspensionStateCalculationParams, steerResponseStates, rigidBodyState, wheelParams, suspensionParams, customSuspensionParams, suspensionComplianceParams, suspensionForceParams, wheelRoadGeomStates, suspensionStates, customSuspensionStates, suspensionComplianceStates, suspensionForces); for (PxU32 i = 0; i < axleDescription->nbWheels; i++) { const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; //Update the suspension state (jounce, jounce speed) PxVehicleSuspensionStateUpdate( wheelParams[wheelId], suspensionParams[wheelId], *suspensionStateCalculationParams, suspensionForceParams[wheelId].stiffness, suspensionForceParams[wheelId].damping, steerResponseStates[wheelId], wheelRoadGeomStates[wheelId], *rigidBodyState, dt, context.frame, context.gravity, suspensionStates[wheelId]); //Update the compliance from the suspension state. PxVehicleSuspensionComplianceUpdate( suspensionParams[wheelId], suspensionComplianceParams[wheelId], suspensionStates[wheelId], suspensionComplianceStates[wheelId]); //Compute the suspension force from the suspension and compliance states. PxVehicleSuspensionForceUpdate( suspensionParams[wheelId], suspensionForceParams[wheelId], wheelRoadGeomStates[wheelId], suspensionStates[wheelId], suspensionComplianceStates[wheelId], *rigidBodyState, context.gravity, rigidBodyParams->mass, suspensionForces[wheelId]); addCustomSuspensionForce(dt, suspensionParams[wheelId], customSuspensionParams[wheelId], wheelRoadGeomStates[wheelId].plane.n, PxVehicleIsWheelOnGround(suspensionStates[wheelId]), suspensionComplianceStates[wheelId], *rigidBodyState, suspensionForces[wheelId], customSuspensionStates[wheelId]); } return true; } }; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a custom component for the suspension logic. // //See BaseVehicle for more details on the snippet code design. // class CustomSuspensionVehicle : public DirectDriveVehicle , public CustomSuspensionComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForCustomSuspensionComponent( const PxVehicleAxleDescription*& axleDescription, const PxVehicleRigidBodyParams*& rigidBodyParams, const PxVehicleSuspensionStateCalculationParams*& suspensionStateCalculationParams, const PxReal*& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, const PxVehicleWheelParams*& wheelParams, const PxVehicleSuspensionParams*& suspensionParams, const CustomSuspensionParams*& customSuspensionParams, const PxVehicleSuspensionComplianceParams*& suspensionComplianceParams, const PxVehicleSuspensionForceParams*& suspensionForceParams, const PxVehicleRoadGeometryState*& wheelRoadGeomStates, PxVehicleSuspensionState*& suspensionStates, CustomSuspensionState*& customSuspensionStates, PxVehicleSuspensionComplianceState*& suspensionComplianceStates, PxVehicleSuspensionForce*& suspensionForces) { axleDescription = &mBaseParams.axleDescription; rigidBodyParams = &mBaseParams.rigidBodyParams; suspensionStateCalculationParams = &mBaseParams.suspensionStateCalculationParams; steerResponseStates = mBaseState.steerCommandResponseStates; rigidBodyState = &mBaseState.rigidBodyState; wheelParams = mBaseParams.wheelParams; suspensionParams = mBaseParams.suspensionParams; customSuspensionParams = mCustomSuspensionParams; suspensionComplianceParams = mBaseParams.suspensionComplianceParams; suspensionForceParams = mBaseParams.suspensionForceParams; wheelRoadGeomStates = mBaseState.roadGeomStates; suspensionStates = mBaseState.suspensionStates; customSuspensionStates = mCustomSuspensionStates; suspensionComplianceStates = mBaseState.suspensionComplianceStates; suspensionForces = mBaseState.suspensionForces; } //Parameters and states of the vehicle's custom suspension. CustomSuspensionParams mCustomSuspensionParams[4]; CustomSuspensionState mCustomSuspensionStates[4]; }; }//namespace snippetvehicle2
8,809
C
41.15311
137
0.820184
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customsuspension/CustomSuspension.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "CustomSuspension.h" namespace snippetvehicle2 { void addCustomSuspensionForce (const PxReal dt, const PxVehicleSuspensionParams& suspParams, const CustomSuspensionParams& customParams, const PxVec3& groundNormal, bool isWheelOnGround, const PxVehicleSuspensionComplianceState& suspComplianceState, const PxVehicleRigidBodyState& rigidBodyState, PxVehicleSuspensionForce& suspForce, CustomSuspensionState& customState) { //Work out the oscillating force magnitude at time t. const PxF32 magnitude = (1.0f + PxCos(customParams.phase + customState.theta))*0.5f*customParams.amplitude; //Compute the custom force and torque. const PxVec3 suspDir = isWheelOnGround ? groundNormal : PxVec3(PxZero); const PxVec3 customForce = suspDir * magnitude; const PxVec3 r = rigidBodyState.pose.rotate(suspParams.suspensionAttachment.transform(suspComplianceState.suspForceAppPoint)); const PxVec3 customTorque = r.cross(customForce); //Increment the phase of the oscillator and clamp it in range (-Pi,Pi) PxReal theta = customState.theta + 2.0f*PxPi*customParams.frequency*dt; if (theta > PxPi) { theta -= 2.0f*PxPi; } else if (theta < -PxPi) { theta += 2.0f*PxPi; } customState.theta = theta; //Add the custom force to the standard suspension force. suspForce.force += customForce; suspForce.torque += customTorque; } bool CustomSuspensionVehicle::initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { if (!DirectDriveVehicle::initialize(physics, params, defaultMaterial, addPhysXBeginEndComponents)) return false; //Set the custom suspension params for all 4 wheels of the vehicle. { CustomSuspensionParams frontLeft; frontLeft.amplitude = 6000.0f*1.25f; frontLeft.frequency = 2.0f; frontLeft.phase = 0.0f; mCustomSuspensionParams[0] = frontLeft; CustomSuspensionParams frontRight; frontRight.amplitude = 6000.0f*1.25f; frontRight.frequency = 2.0f; frontRight.phase = 0.0f; mCustomSuspensionParams[1] = frontRight; CustomSuspensionParams rearLeft; rearLeft.amplitude = 6000.0f*1.25f; rearLeft.frequency = 2.0f; rearLeft.phase = PxPi * 0.5f; mCustomSuspensionParams[2] = rearLeft; CustomSuspensionParams rearRight; rearRight.amplitude = 6000.0f*1.25f; rearRight.frequency = 2.0f; rearRight.phase = PxPi * 0.5f; mCustomSuspensionParams[3] = rearRight; } //Initialise the custom suspension state. mCustomSuspensionStates[0].setToDefault(); mCustomSuspensionStates[1].setToDefault(); mCustomSuspensionStates[2].setToDefault(); mCustomSuspensionStates[3].setToDefault(); return true; } void CustomSuspensionVehicle::destroy() { DirectDriveVehicle::destroy(); } void CustomSuspensionVehicle::initComponentSequence(const bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we perform 3 updates of the suspensions, tires and wheels without recalculating //the plane underneath the wheel. This is useful for stability at low forward speeds and is //computationally cheaper than simulating the entire sequence. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(3); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. //Add an additional sinusoidal suspension force that will entice the vehicle to //perform a kind of mechanical dance. mComponentSequence.add(static_cast<CustomSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<PxVehicleTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
8,228
C++
43.722826
160
0.781842
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/SnippetKinematicSoftBody.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates how to setup softbodies. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetkinematicsoftbody/SnippetKinematicSoftBody.h" #include "../snippetkinematicsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, const PxFEMMaterial& /*femMaterial*/, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount/*, PxMaterial* tetMeshMaterial*/) { PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); //softBody->setMaterial(femMaterial); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxFEMSoftBodyMaterial* material = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); material->setDamping(0.005f); PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); materialPtr->setMaterialModel(PxFEMSoftBodyMaterialModel::eNEO_HOOKEAN); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, *material, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 0.75f; createCube(triVerts, triIndices, PxVec3(0, 0, 0), PxVec3(2.5f, 10, 2.5f)); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxVec3 position(0, 5.0f, 0); for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3& p = triVerts[i]; PxReal corr = PxSqrt(p.x*p.x + p.z*p.z); if (corr != 0) corr = PxMax(PxAbs(p.x), PxAbs(p.z)) / corr; PxReal scaling = 0.75f + 0.5f * (PxCos(1.5f*p.y) + 1.0f); p.x *= scaling * corr; p.z *= scaling * corr; p += position; } PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); PxSoftBody* softBody = createSoftBody(params, triVerts, triIndices, true); SoftBody* sb = &gSoftBodies[0]; sb->copyDeformedVerticesFromGPU(); PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); PxU32 vertexCount = sb->mSoftBody->getSimulationMesh()->getNbVertices(); PxVec4* kinematicTargets = PX_PINNED_HOST_ALLOC_T(PxVec4, cudaContextManager, vertexCount); PxVec4* positionInvMass = sb->mPositionsInvMass; for (PxU32 i = 0; i < vertexCount; ++i) { PxVec4& p = positionInvMass[i]; bool kinematic = false; if (i < triVerts.size()) { if (p.y > 9.9f) kinematic = true; if (p.y > 5 - 0.1f && p.y < 5 + 0.1f) kinematic = true; if (p.y < 0.1f) kinematic = true; } kinematicTargets[i] = PxConfigureSoftBodyKinematicTarget(p, kinematic); } PxVec4* kinematicTargetsD = PX_DEVICE_ALLOC_T(PxVec4, cudaContextManager, vertexCount); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(softBody->getSimPositionInvMassBufferD()), positionInvMass, vertexCount * sizeof(PxVec4)); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(kinematicTargetsD), kinematicTargets, vertexCount * sizeof(PxVec4)); softBody->setKinematicTargetBufferD(kinematicTargetsD, PxSoftBodyFlag::ePARTIALLY_KINEMATIC); sb->mTargetPositionsH = kinematicTargets; sb->mTargetPositionsD = kinematicTargetsD; sb->mTargetCount = vertexCount; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); // Setup rigid bodies const PxReal dynamicsDensity = 10; const PxReal boxSize = 0.5f; const PxReal spacing = 0.6f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; const PxU32 gridSizeA = 13; const PxU32 gridSizeB = 3; const PxReal initialRadius = 1.65f; const PxReal distanceJointStiffness = 500.0f; const PxReal distanceJointDamping = 0.5f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); shape->setDensityForFluid(dynamicsDensity); PxArray<PxRigidDynamic*> rigids; for (PxU32 i = 0; i < gridSizeA; ++i) for (PxU32 j = 0; j < gridSizeB; ++j) { PxReal x = PxCos((2 * PxPi*i) / gridSizeA); PxReal y = PxSin((2 * PxPi*i) / gridSizeA); PxVec3 pos = PxVec3((x*j)*spacing + x * initialRadius, 8, (y *j)*spacing + y * initialRadius); PxReal d = 0.0f; { PxReal x2 = PxCos((2 * PxPi*(i + 1)) / gridSizeA); PxReal y2 = PxSin((2 * PxPi*(i + 1)) / gridSizeA); PxVec3 pos2 = PxVec3((x2*j)*spacing + x2 * initialRadius, 8, (y2 *j)*spacing + y2 * initialRadius); d = (pos - pos2).magnitude(); } PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(pos)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); rigids.pushBack(body); if (j > 0) { PxDistanceJoint* joint = PxDistanceJointCreate(*gPhysics, rigids[rigids.size() - 2], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint->setMaxDistance(spacing); joint->setMinDistance(spacing*0.5f); joint->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint->setStiffness(distanceJointStiffness); joint->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); } if (i > 0) { PxDistanceJoint* joint = PxDistanceJointCreate(*gPhysics, rigids[rigids.size() - gridSizeB - 1], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint->setMaxDistance(d); joint->setMinDistance(d*0.5f); joint->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint->setStiffness(distanceJointStiffness); joint->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); if (i == gridSizeA - 1) { PxDistanceJoint* joint2 = PxDistanceJointCreate(*gPhysics, rigids[j], PxTransform(PxIdentity), body, PxTransform(PxIdentity)); joint2->setMaxDistance(d); joint2->setMinDistance(d*0.5f); joint2->setDistanceJointFlags(PxDistanceJointFlag::eMAX_DISTANCE_ENABLED | PxDistanceJointFlag::eMIN_DISTANCE_ENABLED | PxDistanceJointFlag::eSPRING_ENABLED); joint2->setStiffness(distanceJointStiffness); joint2->setDamping(distanceJointDamping); joint->setConstraintFlags(PxConstraintFlag::eCOLLISION_ENABLED); } } } shape->release(); } PxReal simTime = 0.0f; void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); PxCudaContextManager* cudaContextManager = sb->mCudaContextManager; //Update the kinematic targets to get some motion if (i == 0) { PxReal scaling = PxMin(0.01f, simTime * 0.1f); PxReal velocity = 1.0f; for (PxU32 j = 0; j < sb->mTargetCount; ++j) { PxVec4& target = sb->mTargetPositionsH[j]; if (target.w == 0.0f) { PxReal phase = target.y*2.0f; target.x += scaling * PxSin(velocity * simTime + phase); target.z += scaling * PxCos(velocity * simTime + phase); } } PxScopedCudaLock _lock(*cudaContextManager); cudaContextManager->getCudaContext()->memcpyHtoD(reinterpret_cast<CUdeviceptr>(sb->mTargetPositionsD), sb->mTargetPositionsH, sb->mTargetCount * sizeof(PxVec4)); } } simTime += dt; } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Kinematic Softbody done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
15,897
C++
37.400966
175
0.746619
NVIDIA-Omniverse/PhysX/physx/snippets/snippetkinematicsoftbody/SnippetKinematicSoftBody.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PHYSX_SNIPPET_KINEMATIC_SOFTBODY_H #define PHYSX_SNIPPET_KINEMATIC_SOFTBODY_H #include "PxPhysicsAPI.h" #include "cudamanager/PxCudaContextManager.h" #include "cudamanager/PxCudaContext.h" #include <vector> class SoftBody { public: SoftBody(physx::PxSoftBody* softBody, physx::PxCudaContextManager* cudaContextManager) : mSoftBody(softBody), mCudaContextManager(cudaContextManager) { mPositionsInvMass = PX_PINNED_HOST_ALLOC_T(physx::PxVec4, cudaContextManager, softBody->getCollisionMesh()->getNbVertices()); } ~SoftBody() { } void release() { if (mSoftBody) mSoftBody->release(); if (mPositionsInvMass) PX_PINNED_HOST_FREE(mCudaContextManager, mPositionsInvMass); if (mTargetPositionsH) PX_PINNED_HOST_FREE(mCudaContextManager, mTargetPositionsH); if (mTargetPositionsD) PX_DEVICE_FREE(mCudaContextManager, mTargetPositionsD); } void copyDeformedVerticesFromGPUAsync(CUstream stream) { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoHAsync(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4), stream); } void copyDeformedVerticesFromGPU() { physx::PxTetrahedronMesh* tetMesh = mSoftBody->getCollisionMesh(); physx::PxScopedCudaLock _lock(*mCudaContextManager); mCudaContextManager->getCudaContext()->memcpyDtoH(mPositionsInvMass, reinterpret_cast<CUdeviceptr>(mSoftBody->getPositionInvMassBufferD()), tetMesh->getNbVertices() * sizeof(physx::PxVec4)); } physx::PxVec4* mPositionsInvMass; physx::PxSoftBody* mSoftBody; physx::PxCudaContextManager* mCudaContextManager; physx::PxVec4* mTargetPositionsH; physx::PxVec4* mTargetPositionsD; physx::PxU32 mTargetCount; }; #endif
3,563
C
38.164835
205
0.774909
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgeometryquery/SnippetGeometryQuery.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates how to use a PxGeometryQuery for raycasts. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; enum Geom { GEOM_BOX, GEOM_SPHERE, GEOM_CAPSULE, GEOM_CONVEX, GEOM_MESH, GEOM_COUNT }; static const PxU32 gScenarioCount = GEOM_COUNT; static PxU32 gScenario = 0; static PxConvexMesh* createConvexMesh(const PxVec3* verts, const PxU32 numVerts, const PxCookingParams& params) { PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; return PxCreateConvexMesh(params, convexDesc); } static PxConvexMesh* createCylinderMesh(const PxF32 width, const PxF32 radius, const PxCookingParams& params) { PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } return createConvexMesh(points, 32, params); } static void initScene() { } static void releaseScene() { } static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static PxBoxGeometry gBoxGeom(PxVec3(1.0f, 2.0f, 0.5f)); static PxSphereGeometry gSphereGeom(1.5f); static PxCapsuleGeometry gCapsuleGeom(1.0f, 1.0f); static PxConvexMeshGeometry gConvexGeom; static PxTriangleMeshGeometry gMeshGeom; const PxGeometry& getTestGeometry() { switch(gScenario) { case GEOM_BOX: return gBoxGeom; case GEOM_SPHERE: return gSphereGeom; case GEOM_CAPSULE: return gCapsuleGeom; case GEOM_CONVEX: gConvexGeom.convexMesh = gConvexMesh; return gConvexGeom; case GEOM_MESH: gMeshGeom.triangleMesh = gTriangleMesh; gMeshGeom.scale.scale = PxVec3(2.0f); return gMeshGeom; } static PxSphereGeometry pt(0.0f); return pt; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; gConvexMesh = createCylinderMesh(3.0f, 1.0f, params); { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetGeometryQuery done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F5 to select a geometry object."); #endif } int snippetMain(int, const char*const*) { printf("GeometryQuery snippet. Use these keys:\n"); printf(" F1 to F5 - select different geom\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
6,102
C++
27.787736
111
0.727466
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgeometryquery/SnippetGeometryQueryRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern const PxGeometry& getTestGeometry(); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); static float time = 0.0f; time += 0.003f; const PxQuat qx = PxGetRotXQuat(time); const PxQuat qy = PxGetRotYQuat(time*1.7f); const PxQuat qz = PxGetRotZQuat(time*1.33f); const PxTransform pose(PxVec3(0.0f), qx*qy*qz); Snippets::startRender(sCamera); const PxGeometry& geom = getTestGeometry(); const PxU32 screenWidth = Snippets::getScreenWidth(); const PxU32 screenHeight = Snippets::getScreenHeight(); const PxVec3 camPos = sCamera->getEye(); const PxVec3 camDir = sCamera->getDir(); const PxU32 RAYTRACING_RENDER_WIDTH = 256; const PxU32 RAYTRACING_RENDER_HEIGHT = 256; const PxU32 textureWidth = RAYTRACING_RENDER_WIDTH; const PxU32 textureHeight = RAYTRACING_RENDER_HEIGHT; GLubyte* pixels = new GLubyte[textureWidth*textureHeight*4]; const float fScreenWidth = float(screenWidth)/float(RAYTRACING_RENDER_WIDTH); const float fScreenHeight = float(screenHeight)/float(RAYTRACING_RENDER_HEIGHT); GLubyte* buffer = pixels; for(PxU32 j=0;j<RAYTRACING_RENDER_HEIGHT;j++) { const PxU32 yi = PxU32(fScreenHeight*float(j)); for(PxU32 i=0;i<RAYTRACING_RENDER_WIDTH;i++) { const PxU32 xi = PxU32(fScreenWidth*float(i)); const PxVec3 dir = Snippets::computeWorldRay(xi, yi, camDir); PxGeomRaycastHit hit; if(PxGeometryQuery::raycast(camPos, dir, geom, pose, 5000.0f, PxHitFlag::eDEFAULT, 1, &hit)) { buffer[0] = 128+GLubyte(hit.normal.x*127.0f); buffer[1] = 128+GLubyte(hit.normal.y*127.0f); buffer[2] = 128+GLubyte(hit.normal.z*127.0f); buffer[3] = 255; } else { buffer[0] = 0; buffer[1] = 0; buffer[2] = 0; buffer[3] = 255; } buffer+=4; } } const GLuint texID = Snippets::CreateTexture(textureWidth, textureHeight, pixels, false); Snippets::DisplayTexture(texID, RAYTRACING_RENDER_WIDTH, 10); delete [] pixels; Snippets::ReleaseTexture(texID); // Snippets::DrawRectangle(0.0f, 1.0f, 0.0f, 1.0f, PxVec3(0.0f), PxVec3(1.0f), 1.0f, 768, 768, false, false); // PxVec3 camPos = sCamera->getEye(); // PxVec3 camDir = sCamera->getDir(); // printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); // printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); const PxVec3 color(1.0f, 0.5f, 0.25f); const PxGeometryHolder gh(geom); Snippets::renderGeoms(1, &gh, &pose, false, color); renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera(PxVec3(-1.301793f, 2.118334f, 7.282349f), PxVec3(0.209045f, -0.311980f, -0.926806f)); Snippets::setupDefault("PhysX Snippet GeometryQuery", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
5,000
C++
31.686274
117
0.73
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcontactreportccd/SnippetContactReportCCD.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates the use of simple contact reports in combination // with continuous collision detection (CCD). Furthermore, extra contact report // data will be requested. // // The snippet defines a filter shader function that enables CCD and requests // touch reports for all pairs, and a contact callback function that saves the // contact points and the actor positions at time of impact. // It configures the scene to use this filter and callback, enables CCD and // prints the number of contact points found. If rendering, it renders each // contact as a line whose length and direction are defined by the contact // impulse (the line points in the opposite direction of the impulse). In // addition, the path of the fast moving dynamic object is drawn with lines. // // **************************************************************************** #include <vector> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static PxRigidStatic* gTriangleMeshActor = NULL; static PxRigidDynamic* gSphereActor = NULL; static PxPvd* gPvd = NULL; static PxU32 gSimStepCount = 0; std::vector<PxVec3> gContactPositions; std::vector<PxVec3> gContactImpulses; std::vector<PxVec3> gContactSphereActorPositions; static PxFilterFlags contactReportFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(filterData0); PX_UNUSED(filterData1); PX_UNUSED(constantBlockSize); PX_UNUSED(constantBlock); // // Enable CCD for the pair, request contact reports for initial and CCD contacts. // Additionally, provide information per contact point and provide the actor // pose at the time of contact. // pairFlags = PxPairFlag::eCONTACT_DEFAULT | PxPairFlag::eDETECT_CCD_CONTACT | PxPairFlag::eNOTIFY_TOUCH_CCD | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_CONTACT_POINTS | PxPairFlag::eCONTACT_EVENT_POSE; return PxFilterFlag::eDEFAULT; } class ContactReportCallback: public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) { PX_UNUSED(constraints); PX_UNUSED(count); } void onWake(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onSleep(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onTrigger(PxTriggerPair* pairs, PxU32 count) { PX_UNUSED(pairs); PX_UNUSED(count); } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) {} void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) { std::vector<PxContactPairPoint> contactPoints; PxTransform spherePose(PxIdentity); PxU32 nextPairIndex = 0xffffffff; PxContactPairExtraDataIterator iter(pairHeader.extraDataStream, pairHeader.extraDataStreamSize); bool hasItemSet = iter.nextItemSet(); if (hasItemSet) nextPairIndex = iter.contactPairIndex; for(PxU32 i=0; i < nbPairs; i++) { // // Get the pose of the dynamic object at time of impact. // if (nextPairIndex == i) { if (pairHeader.actors[0]->is<PxRigidDynamic>()) spherePose = iter.eventPose->globalPose[0]; else spherePose = iter.eventPose->globalPose[1]; gContactSphereActorPositions.push_back(spherePose.p); hasItemSet = iter.nextItemSet(); if (hasItemSet) nextPairIndex = iter.contactPairIndex; } // // Get the contact points for the pair. // const PxContactPair& cPair = pairs[i]; if (cPair.events & (PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_CCD)) { PxU32 contactCount = cPair.contactCount; contactPoints.resize(contactCount); cPair.extractContacts(&contactPoints[0], contactCount); for(PxU32 j=0; j < contactCount; j++) { gContactPositions.push_back(contactPoints[j].position); gContactImpulses.push_back(contactPoints[j].impulse); } } } } }; ContactReportCallback gContactReportCallback; static void initScene() { // // Create a static triangle mesh // PxVec3 vertices[] = { PxVec3(-8.0f, 0.0f, -3.0f), PxVec3(-8.0f, 0.0f, 3.0f), PxVec3(0.0f, 0.0f, 3.0f), PxVec3(0.0f, 0.0f, -3.0f), PxVec3(-8.0f, 10.0f, -3.0f), PxVec3(-8.0f, 10.0f, 3.0f), PxVec3(0.0f, 10.0f, 3.0f), PxVec3(0.0f, 10.0f, -3.0f), }; PxU32 vertexCount = sizeof(vertices) / sizeof(vertices[0]); PxU32 triangleIndices[] = { 0, 1, 2, 0, 2, 3, 0, 5, 1, 0, 4, 5, 4, 6, 5, 4, 7, 6 }; PxU32 triangleCount = (sizeof(triangleIndices) / sizeof(triangleIndices[0])) / 3; PxTriangleMeshDesc triangleMeshDesc; triangleMeshDesc.points.count = vertexCount; triangleMeshDesc.points.data = vertices; triangleMeshDesc.points.stride = sizeof(PxVec3); triangleMeshDesc.triangles.count = triangleCount; triangleMeshDesc.triangles.data = triangleIndices; triangleMeshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale tolerances; const PxCookingParams params(tolerances); gTriangleMesh = PxCreateTriangleMesh(params, triangleMeshDesc, gPhysics->getPhysicsInsertionCallback()); if (!gTriangleMesh) return; gTriangleMeshActor = gPhysics->createRigidStatic(PxTransform(PxVec3(0.0f, 1.0f, 0.0f), PxQuat(PxHalfPi / 60.0f, PxVec3(0.0f, 1.0f, 0.0f)))); if (!gTriangleMeshActor) return; PxTriangleMeshGeometry triGeom(gTriangleMesh); PxShape* triangleMeshShape = PxRigidActorExt::createExclusiveShape(*gTriangleMeshActor, triGeom, *gMaterial); if (!triangleMeshShape) return; gScene->addActor(*gTriangleMeshActor); // // Create a fast moving sphere that will hit and bounce off the static triangle mesh 3 times // in one simulation step. // PxTransform spherePose(PxVec3(0.0f, 5.0f, 1.0f)); gContactSphereActorPositions.push_back(spherePose.p); gSphereActor = gPhysics->createRigidDynamic(spherePose); gSphereActor->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if (!gSphereActor) return; PxSphereGeometry sphereGeom(1.0f); PxShape* sphereShape = PxRigidActorExt::createExclusiveShape(*gSphereActor, sphereGeom, *gMaterial); if (!sphereShape) return; PxRigidBodyExt::updateMassAndInertia(*gSphereActor, 1.0f); PxReal velMagn = 900.0f; PxVec3 vel = PxVec3(-1.0f, -1.0f, 0.0f); vel.normalize(); vel *= velMagn; gSphereActor->setLinearVelocity(vel); gScene->addActor(*gSphereActor); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, 0, 0); sceneDesc.filterShader = contactReportFilterShader; sceneDesc.simulationEventCallback = &gContactReportCallback; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; sceneDesc.ccdMaxPasses = 4; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 1.0f); initScene(); } void stepPhysics(bool /*interactive*/) { if (!gSimStepCount) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); printf("%d contact points\n", PxU32(gContactPositions.size())); if (gSphereActor) gContactSphereActorPositions.push_back(gSphereActor->getGlobalPose().p); gSimStepCount = 1; } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gSphereActor); PX_RELEASE(gTriangleMeshActor); PX_RELEASE(gTriangleMesh); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetContactReportCCD done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,959
C++
32.723077
141
0.726709
NVIDIA-Omniverse/PhysX/physx/snippets/snippetgearjoint/SnippetGearJoint.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of gear joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createGearWithBoxes(PxPhysics& sdk, const PxBoxGeometry& boxGeom, const PxTransform& transform, PxMaterial& material, int nbShapes) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); PxMat33 m(PxIdentity); for(int i=0;i<nbShapes;i++) { const float coeff = float(i)/float(nbShapes); const float angle = PxPi * 0.5f * coeff; PxShape* shape = sdk.createShape(boxGeom, material, true); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); shape->setLocalPose(localPose); actor->attachShape(*shape); } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRevoluteJoint* gHinge0 = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); const float velocityTarget = 0.5f; const float radius0 = 5.0f; const float radius1 = 2.0f; const float extent0 = radius0 * sqrtf(2.0f); const float extent1 = radius1 * sqrtf(2.0f); const float teethLength0 = extent0 - radius0; const float teethLength1 = extent1 - radius1; const float extra = (teethLength0 + teethLength1)*0.75f; const PxBoxGeometry boxGeom0(radius0, radius0, 0.5f); const PxBoxGeometry boxGeom1(radius1, radius1, 0.25f); const PxVec3 boxPos0(0.0f, 10.0f, 0.0f); const PxVec3 boxPos1(radius0+radius1+extra, 10.0f, 0.0f); PxRigidDynamic* actor0 = createGearWithBoxes(*gPhysics, boxGeom0, PxTransform(boxPos0), *gMaterial, int(radius0)); gScene->addActor(*actor0); PxRigidDynamic* actor1= createGearWithBoxes(*gPhysics, boxGeom1, PxTransform(boxPos1), *gMaterial, int(radius1)); gScene->addActor(*actor1); const PxQuat x2z = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f)); PxRevoluteJoint* hinge0 = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos0, x2z), actor0, PxTransform(PxVec3(0.0f), x2z)); PxRevoluteJoint* hinge1 = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos1, x2z), actor1, PxTransform(PxVec3(0.0f), x2z)); hinge0->setDriveVelocity(velocityTarget); hinge0->setRevoluteJointFlag(PxRevoluteJointFlag::eDRIVE_ENABLED, true); gHinge0 = hinge0; PxGearJoint* gearJoint = PxGearJointCreate(*gPhysics, actor0, PxTransform(PxVec3(0.0f), x2z), actor1, PxTransform(PxVec3(0.0f), x2z)); gearJoint->setHinges(hinge0, hinge1); const float ratio = radius0/radius1; gearJoint->setGearRatio(ratio); } void stepPhysics(bool /*interactive*/) { if(0) { static float globalTime = 0.0f; globalTime += 1.0f/60.0f; const float velocityTarget = sinf(globalTime)*3.0f; gHinge0->setDriveVelocity(velocityTarget); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGearJoint done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
6,835
C++
33.877551
154
0.732114
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbf/SnippetPBF.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates fluid simulation using position-based dynamics // particle simulation. It creates a container and drops a body of water. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxParticleExt.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleAndDiffuseBuffer* gParticleBuffer = NULL; static bool gIsRunning = true; static bool gStep = true; PxRigidDynamic* movingWall; static void initObstacles() { PxShape* shape = gPhysics->createShape(PxCapsuleGeometry(1.0f, 2.5f), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(3.5f, 3.5f, 0), PxQuat(PxPi*-0.5f, PxVec3(0, 0, 1)))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); shape = gPhysics->createShape(PxBoxGeometry(1.0f, 1.0f, 5.0f), *gMaterial); body = gPhysics->createRigidDynamic(PxTransform(PxVec3(3.5f, 0.75f, 0))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); } static int gMaxDiffuseParticles = 0; // ----------------------------------------------------------------------------------------------------------------- static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); } int getNumDiffuseParticles() { return gMaxDiffuseParticles; } // ----------------------------------------------------------------------------------------------------------------- static void initParticles(const PxU32 numX, const PxU32 numY, const PxU32 numZ, const PxVec3& position = PxVec3(0, 0, 0), const PxReal particleSpacing = 0.2f, const PxReal fluidDensity = 1000.f, const PxU32 maxDiffuseParticles = 100000) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; const PxU32 maxParticles = numX * numY * numZ; const PxReal restOffset = 0.5f * particleSpacing / 0.6f; // Material setup PxPBDMaterial* defaultMat = gPhysics->createPBDMaterial(0.05f, 0.05f, 0.f, 0.001f, 0.5f, 0.005f, 0.01f, 0.f, 0.f); defaultMat->setViscosity(0.001f); defaultMat->setSurfaceTension(0.00704f); defaultMat->setCohesion(0.0704f); defaultMat->setVorticityConfinement(10.f); PxPBDParticleSystem *particleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager, 96); gParticleSystem = particleSystem; // General particle system setting const PxReal solidRestOffset = restOffset; const PxReal fluidRestOffset = restOffset * 0.6f; const PxReal particleMass = fluidDensity * 1.333f * 3.14159f * particleSpacing * particleSpacing * particleSpacing; particleSystem->setRestOffset(restOffset); particleSystem->setContactOffset(restOffset + 0.01f); particleSystem->setParticleContactOffset(fluidRestOffset / 0.6f); particleSystem->setSolidRestOffset(solidRestOffset); particleSystem->setFluidRestOffset(fluidRestOffset); particleSystem->enableCCD(false); particleSystem->setMaxVelocity(solidRestOffset*100.f); gScene->addActor(*particleSystem); // Diffuse particles setting PxDiffuseParticleParams dpParams; dpParams.threshold = 300.0f; dpParams.bubbleDrag = 0.9f; dpParams.buoyancy = 0.9f; dpParams.airDrag = 0.0f; dpParams.kineticEnergyWeight = 0.01f; dpParams.pressureWeight = 1.0f; dpParams.divergenceWeight = 10.f; dpParams.lifetime = 1.0f; dpParams.useAccurateVelocity = false; gMaxDiffuseParticles = maxDiffuseParticles; // Create particles and add them to the particle system const PxU32 particlePhase = particleSystem->createPhase(defaultMat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseFluid | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); PxU32* phase = cudaContextManager->allocPinnedHostBuffer<PxU32>(maxParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(maxParticles); PxReal x = position.x; PxReal y = position.y; PxReal z = position.z; for (PxU32 i = 0; i < numX; ++i) { for (PxU32 j = 0; j < numY; ++j) { for (PxU32 k = 0; k < numZ; ++k) { const PxU32 index = i * (numY * numZ) + j * numZ + k; PxVec4 pos(x, y, z, 1.0f / particleMass); phase[index] = particlePhase; positionInvMass[index] = pos; velocity[index] = PxVec4(0.0f); z += particleSpacing; } z = position.z; y += particleSpacing; } y = position.y; x += particleSpacing; } ExtGpu::PxParticleAndDiffuseBufferDesc bufferDesc; bufferDesc.maxParticles = maxParticles; bufferDesc.numActiveParticles = maxParticles; bufferDesc.maxDiffuseParticles = maxDiffuseParticles; bufferDesc.maxActiveDiffuseParticles = maxDiffuseParticles; bufferDesc.diffuseParams = dpParams; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phase; gParticleBuffer = physx::ExtGpu::PxCreateAndPopulateParticleAndDiffuseBuffer(bufferDesc, cudaContextManager); gParticleSystem->addParticleBuffer(gParticleBuffer); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phase); } PxPBDParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleAndDiffuseBuffer* getParticleBuffer() { return gParticleBuffer; } // ----------------------------------------------------------------------------------------------------------------- void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup PBF bool useLargeFluid = true; bool useMovingWall = true; const PxReal fluidDensity = 1000.0f; const PxU32 maxDiffuseParticles = useLargeFluid ? 2000000 : 100000; initParticles(50, 120 * (useLargeFluid ? 5 : 1), 30, PxVec3(-2.5f, 3.f, 0.5f), 0.1f, fluidDensity, maxDiffuseParticles); initObstacles(); // Setup container gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.0f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(-1.f, 0.f, 0.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, 1.f, 7.5f), *gMaterial)); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 0.f, -1.f, 7.5f), *gMaterial)); if (!useMovingWall) { gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(1.f, 0.f, 0.f, 7.5f), *gMaterial)); movingWall = NULL; } else { PxTransform trans = PxTransformFromPlaneEquation(PxPlane(1.f, 0.f, 0.f, 5.f)); movingWall = gPhysics->createRigidDynamic(trans); movingWall->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); PxRigidActorExt::createExclusiveShape(*movingWall, PxPlaneGeometry(), *gMaterial); gScene->addActor(*movingWall); } // Setup rigid bodies const PxReal dynamicsDensity = fluidDensity * 0.5f; const PxReal boxSize = 1.0f; const PxReal boxMass = boxSize * boxSize * boxSize * dynamicsDensity; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 3.0f, 10, 7.5f))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } // --------------------------------------------------- void stepPhysics(bool /*interactive*/) { if (gIsRunning || gStep) { gStep = false; const PxReal dt = 1.0f / 60.0f; if (movingWall) { static bool moveOut = false; const PxReal speed = 3.0f; PxTransform pose = movingWall->getGlobalPose(); if (moveOut) { pose.p.x += dt * speed; if (pose.p.x > -7.f) moveOut = false; } else { pose.p.x -= dt * speed; if (pose.p.x < -15.f) moveOut = true; } movingWall->setKinematicTarget(pose); } gScene->simulate(dt); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBFFluid done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; case 'O': gIsRunning = false; gStep = true; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,993
C++
33.466843
236
0.712999
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsdf/SnippetSDF.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates how to setup triangle meshes with SDFs. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsdf/MeshGenerator.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxTriangleMesh* createMesh(PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, PxReal sdfSpacing, PxU32 sdfSubgridSize = 6, PxSdfBitsPerSubgridPixel::Enum bitsPerSdfSubgridPixel = PxSdfBitsPerSubgridPixel::e16_BIT_PER_PIXEL) { PxTriangleMeshDesc meshDesc; meshDesc.points.count = triVerts.size(); meshDesc.triangles.count = triIndices.size() / 3; meshDesc.points.stride = sizeof(float) * 3; meshDesc.triangles.stride = sizeof(int) * 3; meshDesc.points.data = triVerts.begin(); meshDesc.triangles.data = triIndices.begin(); params.meshPreprocessParams |= PxMeshPreprocessingFlag::eENABLE_INERTIA; params.meshWeldTolerance = 1e-7f; PxSDFDesc sdfDesc; if (sdfSpacing > 0.f) { sdfDesc.spacing = sdfSpacing; sdfDesc.subgridSize = sdfSubgridSize; sdfDesc.bitsPerSubgridPixel = bitsPerSdfSubgridPixel; sdfDesc.numThreadsForSdfConstruction = 16; meshDesc.sdfDesc = &sdfDesc; } bool enableCaching = false; if (enableCaching) { const char* path = "C:\\tmp\\PhysXSDFSnippetData.dat"; bool ok = false; FILE* fp = fopen(path, "rb"); if (fp) { fclose(fp); ok = true; } if (!ok) { PxDefaultFileOutputStream stream(path); ok = PxCookTriangleMesh(params, meshDesc, stream); } if (ok) { PxDefaultFileInputData stream(path); PxTriangleMesh* triangleMesh = gPhysics->createTriangleMesh(stream); return triangleMesh; } return NULL; } else return PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } static void addInstance(const PxTransform& transform, PxTriangleMesh* mesh) { PxRigidDynamic* dyn = gPhysics->createRigidDynamic(transform); dyn->setLinearDamping(0.2f); dyn->setAngularDamping(0.1f); PxTriangleMeshGeometry geom; geom.triangleMesh = mesh; geom.scale = PxVec3(0.1f, 0.1f, 0.1f); dyn->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES, true); dyn->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); PxShape* shape = PxRigidActorExt::createExclusiveShape(*dyn, geom, *gMaterial); shape->setContactOffset(0.05f); shape->setRestOffset(0.0f); PxRigidBodyExt::updateMassAndInertia(*dyn, 100.f); gScene->addActor(*dyn); dyn->setWakeCounter(100000000.f); dyn->setSolverIterationCounts(50, 1); dyn->setMaxDepenetrationVelocity(5.f); } static void createBowls(PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createBowl(triVerts, triIndices, PxVec3(0, 4.5, 0), 6.0f, maxEdgeLength); PxTriangleMesh* mesh = createMesh(params, triVerts, triIndices, 0.05f); PxQuat rotate(PxIdentity); const PxU32 numInstances = 200; for (PxU32 i = 0; i < numInstances; ++i) { PxTransform transform(PxVec3(0, 5.f + i * 0.5f, 0), rotate); addInstance(transform, mesh); } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createBowls(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet SDF done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
8,420
C++
31.639535
145
0.745012
NVIDIA-Omniverse/PhysX/physx/snippets/snippettriggers/SnippetTriggers.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates the use of built-in triggers, and how to emulate // them with regular shapes if you need CCD or trigger-trigger notifications. // // **************************************************************************** #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; enum TriggerImpl { // Uses built-in triggers (PxShapeFlag::eTRIGGER_SHAPE). REAL_TRIGGERS, // Emulates triggers using a filter shader. Needs one reserved value in PxFilterData. FILTER_SHADER, // Emulates triggers using a filter callback. Doesn't use PxFilterData but needs user-defined way to mark a shape as a trigger. FILTER_CALLBACK, }; struct ScenarioData { TriggerImpl mImpl; bool mCCD; bool mTriggerTrigger; }; #define SCENARIO_COUNT 9 static ScenarioData gData[SCENARIO_COUNT] = { {REAL_TRIGGERS, false, false}, {FILTER_SHADER, false, false}, {FILTER_CALLBACK, false, false}, {REAL_TRIGGERS, true, false}, {FILTER_SHADER, true, false}, {FILTER_CALLBACK, true, false}, {REAL_TRIGGERS, false, true}, {FILTER_SHADER, false, true}, {FILTER_CALLBACK, false, true}, }; static PxU32 gScenario = 0; static PX_FORCE_INLINE TriggerImpl getImpl() { return gData[gScenario].mImpl; } static PX_FORCE_INLINE bool usesCCD() { return gData[gScenario].mCCD; } static PX_FORCE_INLINE bool usesTriggerTrigger() { return gData[gScenario].mTriggerTrigger; } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static bool gPause = false; static bool gOneFrame = false; // Detects a trigger using the shape's simulation filter data. See createTriggerShape() function. bool isTrigger(const PxFilterData& data) { if(data.word0!=0xffffffff) return false; if(data.word1!=0xffffffff) return false; if(data.word2!=0xffffffff) return false; if(data.word3!=0xffffffff) return false; return true; } bool isTriggerShape(PxShape* shape) { const TriggerImpl impl = getImpl(); // Detects native built-in triggers. if(impl==REAL_TRIGGERS && (shape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)) return true; // Detects our emulated triggers using the simulation filter data. See createTriggerShape() function. if(impl==FILTER_SHADER && ::isTrigger(shape->getSimulationFilterData())) return true; // Detects our emulated triggers using the simulation filter callback. See createTriggerShape() function. if(impl==FILTER_CALLBACK && shape->userData) return true; return false; } static PxFilterFlags triggersUsingFilterShader(PxFilterObjectAttributes /*attributes0*/, PxFilterData filterData0, PxFilterObjectAttributes /*attributes1*/, PxFilterData filterData1, PxPairFlags& pairFlags, const void* /*constantBlock*/, PxU32 /*constantBlockSize*/) { // printf("contactReportFilterShader\n"); PX_ASSERT(getImpl()==FILTER_SHADER); // We need to detect whether one of the shapes is a trigger. const bool isTriggerPair = isTrigger(filterData0) || isTrigger(filterData1); // If we have a trigger, replicate the trigger codepath from PxDefaultSimulationFilterShader if(isTriggerPair) { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT; return PxFilterFlag::eDEFAULT; } else { // Otherwise use the default flags for regular pairs pairFlags = PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlag::eDEFAULT; } } static PxFilterFlags triggersUsingFilterCallback(PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, PxPairFlags& pairFlags, const void* /*constantBlock*/, PxU32 /*constantBlockSize*/) { // printf("contactReportFilterShader\n"); PX_ASSERT(getImpl()==FILTER_CALLBACK); pairFlags = PxPairFlag::eCONTACT_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT|PxPairFlag::eNOTIFY_TOUCH_CCD; return PxFilterFlag::eCALLBACK; } class TriggersFilterCallback : public PxSimulationFilterCallback { virtual PxFilterFlags pairFound( PxU64 /*pairID*/, PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, const PxActor* /*a0*/, const PxShape* s0, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, const PxActor* /*a1*/, const PxShape* s1, PxPairFlags& pairFlags) PX_OVERRIDE { // printf("pairFound\n"); if(s0->userData || s1->userData) // See createTriggerShape() function { pairFlags = PxPairFlag::eTRIGGER_DEFAULT; if(usesCCD()) pairFlags |= PxPairFlag::eDETECT_CCD_CONTACT|PxPairFlag::eNOTIFY_TOUCH_CCD; } else pairFlags = PxPairFlag::eCONTACT_DEFAULT; return PxFilterFlags(); } virtual void pairLost( PxU64 /*pairID*/, PxFilterObjectAttributes /*attributes0*/, PxFilterData /*filterData0*/, PxFilterObjectAttributes /*attributes1*/, PxFilterData /*filterData1*/, bool /*objectRemoved*/) PX_OVERRIDE { // printf("pairLost\n"); } virtual bool statusChange(PxU64& /*pairID*/, PxPairFlags& /*pairFlags*/, PxFilterFlags& /*filterFlags*/) PX_OVERRIDE { // printf("statusChange\n"); return false; } }gTriggersFilterCallback; class ContactReportCallback: public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* /*constraints*/, PxU32 /*count*/) PX_OVERRIDE { printf("onConstraintBreak\n"); } void onWake(PxActor** /*actors*/, PxU32 /*count*/) PX_OVERRIDE { printf("onWake\n"); } void onSleep(PxActor** /*actors*/, PxU32 /*count*/) PX_OVERRIDE { printf("onSleep\n"); } void onTrigger(PxTriggerPair* pairs, PxU32 count) PX_OVERRIDE { // printf("onTrigger: %d trigger pairs\n", count); while(count--) { const PxTriggerPair& current = *pairs++; if(current.status & PxPairFlag::eNOTIFY_TOUCH_FOUND) printf("Shape is entering trigger volume\n"); if(current.status & PxPairFlag::eNOTIFY_TOUCH_LOST) printf("Shape is leaving trigger volume\n"); } } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) PX_OVERRIDE { printf("onAdvance\n"); } void onContact(const PxContactPairHeader& /*pairHeader*/, const PxContactPair* pairs, PxU32 count) PX_OVERRIDE { // printf("onContact: %d pairs\n", count); while(count--) { const PxContactPair& current = *pairs++; // The reported pairs can be trigger pairs or not. We only enabled contact reports for // trigger pairs in the filter shader, so we don't need to do further checks here. In a // real-world scenario you would probably need a way to tell whether one of the shapes // is a trigger or not. You could e.g. reuse the PxFilterData like we did in the filter // shader, or maybe use the shape's userData to identify triggers, or maybe put triggers // in a hash-set and test the reported shape pointers against it. Many options here. if(current.events & (PxPairFlag::eNOTIFY_TOUCH_FOUND|PxPairFlag::eNOTIFY_TOUCH_CCD)) printf("Shape is entering trigger volume\n"); if(current.events & PxPairFlag::eNOTIFY_TOUCH_LOST) printf("Shape is leaving trigger volume\n"); if(isTriggerShape(current.shapes[0]) && isTriggerShape(current.shapes[1])) printf("Trigger-trigger overlap detected\n"); } } }; static ContactReportCallback gContactReportCallback; static PxShape* createTriggerShape(const PxGeometry& geom, bool isExclusive) { const TriggerImpl impl = getImpl(); PxShape* shape = nullptr; if(impl==REAL_TRIGGERS) { const PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eTRIGGER_SHAPE; shape = gPhysics->createShape(geom, *gMaterial, isExclusive, shapeFlags); } else if(impl==FILTER_SHADER) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSIMULATION_SHAPE; shape = gPhysics->createShape(geom, *gMaterial, isExclusive, shapeFlags); // For this method to work, you need a way to mark shapes as triggers without using PxShapeFlag::eTRIGGER_SHAPE // (so that trigger-trigger pairs are reported), and without calling a PxShape function (so that the data is // available in a filter shader). // // One way is to reserve a special PxFilterData value/mask for triggers. It may not always be possible depending // on how you otherwise use the filter data). const PxFilterData triggerFilterData(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); shape->setSimulationFilterData(triggerFilterData); } else if(impl==FILTER_CALLBACK) { // We will have access to shape pointers in the filter callback so we just mark triggers in an arbitrary way here, // for example using the shape's userData. shape = gPhysics->createShape(geom, *gMaterial, isExclusive); shape->userData = shape; // Arbitrary rule: it's a trigger if non null } return shape; } static void createDefaultScene() { const bool ccd = usesCCD(); // Create trigger shape { const PxVec3 halfExtent(10.0f, ccd ? 0.01f : 1.0f, 10.0f); PxShape* shape = createTriggerShape(PxBoxGeometry(halfExtent), false); if(shape) { PxRigidStatic* body = gPhysics->createRigidStatic(PxTransform(0.0f, 10.0f, 0.0f)); body->attachShape(*shape); gScene->addActor(*body); shape->release(); } } // Create falling rigid body { const PxVec3 halfExtent(ccd ? 0.1f : 1.0f); PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(0.0f, ccd ? 30.0f : 20.0f, 0.0f)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 1.0f); gScene->addActor(*body); shape->release(); if(ccd) { body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); body->setLinearVelocity(PxVec3(0.0f, -140.0f, 0.0f)); } } } static void createTriggerTriggerScene() { struct Local { static void createSphereActor(const PxVec3& pos, const PxVec3& linVel) { PxShape* sphereShape = gPhysics->createShape(PxSphereGeometry(1.0f), *gMaterial, false); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(pos)); body->attachShape(*sphereShape); PxShape* triggerShape = createTriggerShape(PxSphereGeometry(4.0f), true); body->attachShape(*triggerShape); const bool isTriggershape = triggerShape->getFlags() & PxShapeFlag::eTRIGGER_SHAPE; if(!isTriggershape) triggerShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); PxRigidBodyExt::updateMassAndInertia(*body, 1.0f); if(!isTriggershape) triggerShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true); gScene->addActor(*body); sphereShape->release(); triggerShape->release(); body->setLinearVelocity(linVel); } }; Local::createSphereActor(PxVec3(-5.0f, 1.0f, 0.0f), PxVec3( 1.0f, 0.0f, 0.0f)); Local::createSphereActor(PxVec3( 5.0f, 1.0f, 0.0f), PxVec3(-1.0f, 0.0f, 0.0f)); } static void initScene() { const TriggerImpl impl = getImpl(); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); // sceneDesc.flags &= ~PxSceneFlag::eENABLE_PCM; sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.simulationEventCallback = &gContactReportCallback; if(impl==REAL_TRIGGERS) { sceneDesc.filterShader = PxDefaultSimulationFilterShader; printf("- Using built-in triggers.\n"); } else if(impl==FILTER_SHADER) { sceneDesc.filterShader = triggersUsingFilterShader; printf("- Using regular shapes emulating triggers with a filter shader.\n"); } else if(impl==FILTER_CALLBACK) { sceneDesc.filterShader = triggersUsingFilterCallback; sceneDesc.filterCallback = &gTriggersFilterCallback; printf("- Using regular shapes emulating triggers with a filter callback.\n"); } if(usesCCD()) { sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; printf("- Using CCD.\n"); } else { printf("- Using no CCD.\n"); } gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); if(usesTriggerTrigger()) createTriggerTriggerScene(); else createDefaultScene(); } static void releaseScene() { PX_RELEASE(gScene); } void stepPhysics(bool /*interactive*/) { if(gPause && !gOneFrame) return; gOneFrame = false; if(gScene) { // printf("Update...\n"); gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } } void initPhysics(bool /*interactive*/) { printf("Press keys F1 to F9 to select a scenario.\n"); gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxInitExtensions(*gPhysics,gPvd); const PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); gMaterial = gPhysics->createMaterial(1.0f, 1.0f, 0.0f); initScene(); } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetTriggers done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } if(gScene) { if(key>=1 && key<=SCENARIO_COUNT) { gScenario = key-1; releaseScene(); initScene(); } if(key=='r' || key=='R') { releaseScene(); initScene(); } } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); for(PxU32 i=0; i<250; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
16,213
C++
29.825095
128
0.719546
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmassproperties/SnippetMassProperties.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates different ways of setting mass for rigid bodies. // // It creates 5 snowmen with different mass properties: // - massless with a weight at the bottom // - only the mass of the lowest snowball // - the mass of all the snowballs // - the whole mass but with a low center of gravity // - manual setup of masses // // The different mass properties can be visually inspected by firing a rigid // ball towards each snowman using the space key. // // For more details, please consult the "Rigid Body Dynamics" section of the // user guide. // // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; // create a dynamic ball to throw at the snowmen. static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static PxRigidDynamic* createSnowMan(const PxTransform& pos, PxU32 mode) { PxRigidDynamic* snowmanActor = gPhysics->createRigidDynamic(PxTransform(pos)); if(!snowmanActor) { printf("create snowman actor failed"); return NULL; } PxShape* armL = NULL; PxShape* armR = NULL; switch(mode%5) { case 0: // with a weight at the bottom { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.2), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,-.29,0))); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,10); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); } break; case 1: // only considering lowest shape mass { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); } break; case 2: // considering whole mass { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); } break; case 3: // considering whole mass with low COM { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); const PxVec3 localPos = PxVec3(0,-.5,0); PxRigidBodyExt::updateMassAndInertia(*snowmanActor,1,&localPos); } break; case 4: // setting up mass properties manually { PxShape* shape = NULL; shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.5), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.4), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,.6,0))); shape = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxSphereGeometry(.3), *gMaterial); if(!shape) printf("creating snowman shape failed"); shape->setLocalPose(PxTransform(PxVec3(0,1.1,0))); armL = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armL) printf("creating snowman shape failed"); armL->setLocalPose(PxTransform(PxVec3(-.4,.7,0))); armR = PxRigidActorExt::createExclusiveShape(*snowmanActor, PxCapsuleGeometry(.1,.1), *gMaterial); if(!armR) printf("creating snowman shape failed"); armR->setLocalPose(PxTransform(PxVec3( .4,.7,0))); snowmanActor->setMass(1); snowmanActor->setCMassLocalPose(PxTransform(PxVec3(0,-.5,0))); snowmanActor->setMassSpaceInertiaTensor(PxVec3(.05,100,100)); } break; default: break; } gScene->addActor(*snowmanActor); return snowmanActor; } static void createSnowMen() { PxU32 numSnowmen = 5; for(PxU32 i=0; i<numSnowmen; i++) { PxVec3 pos(i * 2.5f,1,-8); createSnowMan(PxTransform(pos), i); } } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSnowMen(); } void stepPhysics(bool /*interactive*/) { gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMassProperties done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(0.1f), camera.rotate(PxVec3(0,0,-1))*20); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,305
C++
34.463977
120
0.721333
NVIDIA-Omniverse/PhysX/physx/snippets/snippettrianglemeshcreate/SnippetTriangleMeshCreate.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates the possibilities of triangle mesh creation. // // The snippet creates triangle mesh with a different cooking settings // and shows how these settings affect the triangle mesh creation speed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; float rand(float loVal, float hiVal) { return loVal + float(rand()/float(RAND_MAX))*(hiVal - loVal); } PxU32 rand(PxU32 loVal, PxU32 hiVal) { return loVal + PxU32(rand()%(hiVal - loVal)); } void indexToCoord(PxU32& x, PxU32& z, PxU32 index, PxU32 w) { x = index % w; z = index / w; } // Creates a random terrain data. void createRandomTerrain(const PxVec3& origin, PxU32 numRows, PxU32 numColumns, PxReal cellSizeRow, PxReal cellSizeCol, PxReal heightScale, PxVec3*& vertices, PxU32*& indices) { PxU32 numX = (numColumns + 1); PxU32 numZ = (numRows + 1); PxU32 numVertices = numX*numZ; PxU32 numTriangles = numRows*numColumns * 2; if (vertices == NULL) vertices = new PxVec3[numVertices]; if (indices == NULL) indices = new PxU32[numTriangles * 3]; PxU32 currentIdx = 0; for (PxU32 i = 0; i <= numRows; i++) { for (PxU32 j = 0; j <= numColumns; j++) { PxVec3 v(origin.x + PxReal(j)*cellSizeRow, origin.y, origin.z + PxReal(i)*cellSizeCol); vertices[currentIdx++] = v; } } currentIdx = 0; for (PxU32 i = 0; i < numRows; i++) { for (PxU32 j = 0; j < numColumns; j++) { PxU32 base = (numColumns + 1)*i + j; indices[currentIdx++] = base + 1; indices[currentIdx++] = base; indices[currentIdx++] = base + numColumns + 1; indices[currentIdx++] = base + numColumns + 2; indices[currentIdx++] = base + 1; indices[currentIdx++] = base + numColumns + 1; } } for (PxU32 i = 0; i < numVertices; i++) { PxVec3& v = vertices[i]; v.y += heightScale * rand(-1.0f, 1.0f); } } // Setup common cooking params void setupCommonCookingParams(PxCookingParams& params, bool skipMeshCleanup, bool skipEdgeData) { // we suppress the triangle mesh remap table computation to gain some speed, as we will not need it // in this snippet params.suppressTriangleMeshRemapTable = true; // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. The input mesh must be valid. // The following conditions are true for a valid triangle mesh : // 1. There are no duplicate vertices(within specified vertexWeldTolerance.See PxCookingParams::meshWeldTolerance) // 2. There are no large triangles(within specified PxTolerancesScale.) // It is recommended to run a separate validation check in debug/checked builds, see below. if (!skipMeshCleanup) params.meshPreprocessParams &= ~static_cast<PxMeshPreprocessingFlags>(PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH); else params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; // If eDISABLE_ACTIVE_EDGES_PRECOMPUTE is set, the cooking does not compute the active (convex) edges, and instead // marks all edges as active. This makes cooking faster but can slow down contact generation. This flag may change // the collision behavior, as all edges of the triangle mesh will now be considered active. if (!skipEdgeData) params.meshPreprocessParams &= ~static_cast<PxMeshPreprocessingFlags>(PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE); else params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; } // Creates a triangle mesh using BVH33 midphase with different settings. void createBV33TriangleMesh(PxU32 numVertices, const PxVec3* vertices, PxU32 numTriangles, const PxU32* indices, bool skipMeshCleanup, bool skipEdgeData, bool inserted, bool cookingPerformance, bool meshSizePerfTradeoff) { PxU64 startTime = SnippetUtils::getCurrentTimeCounterValue(); PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = numTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale scale; PxCookingParams params(scale); // Create BVH33 midphase params.midphaseDesc = PxMeshMidPhase::eBVH33; // setup common cooking params setupCommonCookingParams(params, skipMeshCleanup, skipEdgeData); // The COOKING_PERFORMANCE flag for BVH33 midphase enables a fast cooking path at the expense of somewhat lower quality BVH construction. if (cookingPerformance) params.midphaseDesc.mBVH33Desc.meshCookingHint = PxMeshCookingHint::eCOOKING_PERFORMANCE; else params.midphaseDesc.mBVH33Desc.meshCookingHint = PxMeshCookingHint::eSIM_PERFORMANCE; // If meshSizePerfTradeoff is set to true, smaller mesh cooked mesh is produced. The mesh size/performance trade-off // is controlled by setting the meshSizePerformanceTradeOff from 0.0f (smaller mesh) to 1.0f (larger mesh). if(meshSizePerfTradeoff) { params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff = 0.0f; } else { // using the default value params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff = 0.55f; } #if defined(PX_CHECKED) || defined(PX_DEBUG) // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. // We should check the validity of provided triangles in debug/checked builds though. if (skipMeshCleanup) { PX_ASSERT(PxValidateTriangleMesh(params, meshDesc)); } #endif // DEBUG PxTriangleMesh* triMesh = NULL; PxU32 meshSize = 0; // The cooked mesh may either be saved to a stream for later loading, or inserted directly into PxPhysics. if (inserted) { triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } else { PxDefaultMemoryOutputStream outBuffer; PxCookTriangleMesh(params, meshDesc, outBuffer); PxDefaultMemoryInputData stream(outBuffer.getData(), outBuffer.getSize()); triMesh = gPhysics->createTriangleMesh(stream); meshSize = outBuffer.getSize(); } // Print the elapsed time for comparison PxU64 stopTime = SnippetUtils::getCurrentTimeCounterValue(); float elapsedTime = SnippetUtils::getElapsedTimeInMilliseconds(stopTime - startTime); printf("\t -----------------------------------------------\n"); printf("\t Create triangle mesh with %d triangles: \n",numTriangles); cookingPerformance ? printf("\t\t Cooking performance on\n") : printf("\t\t Cooking performance off\n"); inserted ? printf("\t\t Mesh inserted on\n") : printf("\t\t Mesh inserted off\n"); !skipEdgeData ? printf("\t\t Precompute edge data on\n") : printf("\t\t Precompute edge data off\n"); !skipMeshCleanup ? printf("\t\t Mesh cleanup on\n") : printf("\t\t Mesh cleanup off\n"); printf("\t\t Mesh size/performance trade-off: %f \n", double(params.midphaseDesc.mBVH33Desc.meshSizePerformanceTradeOff)); printf("\t Elapsed time in ms: %f \n", double(elapsedTime)); if(!inserted) { printf("\t Mesh size: %d \n", meshSize); } triMesh->release(); } // Creates a triangle mesh using BVH34 midphase with different settings. void createBV34TriangleMesh(PxU32 numVertices, const PxVec3* vertices, PxU32 numTriangles, const PxU32* indices, bool skipMeshCleanup, bool skipEdgeData, bool inserted, const PxU32 numTrisPerLeaf) { PxU64 startTime = SnippetUtils::getCurrentTimeCounterValue(); PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVertices; meshDesc.points.data = vertices; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = numTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = 3 * sizeof(PxU32); PxTolerancesScale scale; PxCookingParams params(scale); // Create BVH34 midphase params.midphaseDesc = PxMeshMidPhase::eBVH34; // setup common cooking params setupCommonCookingParams(params, skipMeshCleanup, skipEdgeData); // Cooking mesh with less triangles per leaf produces larger meshes with better runtime performance // and worse cooking performance. Cooking time is better when more triangles per leaf are used. params.midphaseDesc.mBVH34Desc.numPrimsPerLeaf = numTrisPerLeaf; #if defined(PX_CHECKED) || defined(PX_DEBUG) // If DISABLE_CLEAN_MESH is set, the mesh is not cleaned during the cooking. // We should check the validity of provided triangles in debug/checked builds though. if (skipMeshCleanup) { PX_ASSERT(PxValidateTriangleMesh(params, meshDesc)); } #endif // DEBUG PxTriangleMesh* triMesh = NULL; PxU32 meshSize = 0; // The cooked mesh may either be saved to a stream for later loading, or inserted directly into PxPhysics. if (inserted) { triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); } else { PxDefaultMemoryOutputStream outBuffer; PxCookTriangleMesh(params, meshDesc, outBuffer); PxDefaultMemoryInputData stream(outBuffer.getData(), outBuffer.getSize()); triMesh = gPhysics->createTriangleMesh(stream); meshSize = outBuffer.getSize(); } // Print the elapsed time for comparison PxU64 stopTime = SnippetUtils::getCurrentTimeCounterValue(); float elapsedTime = SnippetUtils::getElapsedTimeInMilliseconds(stopTime - startTime); printf("\t -----------------------------------------------\n"); printf("\t Create triangle mesh with %d triangles: \n", numTriangles); inserted ? printf("\t\t Mesh inserted on\n") : printf("\t\t Mesh inserted off\n"); !skipEdgeData ? printf("\t\t Precompute edge data on\n") : printf("\t\t Precompute edge data off\n"); !skipMeshCleanup ? printf("\t\t Mesh cleanup on\n") : printf("\t\t Mesh cleanup off\n"); printf("\t\t Num triangles per leaf: %d \n", numTrisPerLeaf); printf("\t Elapsed time in ms: %f \n", double(elapsedTime)); if (!inserted) { printf("\t Mesh size: %d \n", meshSize); } triMesh->release(); } void createTriangleMeshes() { const PxU32 numColumns = 128; const PxU32 numRows = 128; const PxU32 numVertices = (numColumns + 1)*(numRows + 1); const PxU32 numTriangles = numColumns*numRows * 2; PxVec3* vertices = new PxVec3[numVertices]; PxU32* indices = new PxU32[numTriangles * 3]; srand(50); createRandomTerrain(PxVec3(0.0f, 0.0f, 0.0f), numRows, numColumns, 1.0f, 1.0f, 1.f, vertices, indices); // Create triangle mesh using BVH33 midphase with different settings printf("-----------------------------------------------\n"); printf("Create triangles mesh using BVH33 midphase: \n\n"); // Favor runtime speed, cleaning the mesh and precomputing active edges. Store the mesh in a stream. // These are the default settings, suitable for offline cooking. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, false, false, false, false, false); // Favor mesh size, cleaning the mesh and precomputing active edges. Store the mesh in a stream. createBV33TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, false, true); // Favor cooking speed, skip mesh cleanup, but precompute active edges. Insert into PxPhysics. // These settings are suitable for runtime cooking, although selecting fast cooking may reduce // runtime performance of simulation and queries. We still need to ensure the triangles // are valid, so we perform a validation check in debug/checked builds. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, true, false, true, true, false); // Favor cooking speed, skip mesh cleanup, and don't precompute the active edges. Insert into PxPhysics. // This is the fastest possible solution for runtime cooking, but all edges are marked as active, which can // further reduce runtime performance, and also affect behavior. createBV33TriangleMesh(numVertices,vertices,numTriangles,indices, false, true, true, true, false); // Create triangle mesh using BVH34 midphase with different settings printf("-----------------------------------------------\n"); printf("Create triangles mesh using BVH34 midphase: \n\n"); // Favor runtime speed, cleaning the mesh and precomputing active edges. Store the mesh in a stream. // These are the default settings, suitable for offline cooking. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, 4); // Favor mesh size, cleaning the mesh and precomputing active edges. Store the mesh in a stream. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, false, false, 15); // Favor cooking speed, skip mesh cleanup, but precompute active edges. Insert into PxPhysics. // These settings are suitable for runtime cooking, although selecting more triangles per leaf may reduce // runtime performance of simulation and queries. We still need to ensure the triangles // are valid, so we perform a validation check in debug/checked builds. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, true, false, true, 15); // Favor cooking speed, skip mesh cleanup, and don't precompute the active edges. Insert into PxPhysics. // This is the fastest possible solution for runtime cooking, but all edges are marked as active, which can // further reduce runtime performance, and also affect behavior. createBV34TriangleMesh(numVertices, vertices, numTriangles, indices, false, true, true, 15); delete [] vertices; delete [] indices; } void initPhysics() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true); createTriangleMeshes(); } void cleanupPhysics() { PX_RELEASE(gPhysics); PX_RELEASE(gFoundation); printf("SnippetTriangleMeshCreate done.\n"); } int snippetMain(int, const char*const*) { initPhysics(); cleanupPhysics(); return 0; }
15,642
C++
39.525907
139
0.738077
NVIDIA-Omniverse/PhysX/physx/snippets/snippetmultipruners/SnippetMultiPruners.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to use a custom scene query system with N pruners // instead of the traditional two in PxScene. This is mainly useful for large // world with a lot of actors and a lot of updates. The snippet creates a // "worst case scenario" involving hundreds of thousands of actors, which are // all artificially updated each frame to put a lot of pressure on the query // structures. This is not entirely realistic but it makes the gains from the // custom query system more obvious. There is a virtual "player" moving around // in that world and regions are added and removed at runtime according to the // player's position. Each region contains thousands of actors, which stresses // the tree building code, the tree refit code, the build step code, and many // parts of the SQ update pipeline. Pruners can be updated in parallel, which // is more useful with N pruners than it was with the two PxScene build-in pruners. // // Rendering is disabled by default since it can be quite slow for so many // actors. // // Note that the cost of actual scene queries (raycasts, etc) might go up when // using multiple pruners. However the cost of updating the SQ structures can be // much higher than the cost of the scene queries themselves, so this can be a // good trade-off. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" #include "foundation/PxArray.h" #include "foundation/PxTime.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; // Define this to use a custom pruner. Undefine to use the default PxScene code. #define USE_CUSTOM_PRUNER // This number of threads is used both for the default PhysX CPU dispatcher, and // for the custom concurrent build steps when a custom pruner is used. It does not // have much of an impact when USE_CUSTOM_PRUNER is undefined. #define NUM_WORKER_THREADS 8 //#define NUM_WORKER_THREADS 4 //#define NUM_WORKER_THREADS 2 //#define NUM_WORKER_THREADS 1 #ifdef RENDER_SNIPPET // Enable or disable rendering. Disabled by default, since the default scene uses 648081 actors. // There is a custom piece of code that renders the scene as a single mesh though, so it should // still be usable on fast PCs when enabled. static const bool gEnableRendering = false; #endif // Number of frames to simulate, only used when gEnableRendering == false static const PxU32 gNbFramesToSimulate = 100; // The PhysX tree rebuild rate hint. It is usually a *bad idea* to decrease it to 10 (the default // value is 100), but people do this, and it puts more stress on the build code, which fits the // worst case scenario we're looking for in this snippet. But do note that in most cases it should // really be left to "100", or actually increased in large scenes. static PxU32 gDynamicTreeRebuildRateHint = 10; // How many objects are added in each region. This has a direct impact on performance in all parts // of the system. //static const PxU32 gNbObjectsPerRegion = 400; //static const PxU32 gNbObjectsPerRegion = 800; //static const PxU32 gNbObjectsPerRegion = 2000; //static const PxU32 gNbObjectsPerRegion = 4000; static const PxU32 gNbObjectsPerRegion = 8000; static const float gGlobalScale = 1.0f; // Size of added objects. static const float gObjectScale = 0.01f * gGlobalScale; // This controls whether objects are artificially updated each frame. This resets the objects' positions // to what they already are, no nothing is moving but internally it forces all trees to be refit & rebuilt // constantly. This has a big impact on performance. // // Using "false" here means that: // - if USE_CUSTOM_PRUNER is NOT defined, the new objects are added to a unique tree in PxScene, which triggers // a rebuild. The refit operation is not necessary and skipped. // - if USE_CUSTOM_PRUNER is defined, the new objects are added to a per-region pruner in each region. There is // no rebuild necessary, and no refit either. // // Using "true" here means that all involved trees are constantly refit & rebuilt over a number of frames. static const bool gUpdateObjectsInRegion = true; // Range of player's motion static const float gRange = 10.0f * gGlobalScale; #ifdef RENDER_SNIPPET // Size of player static const float gPlayerSize = 0.1f * gGlobalScale; #endif // Speed of player. If you increase it too much the player might leave a region before its tree gets rebuilt, // which means some parts of the update pipeline are never executed. static const float gPlayerSpeed = 0.1f; //static const float gPlayerSpeed = 0.01f; // Size of active area. The world is effectively infinite but only this active area is considered by the // streaming code. The active area is a square whose edge size is gActiveAreaSize*2. static const float gActiveAreaSize = 5.0f * gGlobalScale; // Number of cells per side == number of regions per side. static const PxU32 gNbCellsPerSide = 8; #ifdef USE_CUSTOM_PRUNER // Number of pruners in the system static const PxU32 gNbPruners = (gNbCellsPerSide+1)*(gNbCellsPerSide+1); // Use true to update all pruners in parallel, false to update them sequentially static const bool gUseConcurrentBuildSteps = true; // Use tree of pruners or not. This is mainly useful if you have a large number of pruners in // the system. There is a small cost associated with maintaining that extra tree but since the // number of pruners should still be vastly smaller than the total number of objects, this is // usually quite cheap. You can profile the ratcast cost by modifying the code at the end of // this snippet and see how using a tree of pruners improves performance. static const bool gUseTreeOfPruners = false; #endif static float gGlobalTime = 0.0f; static SnippetUtils::BasicRandom gRandom(42); static const PxVec3 gYellow(1.0f, 1.0f, 0.0f); static const PxVec3 gRed(1.0f, 0.0f, 0.0f); static const PxVec3 gGreen(0.0f, 1.0f, 0.0f); static PxVec3 computePlayerPos(float globalTime) { const float Amplitude = gRange; const float t = globalTime * gPlayerSpeed; const float x = sinf(t*2.17f) * sinf(t) * Amplitude; const float z = sinf(t*0.77f) * cosf(t) * Amplitude; return PxVec3(x, 0.0f, z); } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; #define INVALID_ID 0xffffffff #ifdef RENDER_SNIPPET static PxU8 gBoxIndices[] = { 0,2,1, 0,3,2, 1,6,5, 1,2,6, 5,7,4, 5,6,7, 4,3,0, 4,7,3, 3,6,2, 3,7,6, 5,0,1, 5,4,0 }; #endif namespace { #ifdef USE_CUSTOM_PRUNER struct PrunerData { PrunerData() : mPrunerIndex(INVALID_ID), mNbObjects(0) {} PxU32 mPrunerIndex; PxU32 mNbObjects; }; #endif struct RegionData { PxArray<PxRigidStatic*> mObjects; #ifdef USE_CUSTOM_PRUNER PrunerData* mPrunerData; #endif #ifdef RENDER_SNIPPET PxU32 mNbVerts, mNbTris; PxVec3* mVerts; PxU32* mIndices; #endif }; #ifdef USE_CUSTOM_PRUNER // This adapter class will be used by the PxCustomSceneQuerySystem to map each new actor/shape to a user-defined pruner class SnippetCustomSceneQuerySystemAdapter : public PxCustomSceneQuerySystemAdapter { public: PrunerData mPrunerData[gNbPruners]; SnippetCustomSceneQuerySystemAdapter() { } void createPruners(PxCustomSceneQuerySystem* customSQ) { // We create a pool of pruners, large enough to provide one pruner per region. This is an arbitrary choice, we could also // map multiple regions to the same pruner (as long as these regions are close to each other it's just fine). if(customSQ) { for(PxU32 i=0;i<gNbPruners;i++) mPrunerData[i].mPrunerIndex = customSQ->addPruner(PxPruningStructureType::eDYNAMIC_AABB_TREE, PxDynamicTreeSecondaryPruner::eINCREMENTAL); //mPrunerData[i].mPrunerIndex = customSQ->addPruner(PxPruningStructureType::eDYNAMIC_AABB_TREE, PxDynamicTreeSecondaryPruner::eBVH); } } // This is called by the streaming code to assign a pruner to a region PrunerData* findFreePruner() { for(PxU32 i=0;i<gNbPruners;i++) { if(mPrunerData[i].mNbObjects==0) return &mPrunerData[i]; } PX_ASSERT(0); return NULL; } // This is called by the streaming code to release a pruner when a region is deleted void releasePruner(PxU32 index) { PX_ASSERT(mPrunerData[index].mNbObjects==0); mPrunerData[index].mNbObjects=0; } // This is called by PxCustomSceneQuerySystem to assign a pruner index to a new actor/shape virtual PxU32 getPrunerIndex(const PxRigidActor& actor, const PxShape& /*shape*/) const { const PrunerData* prunerData = reinterpret_cast<const PrunerData*>(actor.userData); return prunerData->mPrunerIndex; } // This is called by PxCustomSceneQuerySystem to validate a pruner for scene queries virtual bool processPruner(PxU32 /*prunerIndex*/, const PxQueryThreadContext* /*context*/, const PxQueryFilterData& /*filterData*/, PxQueryFilterCallback* /*filterCall*/) const { // We could filter out empty pruners here if we have some, but for now we don't bother return true; } }; #endif struct StreamRegion { PX_FORCE_INLINE StreamRegion() : mKey(0), mTimestamp(INVALID_ID), mRegionData(NULL) {} PxU64 mKey; PxU32 mTimestamp; PxBounds3 mCellBounds; RegionData* mRegionData; }; typedef PxHashMap<PxU64, StreamRegion> StreamingCache; class Streamer { PX_NOCOPY(Streamer) public: Streamer(float activeAreaSize, PxU32 nbCellsPerSide); ~Streamer(); void update(const PxVec3& playerPos); void renderDebug(); void render(); PxBounds3 mStreamingBounds; StreamingCache mStreamingCache; PxU32 mTimestamp; const float mActiveAreaSize; const PxU32 mNbCellsPerSide; void addRegion(StreamRegion& region); void updateRegion(StreamRegion& region); void removeRegion(StreamRegion& region); }; } #ifdef USE_CUSTOM_PRUNER static SnippetCustomSceneQuerySystemAdapter gAdapter; #endif Streamer::Streamer(float activeAreaSize, PxU32 nbCellsPerSide) : mTimestamp(0), mActiveAreaSize(activeAreaSize), mNbCellsPerSide(nbCellsPerSide) { mStreamingBounds.setEmpty(); } Streamer::~Streamer() { } void Streamer::addRegion(StreamRegion& region) { PX_ASSERT(region.mRegionData==NULL); // We disable the simulation flag to measure the cost of SQ structures exclusively const PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE; PxVec3 extents = region.mCellBounds.getExtents(); extents.x -= 0.01f * gGlobalScale; extents.z -= 0.01f * gGlobalScale; extents.y = 0.1f * gGlobalScale; PxVec3 center = region.mCellBounds.getCenter(); center.y = -0.1f * gGlobalScale; // In each region we create one "ground" shape and a number of extra smaller objects on it. We use // static objects to make sure the timings aren't polluted by dynamics-related costs. Dynamic actors // can also move to neighboring regions, which in theory means they should be transferred to another // pruner to avoid unpleasant visual artefacts when removing an entire region. This is beyond the // scope of this snippet so, static actors it is. // // The number of static actors in the world is usually much larger than the number of dynamic actors. // Dynamic actors move constantly, so they usually always trigger a refit & rebuild of the corresponding // trees. It is therefore a good idea to separate static and dynamic actors, to avoid the cost of // refit & rebuild for the static parts. In the context of a streaming world it is sometimes good enough // to put static actors in separate pruners (like we do here) but still stuff all dynamic actors in a // unique separate pruner (i.e. the same for the whole world). It avoids the aforementioned issues with // dynamic actors moving to other regions, and if the total number of dynamic actors remains small a // single structure for dynamic actors is often enough. PxShape* groundShape = gPhysics->createShape(PxBoxGeometry(extents), *gMaterial, false, shapeFlags); PxRigidStatic* ground = PxCreateStatic(*gPhysics, PxTransform(center), *groundShape); RegionData* regionData = new RegionData; regionData->mObjects.pushBack(ground); region.mRegionData = regionData; #ifdef USE_CUSTOM_PRUNER regionData->mPrunerData = gAdapter.findFreePruner(); ground->userData = regionData->mPrunerData; regionData->mPrunerData->mNbObjects++; #endif gScene->addActor(*ground); if(gNbObjectsPerRegion) { const PxU32 nbExtraObjects = gNbObjectsPerRegion; const float objectScale = gObjectScale; const float coeffY = objectScale * 20.0f; center.y = objectScale; const PxBoxGeometry boxGeom(objectScale, objectScale, objectScale); PxShape* shape = gPhysics->createShape(boxGeom, *gMaterial, false, shapeFlags); PxRigidActor* actors[nbExtraObjects]; for(PxU32 j=0;j<nbExtraObjects;j++) { PxVec3 c = center; c.x += gRandom.randomFloat() * extents.x * (2.0f - objectScale); c.y += fabsf(gRandom.randomFloat()) * coeffY; c.z += gRandom.randomFloat() * extents.z * (2.0f - objectScale); PxRigidStatic* actor = PxCreateStatic(*gPhysics, PxTransform(c), *shape); actors[j] = actor; regionData->mObjects.pushBack(actor); #ifdef USE_CUSTOM_PRUNER actor->userData = regionData->mPrunerData; regionData->mPrunerData->mNbObjects++; #endif } /* if(0) { PxPruningStructure* ps = physics.createPruningStructure(actors, nbDynamicObjects); scene.addActors(*ps); } else*/ { gScene->addActors(reinterpret_cast<PxActor**>(actors), nbExtraObjects); } } #ifdef RENDER_SNIPPET // Precompute single render mesh for this region (rendering them as individual actors is too // slow). This is also only possible because we used static actors. { const PxU32 nbActors = regionData->mObjects.size(); const PxU32 nbVerts = nbActors*8; const PxU32 nbTris = nbActors*12; PxVec3* pts = new PxVec3[nbVerts]; PxVec3* dstPts = pts; PxU32* indices = new PxU32[nbTris*3]; PxU32* dstIndices = indices; PxU32 baseIndex = 0; for(PxU32 i=0;i<nbActors;i++) { const PxVec3 c = regionData->mObjects[i]->getGlobalPose().p; PxShape* shape; regionData->mObjects[i]->getShapes(&shape, 1); const PxBoxGeometry& boxGeom = static_cast<const PxBoxGeometry&>(shape->getGeometry()); const PxVec3 minimum = c - boxGeom.halfExtents; const PxVec3 maximum = c + boxGeom.halfExtents; dstPts[0] = PxVec3(minimum.x, minimum.y, minimum.z); dstPts[1] = PxVec3(maximum.x, minimum.y, minimum.z); dstPts[2] = PxVec3(maximum.x, maximum.y, minimum.z); dstPts[3] = PxVec3(minimum.x, maximum.y, minimum.z); dstPts[4] = PxVec3(minimum.x, minimum.y, maximum.z); dstPts[5] = PxVec3(maximum.x, minimum.y, maximum.z); dstPts[6] = PxVec3(maximum.x, maximum.y, maximum.z); dstPts[7] = PxVec3(minimum.x, maximum.y, maximum.z); dstPts += 8; for(PxU32 j=0;j<12*3;j++) dstIndices[j] = gBoxIndices[j] + baseIndex; dstIndices += 12*3; baseIndex += 8; } regionData->mVerts = pts; regionData->mIndices = indices; regionData->mNbVerts = nbVerts; regionData->mNbTris = nbTris; } #endif } void Streamer::updateRegion(StreamRegion& region) { RegionData* regionData = region.mRegionData; if(gUpdateObjectsInRegion) { // Artificial update to trigger the tree refit & rebuild code const PxU32 nbObjects = regionData->mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const PxTransform pose = regionData->mObjects[i]->getGlobalPose(); regionData->mObjects[i]->setGlobalPose(pose); } } } void Streamer::removeRegion(StreamRegion& region) { PX_ASSERT(region.mRegionData); RegionData* regionData = region.mRegionData; #ifdef RENDER_SNIPPET delete [] regionData->mIndices; delete [] regionData->mVerts; #endif // Because we used static actors only we can just release all actors, they didn't move to other regions const PxU32 nbObjects = regionData->mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) regionData->mObjects[i]->release(); #ifdef USE_CUSTOM_PRUNER PX_ASSERT(regionData->mPrunerData); regionData->mPrunerData->mNbObjects-=nbObjects; PX_ASSERT(regionData->mPrunerData->mNbObjects==0); gAdapter.releasePruner(regionData->mPrunerData->mPrunerIndex); #endif delete region.mRegionData; region.mRegionData = NULL; } void Streamer::update(const PxVec3& playerPos) { const float activeAreaSize = mActiveAreaSize; mStreamingBounds = PxBounds3::centerExtents(playerPos, PxVec3(activeAreaSize)); const float worldSize = activeAreaSize*2.0f; const PxU32 nbCellsPerSide = mNbCellsPerSide; const float cellSize = worldSize/float(nbCellsPerSide); const float cellSizeX = cellSize; const float cellSizeZ = cellSize; const PxI32 x0 = PxI32(floorf(mStreamingBounds.minimum.x/cellSizeX)); const PxI32 z0 = PxI32(floorf(mStreamingBounds.minimum.z/cellSizeZ)); const PxI32 x1 = PxI32(ceilf(mStreamingBounds.maximum.x/cellSizeX)); const PxI32 z1 = PxI32(ceilf(mStreamingBounds.maximum.z/cellSizeZ)); // Generally speaking when streaming objects in and out of the game world, we want to first remove // old objects then add new objects (in this order) to give the system a chance to recycle removed // entries and use less resources overall. That's why we split the loop to add objects in two parts. // The first part below finds currently touched regions and updates their timestamp. for(PxI32 j=z0;j<z1;j++) { for(PxI32 i=x0;i<x1;i++) { const PxU64 Key = (PxU64(i)<<32)|PxU64(PxU32(j)); StreamRegion& region = mStreamingCache[Key]; if(region.mTimestamp!=INVALID_ID) { // This region was already active => update its timestamp. PX_ASSERT(region.mKey==Key); region.mTimestamp = mTimestamp; updateRegion(region); } } } // This loop checks all regions in the system and removes the ones that are neither new // (mTimestamp==INVALID_ID) nor persistent (mTimestamp==current timestamp). { PxArray<PxU64> toRemove; // Delayed removal to avoid touching the hashmap while we're iterating it for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) { if(iter->second.mTimestamp!=mTimestamp && iter->second.mTimestamp!=INVALID_ID) { removeRegion(iter->second); toRemove.pushBack(iter->second.mKey); } } const PxU32 nbToGo = toRemove.size(); for(PxU32 i=0;i<nbToGo;i++) { bool b = mStreamingCache.erase(toRemove[i]); PX_ASSERT(b); PX_UNUSED(b); } } // Finally we do our initial loop again looking for new regions (mTimestamp==INVALID_ID) and actually add them. for(PxI32 j=z0;j<z1;j++) { for(PxI32 i=x0;i<x1;i++) { const PxU64 Key = (PxU64(i)<<32)|PxU64(PxU32(j)); StreamRegion& region = mStreamingCache[Key]; if(region.mTimestamp==INVALID_ID) { // New entry region.mKey = Key; region.mTimestamp = mTimestamp; region.mCellBounds.minimum = PxVec3(float(i)*cellSizeX, 0.0f, float(j)*cellSizeZ); region.mCellBounds.maximum = PxVec3(float(i+1)*cellSizeX, 0.0f, float(j+1)*cellSizeZ); addRegion(region); } } } mTimestamp++; } void Streamer::renderDebug() { #ifdef RENDER_SNIPPET Snippets::DrawBounds(mStreamingBounds, gGreen); for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) Snippets::DrawBounds(iter->second.mCellBounds, gRed); #endif } void Streamer::render() { #ifdef RENDER_SNIPPET for(StreamingCache::Iterator iter = mStreamingCache.getIterator(); !iter.done(); ++iter) { const RegionData* data = iter->second.mRegionData; Snippets::renderMesh(data->mNbVerts, data->mVerts, data->mNbTris, data->mIndices, PxVec3(0.1f, 0.2f, 0.3f)); } #endif } static Streamer* gStreamer = NULL; #ifdef USE_CUSTOM_PRUNER static PxCustomSceneQuerySystem* gCustomSQ = NULL; #endif static bool gHasRaycastHit; static PxRaycastHit gRaycastHit; static PxVec3 gOrigin; void renderScene() { #ifdef RENDER_SNIPPET if(0) // Disabled, this is too slow { PxScene* scene; PxGetPhysics().getScenes(&scene,1); PxU32 nbActors = scene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); if(nbActors) { //printf("Rendering %d actors\n", nbActors); std::vector<PxRigidActor*> actors(nbActors); scene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC, reinterpret_cast<PxActor**>(&actors[0]), nbActors); Snippets::renderActors(&actors[0], static_cast<PxU32>(actors.size()), false, PxVec3(0.1f, 0.2f, 0.3f), NULL, true, false); } } else { if(gStreamer) gStreamer->render(); } if(gHasRaycastHit) { Snippets::DrawLine(gOrigin, gRaycastHit.position, gYellow); Snippets::DrawFrame(gRaycastHit.position, 1.0f); } else Snippets::DrawLine(gOrigin, gOrigin - PxVec3(0.0f, 100.0f, 0.0f), gYellow); const PxVec3 playerPos = computePlayerPos(gGlobalTime); const PxBounds3 playerBounds = PxBounds3::centerExtents(playerPos, PxVec3(gPlayerSize)); Snippets::DrawBounds(playerBounds, gYellow); // const PxBounds3 activeAreaBounds = PxBounds3::centerExtents(playerPos, PxVec3(gActiveAreaSize)); // Snippets::DrawBounds(activeAreaBounds, gGreen); if(gStreamer) gStreamer->renderDebug(); #endif } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); if(1) { gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); //gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPvd->connect(*transport,PxPvdInstrumentationFlag::ePROFILE); } gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), false, gPvd); gDispatcher = PxDefaultCpuDispatcherCreate(NUM_WORKER_THREADS); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.dynamicStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.dynamicTreeRebuildRateHint = gDynamicTreeRebuildRateHint; #ifdef USE_CUSTOM_PRUNER // For concurrent build steps we're going to use the new custom API in PxCustomSceneQuerySystem so we tell the system // to disable the built-in build-step & commit functions (which are otherwise executed in fetchResults). sceneDesc.sceneQueryUpdateMode = gUseConcurrentBuildSteps ? PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED : PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED; // Create our custom scene query system and tell PxSceneDesc about it PxCustomSceneQuerySystem* customSQ = PxCreateCustomSceneQuerySystem(sceneDesc.sceneQueryUpdateMode, 0x0102030405060708, gAdapter, gUseTreeOfPruners); if(customSQ) { gAdapter.createPruners(customSQ); sceneDesc.sceneQuerySystem = customSQ; gCustomSQ = customSQ; } #endif gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); gStreamer = new Streamer(gActiveAreaSize, gNbCellsPerSide); } #ifdef USE_CUSTOM_PRUNER class TaskBuildStep : public PxLightCpuTask { public: TaskBuildStep() : PxLightCpuTask(), mIndex(INVALID_ID) {} virtual void run() { PX_SIMD_GUARD gCustomSQ->customBuildstep(mIndex); } virtual const char* getName() const { return "TaskBuildStep"; } PxU32 mIndex; }; class TaskWait: public PxLightCpuTask { public: TaskWait(SnippetUtils::Sync* syncHandle) : PxLightCpuTask(), mSyncHandle(syncHandle) {} virtual void run() {} PX_INLINE void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSyncHandle); } virtual const char* getName() const { return "TaskWait"; } private: SnippetUtils::Sync* mSyncHandle; }; static void concurrentBuildSteps() { const PxU32 nbPruners = gCustomSQ->startCustomBuildstep(); PX_UNUSED(nbPruners); { PX_ASSERT(nbPruners==gNbPruners); SnippetUtils::Sync* buildStepsComplete = SnippetUtils::syncCreate(); SnippetUtils::syncReset(buildStepsComplete); TaskWait taskWait(buildStepsComplete); TaskBuildStep taskBuildStep[gNbPruners]; for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].mIndex = i; PxTaskManager* tm = gScene->getTaskManager(); tm->resetDependencies(); tm->startSimulation(); taskWait.setContinuation(*tm, NULL); for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].setContinuation(&taskWait); taskWait.removeReference(); for(PxU32 i=0; i<gNbPruners; i++) taskBuildStep[i].removeReference(); SnippetUtils::syncWait(buildStepsComplete); SnippetUtils::syncRelease(buildStepsComplete); } gCustomSQ->finishCustomBuildstep(); } #endif static PxTime gTime; void stepPhysics(bool /*interactive*/) { if(gStreamer) { const PxVec3 playerPos = computePlayerPos(gGlobalTime); gStreamer->update(playerPos); gOrigin = playerPos+PxVec3(0.0f, 10.0f, 0.0f); } const PxU32 nbActors = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC | PxActorTypeFlag::eRIGID_STATIC); const float dt = 1.0f/60.0f; gTime.getElapsedSeconds(); { gScene->simulate(dt); gScene->fetchResults(true); #ifdef USE_CUSTOM_PRUNER if(gUseConcurrentBuildSteps) concurrentBuildSteps(); #endif } PxTime::Second time = gTime.getElapsedSeconds()*1000.0; // Ignore first frames to skip the cost of creating all the initial regions static PxU32 nbIgnored = 16; static PxU32 nbCalls = 0; static PxF64 totalTime = 0; static PxF64 peakTime = 0; if(nbIgnored) nbIgnored--; else { nbCalls++; totalTime+=time; if(time>peakTime) peakTime = time; if(1) printf("%d: time: %f ms | avg: %f ms | peak: %f ms | %d actors\n", nbCalls, time, totalTime/PxU64(nbCalls), peakTime, nbActors); } gTime.getElapsedSeconds(); { PxRaycastBuffer buf; gScene->raycast(gOrigin, PxVec3(0.0f, -1.0f, 0.0f), 100.0f, buf); gHasRaycastHit = buf.hasBlock; if(buf.hasBlock) gRaycastHit = buf.block; } time = gTime.getElapsedSeconds()*1000.0; if(0) printf("raycast time: %f us\n", time*1000.0); gGlobalTime += dt; } void cleanupPhysics(bool /*interactive*/) { delete gStreamer; PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetMultiPruners done.\n"); } void keyPress(unsigned char /*key*/, const PxTransform& /*camera*/) { } static void runWithoutRendering() { static const PxU32 frameCount = gNbFramesToSimulate; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); } int snippetMain(int, const char*const*) { printf("Multi Pruners snippet.\n"); #ifdef RENDER_SNIPPET if(gEnableRendering) { extern void renderLoop(); renderLoop(); } else runWithoutRendering(); #else runWithoutRendering(); #endif return 0; }
29,388
C++
32.20791
178
0.736865
NVIDIA-Omniverse/PhysX/physx/snippets/snippetcustomgeometryqueries/SnippetCustomGeometryQueries.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to implement custom geometries queries // callbacks, using PhysX geometry queries. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; void renderRaycast(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxRaycastHit* hit); void renderSweepBox(const PxVec3& origin, const PxVec3& unitDir, float maxDist, const PxVec3& halfExtents, const PxSweepHit* hit); void renderOverlapBox(const PxVec3& origin, const PxVec3& halfExtents, bool hit); /* Two crossed bars. */ struct BarCrosss : PxCustomGeometry::Callbacks { PxVec3 barExtents; DECLARE_CUSTOM_GEOMETRY_TYPE BarCrosss() : barExtents(27, 9, 3) {} virtual PxBounds3 getLocalBounds(const PxGeometry&) const { return PxBounds3(-PxVec3(barExtents.x * 0.5f, barExtents.y * 0.5f, barExtents.x * 0.5f), PxVec3(barExtents.x * 0.5f, barExtents.y * 0.5f, barExtents.x * 0.5f)); } virtual bool generateContacts(const PxGeometry&, const PxGeometry&, const PxTransform&, const PxTransform&, const PxReal, const PxReal, const PxReal, PxContactBuffer&) const { return false; } virtual PxU32 raycast(const PxVec3& origin, const PxVec3& unitDir, const PxGeometry&, const PxTransform& pose, PxReal maxDist, PxHitFlags hitFlags, PxU32, PxGeomRaycastHit* rayHits, PxU32, PxRaycastThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose; PxGeomRaycastHit hits[2]; PxGeometryQuery::raycast(origin, unitDir, barGeom, p0, maxDist, hitFlags, 1, hits + 0); p0 = pose.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); PxGeometryQuery::raycast(origin, unitDir, barGeom, p0, maxDist, hitFlags, 1, hits + 1); rayHits[0] = hits[0].distance < hits[1].distance ? hits[0] : hits[1]; return hits[0].distance < PX_MAX_REAL || hits[1].distance < PX_MAX_REAL ? 1 : 0; } virtual bool overlap(const PxGeometry&, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxOverlapThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose0; if (PxGeometryQuery::overlap(barGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; p0 = pose0.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); if (PxGeometryQuery::overlap(barGeom, p0, geom1, pose1, PxGeometryQueryFlags(0))) return true; return false; } virtual bool sweep(const PxVec3& unitDir, const PxReal maxDist, const PxGeometry&, const PxTransform& pose0, const PxGeometry& geom1, const PxTransform& pose1, PxGeomSweepHit& sweepHit, PxHitFlags hitFlags, const PxReal inflation, PxSweepThreadContext*) const { PxBoxGeometry barGeom(barExtents * 0.5f); PxTransform p0 = pose0; PxGeomSweepHit hits[2]; PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, barGeom, p0, hits[0], hitFlags, inflation); p0 = pose0.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); PxGeometryQuery::sweep(unitDir, maxDist, geom1, pose1, barGeom, p0, hits[1], hitFlags, inflation); sweepHit = hits[0].distance < hits[1].distance ? hits[0] : hits[1]; return hits[0].distance < PX_MAX_REAL || hits[1].distance < PX_MAX_REAL; } virtual void visualize(const PxGeometry&, PxRenderOutput&, const PxTransform&, const PxBounds3&) const {} virtual void computeMassProperties(const PxGeometry&, PxMassProperties&) const {} virtual bool usePersistentContactManifold(const PxGeometry&, PxReal&) const { return false; } }; IMPLEMENT_CUSTOM_GEOMETRY_TYPE(BarCrosss) static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* gActor = NULL; static BarCrosss gBarCrosss; static PxReal gTime = 0; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity = PxVec3(0), PxReal density = 1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f * 3, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Create bar cross actor PxRigidDynamic* barCrossActor = gPhysics->createRigidDynamic(PxTransform(PxVec3(0, gBarCrosss.barExtents.y * 0.5f, 0))); barCrossActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); PxRigidActorExt::createExclusiveShape(*barCrossActor, PxCustomGeometry(gBarCrosss), *gMaterial); gScene->addActor(*barCrossActor); gActor = barCrossActor; } void debugRender() { PxGeometryHolder geom; geom.storeAny(PxBoxGeometry(gBarCrosss.barExtents * 0.5f)); PxTransform pose = gActor->getGlobalPose(); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.7f)); pose = pose.transform(PxTransform(PxQuat(PX_PIDIV2, PxVec3(0, 1, 0)))); Snippets::renderGeoms(1, &geom, &pose, false, PxVec3(0.7f)); // Raycast { PxVec3 origin((gBarCrosss.barExtents.x + 10) * 0.5f, 0, 0); PxVec3 unitDir(-1, 0, 0); float maxDist = gBarCrosss.barExtents.x + 20; PxRaycastBuffer buffer; gScene->raycast(origin, unitDir, maxDist, buffer); renderRaycast(origin, unitDir, maxDist, buffer.hasBlock ? &buffer.block : nullptr); } // Sweep { PxVec3 origin(0, 0, (gBarCrosss.barExtents.x + 10) * 0.5f); PxVec3 unitDir(0, 0, -1); float maxDist = gBarCrosss.barExtents.x + 20; PxVec3 halfExtents(1.5f, 0.5f, 1.0f); PxSweepBuffer buffer; gScene->sweep(PxBoxGeometry(halfExtents), PxTransform(origin), unitDir, maxDist, buffer); renderSweepBox(origin, unitDir, maxDist, halfExtents, buffer.hasBlock ? &buffer.block : nullptr); } // Overlap { PxVec3 origin((gBarCrosss.barExtents.x) * -0.4f, 0, (gBarCrosss.barExtents.x) * -0.4f); PxVec3 halfExtents(gBarCrosss.barExtents.z * 1.5f, gBarCrosss.barExtents.y * 1.1f, gBarCrosss.barExtents.z * 1.5f); PxOverlapBuffer buffer; gScene->overlap(PxBoxGeometry(halfExtents), PxTransform(origin), buffer, PxQueryFilterData(PxQueryFlag::eANY_HIT | PxQueryFlag::eDYNAMIC)); renderOverlapBox(origin, halfExtents, buffer.hasAnyHits()); } } void stepPhysics(bool /*interactive*/) { gTime += 1.0f / 60.0f; gActor->setKinematicTarget(PxTransform(PxQuat(gTime * 0.3f, PxVec3(0, 1, 0)))); gScene->simulate(1.0f / 60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetGeometryQueries done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch (toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0, 0, -1)) * 200, 3.0f); break; } } int snippetMain(int, const char* const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for (PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char* const*) { return 0; } #endif
10,426
C++
37.476015
148
0.736716
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2multithreading/SnippetVehicleMultithreading.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate a vehicle with direct drive using parameters, states and // components maintained by the PhysX Vehicle SDK. Particlar attention is paid // to the simulation of a PhysX vehicle in a multi-threaded environment. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a direct drive drivetrain model that forwards input controls to wheel torques and angles. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). //This snippet // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPVD.h" #include "common/PxProfileZone.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; PxTaskManager* gTaskManager = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The vehicles with direct drivetrain #define NUM_VEHICLES 1024 DirectDriveVehicle gVehicles[NUM_VEHICLES]; PxVehiclePhysXActorBeginComponent* gPhysXBeginComponents[NUM_VEHICLES]; PxVehiclePhysXActorEndComponent* gPhysXEndComponents[NUM_VEHICLES]; #define NUM_WORKER_THREADS 4 #define UPDATE_BATCH_SIZE 1 #define NB_SUBSTEPS 1 //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicles a name so they can be identified in PVD. const char gVehicleName[] = "directDrive"; //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; //Track the number of simulation steps. PxU32 gNbSimulateSteps = 0; //Commands are issued to the vehicle in a pre-choreographed sequence. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxF32 duration; }; Command gCommands[] = { {0.0f, 0.5f, 0.0f, 4.26f}, //throttle for 256 update steps at 60Hz }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //Profile the different phases of a simulate step. struct UpdatePhases { enum Enum { eVEHICLE_PHYSX_BEGIN_COMPONENTS, eVEHICLE_UPDATE_COMPONENTS, eVEHICLE_PHYSX_END_COMPONENTS, ePHYSX_SCENE_SIMULATE, eMAX_NUM_UPDATE_STAGES }; }; static const char* gUpdatePhaseNames[UpdatePhases::eMAX_NUM_UPDATE_STAGES] = { "vehiclePhysXBeginComponents", "vehicleUpdateComponents", "vehiclePhysXEndComponents", "physXSceneSimulate" }; struct ProfileZones { PxU64 times[UpdatePhases::eMAX_NUM_UPDATE_STAGES]; ProfileZones() { for (int i = 0; i < UpdatePhases::eMAX_NUM_UPDATE_STAGES; ++i) times[i] = 0; } void print() { for (int i = 0; i < UpdatePhases::eMAX_NUM_UPDATE_STAGES; ++i) { float ms = SnippetUtils::getElapsedTimeInMilliseconds(times[i]); printf("%s: %f ms\n", gUpdatePhaseNames[i], PxF64(ms)); } } void zoneStart(UpdatePhases::Enum zoneId) { PxU64 time = SnippetUtils::getCurrentTimeCounterValue(); times[zoneId] -= time; } void zoneEnd(UpdatePhases::Enum zoneId) { PxU64 time = SnippetUtils::getCurrentTimeCounterValue(); times[zoneId] += time; } }; ProfileZones gProfileZones; class ScopedProfileZone { private: ScopedProfileZone(const ScopedProfileZone&); ScopedProfileZone& operator=(const ScopedProfileZone&); public: ScopedProfileZone(ProfileZones& zones, UpdatePhases::Enum zoneId) : mZones(zones) , mZoneId(zoneId) { zones.zoneStart(zoneId); } ~ScopedProfileZone() { mZones.zoneEnd(mZoneId); } private: ProfileZones& mZones; UpdatePhases::Enum mZoneId; }; #define SNIPPET_PROFILE_ZONE(zoneId) ScopedProfileZone PX_CONCAT(_scoped, __LINE__)(gProfileZones, zoneId) //TaskVehicleUpdates allows vehicle updates to be performed concurrently across //multiple threads. class TaskVehicleUpdates : public PxLightCpuTask { public: TaskVehicleUpdates() : PxLightCpuTask(), mTimestep(0), mGravity(PxVec3(0, 0, 0)), mThreadId(0xffffffff), mCommandProgress(0) { } void setThreadId(const PxU32 threadId) { mThreadId = threadId; } void setTimestep(const PxF32 timestep) { mTimestep = timestep; } void setGravity(const PxVec3& gravity) { mGravity = gravity; } void setCommandProgress(const PxU32 commandProgress) { mCommandProgress = commandProgress; } virtual void run() { PxU32 vehicleId = mThreadId * UPDATE_BATCH_SIZE; while (vehicleId < NUM_VEHICLES) { const PxU32 numToUpdate = PxMin(NUM_VEHICLES - vehicleId, static_cast<PxU32>(UPDATE_BATCH_SIZE)); for (PxU32 i = 0; i < numToUpdate; i++) { gVehicles[vehicleId + i].mCommandState.brakes[0] = gCommands[mCommandProgress].brake; gVehicles[vehicleId + i].mCommandState.nbBrakes = 1; gVehicles[vehicleId + i].mCommandState.throttle = gCommands[mCommandProgress].throttle; gVehicles[vehicleId + i].mCommandState.steer = gCommands[mCommandProgress].steer; gVehicles[vehicleId + i].mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eFORWARD; gVehicles[vehicleId + i].step(mTimestep, gVehicleSimulationContext); } vehicleId += NUM_WORKER_THREADS * UPDATE_BATCH_SIZE; } } virtual const char* getName() const { return "TaskVehicleUpdates"; } private: PxF32 mTimestep; PxVec3 mGravity; PxU32 mThreadId; PxU32 mCommandProgress; }; //TaskWait runs after all concurrent updates have completed. class TaskWait : public PxLightCpuTask { public: TaskWait(SnippetUtils::Sync* syncHandle) : PxLightCpuTask(), mSyncHandle(syncHandle) { } virtual void run() { } PX_INLINE void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSyncHandle); } virtual const char* getName() const { return "TaskWait"; } private: SnippetUtils::Sync* mSyncHandle; }; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::ePROFILE); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; gDispatcher = PxDefaultCpuDispatcherCreate(NUM_WORKER_THREADS); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, false); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); ///////////////////////////////////////////// //Create a task manager that will be used to //update the vehicles concurrently across //multiple threads. ///////////////////////////////////////////// gTaskManager = PxTaskManager::createTaskManager(gFoundation->getErrorCallback(), gDispatcher); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PX_RELEASE(gTaskManager); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the params from json BaseVehicleParams baseParams; readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams); PhysXIntegrationParams physxParams; setPhysXIntegrationParams(baseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, physxParams); DirectDrivetrainParams directDrivetrainParams; readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams); //Create the params, states and component sequences for direct drive vehicles. //Take care not to add PxVehiclePhysXActorBeginComponent or PxVehiclePhysXActorEndComponent //to the sequences because are executed in a separate step. for (PxU32 i = 0; i < NUM_VEHICLES; i++) { //Set the vehicle params. //Every vehicle is identical. gVehicles[i].mBaseParams = baseParams; gVehicles[i].mPhysXParams = physxParams; gVehicles[i].mDirectDriveParams = directDrivetrainParams; //Set the states to default and create the component sequence. //Take care not to add PxVehiclePhysXActorBeginComponent and PxVehiclePhysXActorEndComponent //to the sequence because these are handled separately to take advantage of multi-threading. const bool addPhysXBeginAndEndComponentsToSequence = false; if (!gVehicles[i].initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, addPhysXBeginAndEndComponentsToSequence)) { return false; } //Force a known substep count per simulation step so that we have a perfect understanding of //the amount of computational effort involved in running the snippet. gVehicles[i].mComponentSequence.setSubsteps(gVehicles[i].mComponentSequenceSubstepGroupHandle, NB_SUBSTEPS); //Apply a start pose to the physx actor and add it to the physx scene. PxTransform pose(PxVec3(5.0f*(PxI32(i) - NUM_VEHICLES/2), 0.0f, 0.0f), PxQuat(PxIdentity)); gVehicles[i].setUpActor(*gScene, pose, gVehicleName); } //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXBeginComponents[i] = (static_cast<PxVehiclePhysXActorBeginComponent*>(gVehicles + i)); gPhysXEndComponents[i] = (static_cast<PxVehiclePhysXActorEndComponent*>(gVehicles + i)); } //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gVehicles[i].destroy(); } } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void concurrentVehicleUpdates(const PxReal timestep) { SnippetUtils::Sync* vehicleUpdatesComplete = SnippetUtils::syncCreate(); SnippetUtils::syncReset(vehicleUpdatesComplete); //Create tasks that will update the vehicles concurrently then wait until all vehicles //have completed their update. TaskWait taskWait(vehicleUpdatesComplete); TaskVehicleUpdates taskVehicleUpdates[NUM_WORKER_THREADS]; for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].setThreadId(i); taskVehicleUpdates[i].setTimestep(timestep); taskVehicleUpdates[i].setGravity(gScene->getGravity()); taskVehicleUpdates[i].setCommandProgress(gCommandProgress); } //Start the task manager. gTaskManager->resetDependencies(); gTaskManager->startSimulation(); //Perform a vehicle simulation step and profile each phase of the simulation. { //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_PHYSX_BEGIN_COMPONENTS); for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXBeginComponents[i]->update(timestep, gVehicleSimulationContext); } } //Multi-threaded update of direct drive vehicles. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_UPDATE_COMPONENTS); //Update the vehicles concurrently then wait until all vehicles //have completed their update. taskWait.setContinuation(*gTaskManager, NULL); for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].setContinuation(&taskWait); } taskWait.removeReference(); for (PxU32 i = 0; i < NUM_WORKER_THREADS; i++) { taskVehicleUpdates[i].removeReference(); } //Wait for the signal that the work has been completed. SnippetUtils::syncWait(vehicleUpdatesComplete); //Release the sync handle SnippetUtils::syncRelease(vehicleUpdatesComplete); } //PhysX reads/writes require read/write locks that serialize executions. //Perform all physx reads/writes serially in a separate step to avoid serializing code that can take //advantage of multithreading. { SNIPPET_PROFILE_ZONE(UpdatePhases::eVEHICLE_PHYSX_END_COMPONENTS); for (PxU32 i = 0; i < NUM_VEHICLES; i++) { gPhysXEndComponents[i]->update(timestep, gVehicleSimulationContext); } } } } void stepPhysics() { if(gNbCommands == gCommandProgress) return; const PxF32 timestep = 0.0166667f; //Multithreaded update of all vehicles. concurrentVehicleUpdates(timestep); //Forward integrate the phsyx scene by a single timestep. SNIPPET_PROFILE_ZONE(UpdatePhases::ePHYSX_SCENE_SIMULATE); gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if(gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } gNbSimulateSteps++; } int snippetMain(int argc, const char*const* argv) { if(!parseVehicleDataPath(argc, argv, "SnippetVehicle2Multithreading", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. DirectDrivetrainParams directDrivetrainParams; if (!readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", baseParams.axleDescription, directDrivetrainParams)) return 1; printf("Initialising ... \n"); if(initPhysics()) { printf("Simulating %d vehicles with %d threads \n", NUM_VEHICLES, NUM_WORKER_THREADS); while(gCommandProgress != gNbCommands) { stepPhysics(); } printf("Completed %d simulate steps with %d substeps per simulate step \n", gNbSimulateSteps, NB_SUBSTEPS); gProfileZones.print(); cleanupPhysics(); } return 0; }
21,867
C++
32.437309
127
0.755339
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsoftbody/SnippetSoftBody.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates how to setup softbodies. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetsoftbody/SnippetSoftBody.h" #include "../snippetsoftbody/MeshGenerator.h" #include "extensions/PxTetMakerExt.h" #include "extensions/PxSoftBodyExt.h" using namespace physx; using namespace meshgenerator; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxCudaContextManager* gCudaContextManager = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; std::vector<SoftBody> gSoftBodies; void addSoftBody(PxSoftBody* softBody, const PxFEMParameters& femParams, const PxTransform& transform, const PxReal density, const PxReal scale, const PxU32 iterCount) { PxVec4* simPositionInvMassPinned; PxVec4* simVelocityPinned; PxVec4* collPositionInvMassPinned; PxVec4* restPositionPinned; PxSoftBodyExt::allocateAndInitializeHostMirror(*softBody, gCudaContextManager, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); const PxReal maxInvMassRatio = 50.f; softBody->setParameter(femParams); softBody->setSolverIterationCounts(iterCount); PxSoftBodyExt::transform(*softBody, transform, scale, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); PxSoftBodyExt::updateMass(*softBody, density, maxInvMassRatio, simPositionInvMassPinned); PxSoftBodyExt::copyToDevice(*softBody, PxSoftBodyDataFlag::eALL, simPositionInvMassPinned, simVelocityPinned, collPositionInvMassPinned, restPositionPinned); SoftBody sBody(softBody, gCudaContextManager); gSoftBodies.push_back(sBody); PX_PINNED_HOST_FREE(gCudaContextManager, simPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, simVelocityPinned); PX_PINNED_HOST_FREE(gCudaContextManager, collPositionInvMassPinned); PX_PINNED_HOST_FREE(gCudaContextManager, restPositionPinned); } static PxSoftBody* createSoftBody(const PxCookingParams& params, const PxArray<PxVec3>& triVerts, const PxArray<PxU32>& triIndices, bool useCollisionMeshForSimulation = false) { PxSoftBodyMesh* softBodyMesh; PxU32 numVoxelsAlongLongestAABBAxis = 8; PxSimpleTriangleMesh surfaceMesh; surfaceMesh.points.count = triVerts.size(); surfaceMesh.points.data = triVerts.begin(); surfaceMesh.triangles.count = triIndices.size() / 3; surfaceMesh.triangles.data = triIndices.begin(); if (useCollisionMeshForSimulation) { softBodyMesh = PxSoftBodyExt::createSoftBodyMeshNoVoxels(params, surfaceMesh, gPhysics->getPhysicsInsertionCallback()); } else { softBodyMesh = PxSoftBodyExt::createSoftBodyMesh(params, surfaceMesh, numVoxelsAlongLongestAABBAxis, gPhysics->getPhysicsInsertionCallback()); } //Alternatively one can cook a softbody mesh in a single step //tetMesh = cooking.createSoftBodyMesh(simulationMeshDesc, collisionMeshDesc, softbodyDesc, physics.getPhysicsInsertionCallback()); PX_ASSERT(softBodyMesh); if (!gCudaContextManager) return NULL; PxSoftBody* softBody = gPhysics->createSoftBody(*gCudaContextManager); if (softBody) { PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE; PxFEMSoftBodyMaterial* materialPtr = PxGetPhysics().createFEMSoftBodyMaterial(1e+6f, 0.45f, 0.5f); PxTetrahedronMeshGeometry geometry(softBodyMesh->getCollisionMesh()); PxShape* shape = gPhysics->createShape(geometry, &materialPtr, 1, true, shapeFlags); if (shape) { softBody->attachShape(*shape); shape->setSimulationFilterData(PxFilterData(0, 0, 2, 0)); } softBody->attachSimulationMesh(*softBodyMesh->getSimulationMesh(), *softBodyMesh->getSoftBodyAuxData()); gScene->addActor(*softBody); PxFEMParameters femParams; addSoftBody(softBody, femParams, PxTransform(PxVec3(0.f, 0.f, 0.f), PxQuat(PxIdentity)), 100.f, 1.0f, 30); softBody->setSoftBodyFlag(PxSoftBodyFlag::eDISABLE_SELF_COLLISION, true); } return softBody; } static void createSoftbodies(const PxCookingParams& params) { PxArray<PxVec3> triVerts; PxArray<PxU32> triIndices; PxReal maxEdgeLength = 1; createCube(triVerts, triIndices, PxVec3(0, 9, 0), 2.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); createSoftBody(params, triVerts, triIndices, true); createSphere(triVerts, triIndices, PxVec3(0, 4.5, 0), 2.5, maxEdgeLength); createSoftBody(params, triVerts, triIndices); createConeY(triVerts, triIndices, PxVec3(0, 11.5, 0), 2.0f, 3.5); PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength); createSoftBody(params, triVerts, triIndices); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); // initialize cuda PxCudaContextManagerDesc cudaContextManagerDesc; gCudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (gCudaContextManager && !gCudaContextManager->contextIsValid()) { gCudaContextManager->release(); gCudaContextManager = NULL; printf("Failed to initialize cuda context.\n"); } PxTolerancesScale scale; gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, scale, true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxCookingParams params(scale); params.meshWeldTolerance = 0.001f; params.meshPreprocessParams = PxMeshPreprocessingFlags(PxMeshPreprocessingFlag::eWELD_VERTICES); params.buildTriangleAdjacencies = false; params.buildGPUData = true; PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); if (!sceneDesc.cudaContextManager) sceneDesc.cudaContextManager = gCudaContextManager; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_ACTIVE_ACTORS; sceneDesc.sceneQueryUpdateMode = PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_DISABLED; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.gpuMaxNumPartitions = 8; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); createSoftbodies(params); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; gScene->simulate(dt); gScene->fetchResults(true); for (PxU32 i = 0; i < gSoftBodies.size(); i++) { SoftBody* sb = &gSoftBodies[i]; sb->copyDeformedVerticesFromGPU(); } } void cleanupPhysics(bool /*interactive*/) { for (PxU32 i = 0; i < gSoftBodies.size(); i++) gSoftBodies[i].release(); gSoftBodies.clear(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); gCudaContextManager->release(); PX_RELEASE(gFoundation); printf("Snippet Softbody done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
10,158
C++
36.765799
175
0.767769
NVIDIA-Omniverse/PhysX/physx/snippets/snippetsplitfetchresults/SnippetSplitFetchResults.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates the use of split fetchResults() calls to improve // the performace contact report processing. // // It defines a filter shader function that requests touch reports for // all pairs, and a contact callback function that saves the contact points. // It configures the scene to use this filter and callback, and prints the // number of contact reports each frame. If rendering, it renders each // contact as a line whose length and direction are defined by the contact // impulse. The callback can be processed earlier than usual by using the // split fetchResults() sequence of fetchResultsStart(), processCallbacks(), // fetchResultsFinish(). // // **************************************************************************** #include <vector> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "foundation/PxAtomic.h" #include "task/PxTask.h" #define PARALLEL_CALLBACKS 1 using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; const PxI32 maxCount = 10000; PxI32 gSharedIndex = 0; PxVec3* gContactPositions; PxVec3* gContactImpulses; PxVec3* gContactVertices; class CallbackFinishTask : public PxLightCpuTask { SnippetUtils::Sync* mSync; public: CallbackFinishTask(){ mSync = SnippetUtils::syncCreate(); } virtual void release() { PxLightCpuTask::release(); SnippetUtils::syncSet(mSync); } void reset() { SnippetUtils::syncReset(mSync); } void wait() { SnippetUtils::syncWait(mSync); } virtual void run() { /*Do nothing - release the sync in the release method for thread-safety*/} virtual const char* getName() const { return "CallbackFinishTask"; } } callbackFinishTask; PxFilterFlags contactReportFilterShader(PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(attributes1); PX_UNUSED(filterData0); PX_UNUSED(filterData1); PX_UNUSED(constantBlockSize); PX_UNUSED(constantBlock); // all initial and persisting reports for everything, with per-point data pairFlags = PxPairFlag::eSOLVE_CONTACT | PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eNOTIFY_TOUCH_FOUND | PxPairFlag::eNOTIFY_TOUCH_PERSISTS | PxPairFlag::eNOTIFY_CONTACT_POINTS; return PxFilterFlag::eDEFAULT; } class ContactReportCallback : public PxSimulationEventCallback { void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) { PX_UNUSED(constraints); PX_UNUSED(count); } void onWake(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onSleep(PxActor** actors, PxU32 count) { PX_UNUSED(actors); PX_UNUSED(count); } void onTrigger(PxTriggerPair* pairs, PxU32 count) { PX_UNUSED(pairs); PX_UNUSED(count); } void onAdvance(const PxRigidBody*const*, const PxTransform*, const PxU32) {} void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) { PX_UNUSED((pairHeader)); //Maximum of 64 vertices can be produced by contact gen PxContactPairPoint contactPoints[64]; for (PxU32 i = 0; i<nbPairs; i++) { PxU32 contactCount = pairs[i].contactCount; if (contactCount) { pairs[i].extractContacts(&contactPoints[0], contactCount); PxI32 startIdx = physx::PxAtomicAdd(&gSharedIndex, int32_t(contactCount)); for (PxU32 j = 0; j<contactCount; j++) { gContactPositions[startIdx+j] = contactPoints[j].position; gContactImpulses[startIdx+j] = contactPoints[j].impulse; gContactVertices[2*(startIdx + j)] = contactPoints[j].position; gContactVertices[2*(startIdx + j) + 1] = contactPoints[j].position + contactPoints[j].impulse * 0.1f; } } } } }; ContactReportCallback gContactReportCallback; void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i<size; i++) { for (PxU32 j = 0; j<size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } void initPhysics(bool /*interactive*/) { gContactPositions = new PxVec3[maxCount]; gContactImpulses = new PxVec3[maxCount]; gContactVertices = new PxVec3[2*maxCount]; gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.gravity = PxVec3(0, -9.81f, 0); sceneDesc.filterShader = contactReportFilterShader; sceneDesc.simulationEventCallback = &gContactReportCallback; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); const PxU32 nbStacks = 50; for (PxU32 i = 0; i < nbStacks; ++i) { createStack(PxTransform(PxVec3(0, 3.0f, 10.f - 5.f*i)), 5, 2.0f); } } void stepPhysics(bool /*interactive*/) { gSharedIndex = 0; gScene->simulate(1.0f / 60.0f); #if !PARALLEL_CALLBACKS gScene->fetchResults(true); #else //Call fetchResultsStart. Get the set of pair headers const PxContactPairHeader* pairHeader; PxU32 nbContactPairs; gScene->fetchResultsStart(pairHeader, nbContactPairs, true); //Set up continuation task to be run after callbacks have been processed in parallel callbackFinishTask.setContinuation(*gScene->getTaskManager(), NULL); callbackFinishTask.reset(); //process the callbacks gScene->processCallbacks(&callbackFinishTask); callbackFinishTask.removeReference(); callbackFinishTask.wait(); gScene->fetchResultsFinish(); #endif printf("%d contact reports\n", PxU32(gSharedIndex)); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); delete gContactPositions; delete gContactImpulses; delete gContactVertices; printf("SnippetSplitFetchResults done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else initPhysics(false); for (PxU32 i = 0; i<250; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
9,427
C++
33.534798
113
0.73735
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2truck/SnippetVehicleTruck.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of the physx vehicle sdk and demonstrates // how to simulate multiple vehicles jointed together. The snippet introduces // the simple example of a tractor pulling a trailer. The wheels of the tractor // respond to brake, throttle and steer. The trailer, on the other hand, has no // engine or steering column and is only able to apply brake torques to the wheels. // The snippet uses only parameters, states and components maintained by the PhysX Vehicle SDK. // Vehicles are made of parameters, states and components. // Parameters describe the configuration of a vehicle. Examples are vehicle mass, wheel radius // and suspension stiffness. // States describe the instantaneous dynamic state of a vehicle. Examples are engine revs, wheel // yaw angle and tire slip angles. // Components forward integrate the dynamic state of the vehicle, given the previous vehicle state // and the vehicle's parameterisation. // Components update dynamic state by invoking reusable functions in a particular sequence. // An example component is a rigid body component that updates the linear and angular velocity of // the vehicle's rigid body given the instantaneous forces and torques of the suspension and tire // states. // The pipeline of vehicle computation is a sequence of components that run in order. For example, // one component might compute the plane under the wheel by performing a scene query against the // world geometry. The next component in the sequence might compute the suspension compression required // to place the wheel on the surface of the hit plane. Following this, another component might compute // the suspension force that arises from that compression. The rigid body component, as discussed earlier, // can then forward integrate the rigid body's linear velocity using the suspension force. // Custom combinations of parameter, state and component allow different behaviours to be simulated with // different simulation fidelities. For example, a suspension component that implements a linear force // response with respect to its compression state could be replaced with one that imlements a non-linear // response. The replacement component would consume the same suspension compression state data and // would output the same suspension force data structure. In this example, the change has been localised // to the component that converts suspension compression to force and to the parameterisation that governs // that conversion. // Another combination example could be the replacement of the tire component from a low fidelity model to // a high fidelty model such as Pacejka. The low and high fidelity components consume the same state data // (tire slip, load, friction) and output the same state data for the tire forces. Again, the // change has been localised to the component that converts slip angle to tire force and the // parameterisation that governs the conversion. //The PhysX Vehicle SDK presents a maintained set of parameters, states and components. The maintained //set of parameters, states and components may be combined on their own or combined with custom parameters, //states and components. //This snippet breaks the vehicle into into three distinct models: //1) a base vehicle model that describes the mechanical configuration of suspensions, tires, wheels and an // associated rigid body. //2) a drivetrain model that forwards input controls to wheel torques via a drivetrain model // that includes engine, clutch, differential and gears. //3) a physx integration model that provides a representation of the vehicle in an associated physx scene. // It is a good idea to record and playback with pvd (PhysX Visual Debugger). // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/enginedrivetrain/EngineDrivetrain.h" #include "../snippetvehicle2common/serialization/BaseSerialization.h" #include "../snippetvehicle2common/serialization/EngineDrivetrainSerialization.h" #include "../snippetvehicle2common/serialization/DirectDrivetrainSerialization.h" #include "../snippetvehicle2common/SnippetVehicleHelpers.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; using namespace physx::vehicle2; using namespace snippetvehicle2; //PhysX management class instances. PxDefaultAllocator gAllocator; PxDefaultErrorCallback gErrorCallback; PxFoundation* gFoundation = NULL; PxPhysics* gPhysics = NULL; PxDefaultCpuDispatcher* gDispatcher = NULL; PxScene* gScene = NULL; PxMaterial* gMaterial = NULL; PxPvd* gPvd = NULL; //The path to the vehicle json files to be loaded. const char* gVehicleDataPath = NULL; //The tractor with engine drivetrain. //The trailer with direct drivetrain //A joint connecting the two vehicles together. EngineDriveVehicle gTractor; DirectDriveVehicle gTrailer; PxD6Joint* gJoint = NULL; //Vehicle simulation needs a simulation context //to store global parameters of the simulation such as //gravitational acceleration. PxVehiclePhysXSimulationContext gVehicleSimulationContext; //Gravitational acceleration const PxVec3 gGravity(0.0f, -9.81f, 0.0f); //The mapping between PxMaterial and friction. PxVehiclePhysXMaterialFriction gPhysXMaterialFrictions[16]; PxU32 gNbPhysXMaterialFrictions = 0; PxReal gPhysXDefaultMaterialFriction = 1.0f; //Give the vehicles names so they can be identified in PVD. const char gTractorName[] = "tractor"; const char gTrailerName[] = "trailer"; //Commands are issued to the vehicles in a pre-choreographed sequence. //Note: // the tractor responds to brake, throttle and steer commands. // the trailer responds only to brake commands. struct Command { PxF32 brake; PxF32 throttle; PxF32 steer; PxU32 gear; PxF32 duration; }; const PxU32 gTargetGearCommand = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; Command gCommands[] = { {0.5f, 0.0f, 0.0f, gTargetGearCommand, 2.0f}, //brake on and come to rest for 2 seconds {0.0f, 0.65f, 0.0f, gTargetGearCommand, 5.0f}, //throttle for 5 seconds {0.5f, 0.0f, 0.0f, gTargetGearCommand, 5.0f}, //brake for 5 seconds {0.0f, 0.75f, 0.0f, gTargetGearCommand, 5.0f} //throttle for 5 seconds }; const PxU32 gNbCommands = sizeof(gCommands) / sizeof(Command); PxReal gCommandTime = 0.0f; //Time spent on current command PxU32 gCommandProgress = 0; //The id of the current command. //A ground plane to drive on. PxRigidStatic* gGroundPlane = NULL; void initPhysX() { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = gGravity; PxU32 numWorkers = 1; gDispatcher = PxDefaultCpuDispatcherCreate(numWorkers); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = VehicleFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, false); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxInitExtensions(*gPhysics, gPvd); PxInitVehicleExtension(*gFoundation); } void cleanupPhysX() { PxCloseVehicleExtension(); PxCloseExtensions(); PX_RELEASE(gMaterial); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if (gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); } PX_RELEASE(gFoundation); } void initGroundPlane() { gGroundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); for (PxU32 i = 0; i < gGroundPlane->getNbShapes(); i++) { PxShape* shape = NULL; gGroundPlane->getShapes(&shape, 1, i); shape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, true); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, false); } gScene->addActor(*gGroundPlane); } void cleanupGroundPlane() { gGroundPlane->release(); } void initMaterialFrictionTable() { //Each physx material can be mapped to a tire friction value on a per tire basis. //If a material is encountered that is not mapped to a friction value, the friction value used is the specified default value. //In this snippet there is only a single material so there can only be a single mapping between material and friction. //In this snippet the same mapping is used by all tires. gPhysXMaterialFrictions[0].friction = 1.0f; gPhysXMaterialFrictions[0].material = gMaterial; gPhysXDefaultMaterialFriction = 1.0f; gNbPhysXMaterialFrictions = 1; } bool initVehicles() { //Load the tractor params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gTractor.mBaseParams); setPhysXIntegrationParams(gTractor.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gTractor.mPhysXParams); readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", gTractor.mEngineDriveParams); //Load the trailer params from json or set directly. readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", gTrailer.mBaseParams); setPhysXIntegrationParams(gTrailer.mBaseParams.axleDescription, gPhysXMaterialFrictions, gNbPhysXMaterialFrictions, gPhysXDefaultMaterialFriction, gTrailer.mPhysXParams); readDirectDrivetrainParamsFromJsonFile(gVehicleDataPath, "DirectDrive.json", gTrailer.mBaseParams.axleDescription, gTrailer.mDirectDriveParams); //Set the states to default. if (!gTractor.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial, EngineDriveVehicle::eDIFFTYPE_FOURWHEELDRIVE)) { return false; } if (!gTrailer.initialize(*gPhysics, PxCookingParams(PxTolerancesScale()), *gMaterial)) { return false; } //Create a PhysX joint to connect tractor and trailer. //Create a joint anchor that is 1.5m behind the rear wheels of the tractor and 1.5m in front of the front wheels of the trailer. PxTransform anchorTractorFrame(PxIdentity); { //Rear wheels are 2 and 3. PxRigidBody* rigidActor = gTractor.mPhysXState.physxActor.rigidBody; const PxTransform cMassLocalPoseActorFrame = rigidActor->getCMassLocalPose(); const PxVec3 frontAxlePosCMassFrame = (gTractor.mBaseParams.suspensionParams[2].suspensionAttachment.p + gTractor.mBaseParams.suspensionParams[3].suspensionAttachment.p)*0.5f; const PxQuat frontAxleQuatCMassFrame = gTractor.mBaseParams.suspensionParams[2].suspensionAttachment.q; const PxTransform anchorCMassFrame(frontAxlePosCMassFrame - PxVec3(0, 0, 1.5f), frontAxleQuatCMassFrame); anchorTractorFrame = cMassLocalPoseActorFrame * anchorCMassFrame; } PxTransform anchorTrailerFrame(PxIdentity); { //Front wheels are 0 and 1. PxRigidBody* rigidActor = gTrailer.mPhysXState.physxActor.rigidBody; const PxTransform cMassLocalPoseActorFrame = rigidActor->getCMassLocalPose(); const PxVec3 rearAxlePosCMassFrame = (gTrailer.mBaseParams.suspensionParams[0].suspensionAttachment.p + gTractor.mBaseParams.suspensionParams[1].suspensionAttachment.p)*0.5f; const PxQuat rearAxleQuatCMassFrame = gTrailer.mBaseParams.suspensionParams[0].suspensionAttachment.q; const PxTransform anchorCMassFrame(rearAxlePosCMassFrame + PxVec3(0, 0, 1.5f), rearAxleQuatCMassFrame); anchorTrailerFrame = cMassLocalPoseActorFrame * anchorCMassFrame; } //Apply a start pose to the physx actor of tractor and trailer and add them to the physx scene. const PxTransform tractorPose(PxVec3(0.000000000f, -0.0500000119f, -1.59399998f), PxQuat(PxIdentity)); gTractor.setUpActor(*gScene, tractorPose, gTractorName); const PxTransform trailerPose = tractorPose*anchorTractorFrame*anchorTrailerFrame.getInverse(); gTrailer.setUpActor(*gScene, trailerPose, gTrailerName); //Create a joint between tractor and trailer. { gJoint = PxD6JointCreate(*gPhysics, gTractor.mPhysXState.physxActor.rigidBody, anchorTractorFrame, gTrailer.mPhysXState.physxActor.rigidBody, anchorTrailerFrame); gJoint->setMotion(PxD6Axis::eX, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eY, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eZ, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eTWIST, PxD6Motion::eLOCKED); gJoint->setMotion(PxD6Axis::eSWING1, PxD6Motion::eFREE); gJoint->setMotion(PxD6Axis::eSWING2, PxD6Motion::eFREE); gJoint->getConstraint()->setFlags(gJoint->getConstraint()->getFlags() | PxConstraintFlag::eCOLLISION_ENABLED); } //Set the tractor in 1st gear and to use the autobox gTractor.mEngineDriveState.gearboxState.currentGear = gTractor.mEngineDriveParams.gearBoxParams.neutralGear + 1; gTractor.mEngineDriveState.gearboxState.targetGear = gTractor.mEngineDriveParams.gearBoxParams.neutralGear + 1; gTractor.mTransmissionCommandState.targetGear = PxVehicleEngineDriveTransmissionCommandState::eAUTOMATIC_GEAR; //Set the trailer in neutral gear to prevent any drive torques being applied to the trailer. gTrailer.mTransmissionCommandState.gear = PxVehicleDirectDriveTransmissionCommandState::eNEUTRAL; //Set up the simulation context. //The snippet is set up with //a) z as the longitudinal axis //b) x as the lateral axis //c) y as the vertical axis. //d) metres as the lengthscale. gVehicleSimulationContext.setToDefault(); gVehicleSimulationContext.frame.lngAxis = PxVehicleAxes::ePosZ; gVehicleSimulationContext.frame.latAxis = PxVehicleAxes::ePosX; gVehicleSimulationContext.frame.vrtAxis = PxVehicleAxes::ePosY; gVehicleSimulationContext.scale.scale = 1.0f; gVehicleSimulationContext.gravity = gGravity; gVehicleSimulationContext.physxScene = gScene; gVehicleSimulationContext.physxActorUpdateMode = PxVehiclePhysXActorUpdateMode::eAPPLY_ACCELERATION; return true; } void cleanupVehicles() { gJoint->release(); gTractor.destroy(); gTrailer.destroy(); } bool initPhysics() { initPhysX(); initGroundPlane(); initMaterialFrictionTable(); if (!initVehicles()) return false; return true; } void cleanupPhysics() { cleanupVehicles(); cleanupGroundPlane(); cleanupPhysX(); } void stepPhysics() { if (gNbCommands == gCommandProgress) return; const PxReal timestep = 1.0f/60.0f; //Apply the brake, throttle and steer to the command state of the tractor. const Command& command = gCommands[gCommandProgress]; gTractor.mCommandState.brakes[0] = command.brake; gTractor.mCommandState.nbBrakes = 1; gTractor.mCommandState.throttle = command.throttle; gTractor.mCommandState.steer = command.steer; gTractor.mTransmissionCommandState.targetGear = command.gear; //Apply the brake to the command state of the trailer. gTrailer.mCommandState.brakes[0] = command.brake; gTrailer.mCommandState.nbBrakes = 1; //Apply substepping at low forward speed to improve simulation fidelity. //Tractor and trailer will have approximately the same forward speed so we can apply //the same substepping rules to the tractor and trailer. const PxVec3 linVel = gTractor.mPhysXState.physxActor.rigidBody->getLinearVelocity(); const PxVec3 forwardDir = gTractor.mPhysXState.physxActor.rigidBody->getGlobalPose().q.getBasisVector2(); const PxReal forwardSpeed = linVel.dot(forwardDir); const PxU8 nbSubsteps = (forwardSpeed < 5.0f ? 3 : 1); gTractor.mComponentSequence.setSubsteps(gTractor.mComponentSequenceSubstepGroupHandle, nbSubsteps); gTrailer.mComponentSequence.setSubsteps(gTrailer.mComponentSequenceSubstepGroupHandle, nbSubsteps); //Reset the sticky states on the trailer using the actuation state of the truck. //Vehicles are brought to rest with sticky constraints that apply velocity constraints to the tires of the vehicle. //A drive torque applied to any wheel of the tractor signals an intent to accelerate. //An intent to accelerate will release any sticky constraints applied to the tires of the tractor. //It is important to apply the intent to accelerate to the wheels of the trailer as well to prevent the trailer being //held at rest with its own sticky constraints. //It is not possible to determine an intent to accelerate from the trailer alone because the wheels of the trailer //do not respond to the throttle commands and therefore receive zero drive torque. //The function PxVehicleTireStickyStateReset() will reset the sticky states of the trailer using an intention to //accelerate derived from the state of the tractor. const PxVehicleArrayData<const PxVehicleWheelActuationState> tractorActuationStates(gTractor.mBaseState.actuationStates); PxVehicleArrayData<PxVehicleTireStickyState> trailerTireStickyStates(gTrailer.mBaseState.tireStickyStates); const bool intentionToAccelerate = PxVehicleAccelerationIntentCompute(gTractor.mBaseParams.axleDescription, tractorActuationStates); PxVehicleTireStickyStateReset(intentionToAccelerate, gTrailer.mBaseParams.axleDescription, trailerTireStickyStates); //Forward integrate the vehicles by a single timestep. gTractor.step(timestep, gVehicleSimulationContext); gTrailer.step(timestep, gVehicleSimulationContext); //Forward integrate the phsyx scene by a single timestep. gScene->simulate(timestep); gScene->fetchResults(true); //Increment the time spent on the current command. //Move to the next command in the list if enough time has lapsed. gCommandTime += timestep; if (gCommandTime > gCommands[gCommandProgress].duration) { gCommandProgress++; gCommandTime = 0.0f; } } int snippetMain(int argc, const char*const* argv) { if (!parseVehicleDataPath(argc, argv, "SnippetVehicle2Truck", gVehicleDataPath)) return 1; //Check that we can read from the json file before continuing. BaseVehicleParams baseParams; if (!readBaseParamsFromJsonFile(gVehicleDataPath, "Base.json", baseParams)) return 1; //Check that we can read from the json file before continuing. EngineDrivetrainParams engineDrivetrainParams; if (!readEngineDrivetrainParamsFromJsonFile(gVehicleDataPath, "EngineDrive.json", engineDrivetrainParams)) return 1; #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else if (initPhysics()) { while (gCommandProgress != gNbCommands) { stepPhysics(); } cleanupPhysics(); } #endif return 0; }
20,422
C++
43.494553
177
0.781804
NVIDIA-Omniverse/PhysX/physx/snippets/snippetccd/SnippetCCD.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates how to use different types of CCD methods, // including linear, raycast and speculative CCD. // // The scene has two parts: // - a simple box stack and a fast moving sphere. Without (linear) CCD the // sphere goes through the box stack. With CCD the sphere hits the stack and // the behavior is more convincing. // - a simple rotating plank (fixed in space except for one rotation axis) // that collides with a falling box. Wihout (angular) CCD the collision is missed. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "extensions/PxRaycastCCD.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static RaycastCCDManager* gRaycastCCD = NULL; static PxReal stackZ = 10.0f; enum CCDAlgorithm { // Uses linear CCD algorithm LINEAR_CCD, // Uses speculative/angular CCD algorithm SPECULATIVE_CCD, // Uses linear & angular CCD at the same time FULL_CCD, // Uses raycast CCD algorithm RAYCAST_CCD, // Switch to NO_CCD to see the sphere go through the box stack without CCD. NO_CCD, // Number of CCD algorithms used in this snippet CCD_COUNT }; static bool gPause = false; static bool gOneFrame = false; static const PxU32 gScenarioCount = CCD_COUNT; static PxU32 gScenario = 0; static PX_FORCE_INLINE CCDAlgorithm getCCDAlgorithm() { return CCDAlgorithm(gScenario); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0), bool enableLinearCCD = false, bool enableSpeculativeCCD = false) { PX_ASSERT(gScene); PxRigidDynamic* dynamic = NULL; if(gScene) { dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); if(enableLinearCCD) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if(enableSpeculativeCCD) dynamic->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); } return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent, bool enableLinearCCD = false, bool enableSpeculativeCCD = false) { PX_ASSERT(gScene); if(!gScene) return; PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); PX_ASSERT(shape); if(!shape) return; for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { const PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); if(enableLinearCCD) body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); if(enableSpeculativeCCD) body->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, true); gScene->addActor(*body); } } shape->release(); } static PxFilterFlags ccdFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize) { PX_UNUSED(attributes0); PX_UNUSED(filterData0); PX_UNUSED(attributes1); PX_UNUSED(filterData1); PX_UNUSED(constantBlock); PX_UNUSED(constantBlockSize); pairFlags = PxPairFlag::eSOLVE_CONTACT | PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eDETECT_CCD_CONTACT; return PxFilterFlags(); } static void registerForRaycastCCD(PxRigidDynamic* actor) { if(actor) { PxShape* shape = NULL; actor->getShapes(&shape, 1); // Register each object for which CCD should be enabled. In this snippet we only enable it for the sphere. gRaycastCCD->registerRaycastCCDObject(actor, shape); } } static void initScene() { PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; bool enableLinearCCD = false; bool enableSpeculativeCCD = false; const CCDAlgorithm ccd = getCCDAlgorithm(); if(ccd == LINEAR_CCD) { enableLinearCCD = true; sceneDesc.filterShader = ccdFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; gScene = gPhysics->createScene(sceneDesc); printf("- Using linear CCD.\n"); } else if(ccd == SPECULATIVE_CCD) { enableSpeculativeCCD = true; gScene = gPhysics->createScene(sceneDesc); printf("- Using speculative/angular CCD.\n"); } else if(ccd == FULL_CCD) { enableLinearCCD = true; enableSpeculativeCCD = true; sceneDesc.filterShader = ccdFilterShader; sceneDesc.flags |= PxSceneFlag::eENABLE_CCD; gScene = gPhysics->createScene(sceneDesc); printf("- Using full CCD.\n"); } else if(ccd == RAYCAST_CCD) { gScene = gPhysics->createScene(sceneDesc); gRaycastCCD = new RaycastCCDManager(gScene); printf("- Using raycast CCD.\n"); } else if(ccd == NO_CCD) { gScene = gPhysics->createScene(sceneDesc); printf("- Using no CCD.\n"); } // Create a scenario that requires angular CCD: a rotating plank colliding with a falling box. { PxRigidDynamic* actor = createDynamic(PxTransform(PxVec3(40.0f, 20.0f, 0.0f)), PxBoxGeometry(10.0f, 1.0f, 0.1f), PxVec3(0.0f), enableLinearCCD, enableSpeculativeCCD); actor->setAngularVelocity(PxVec3(0.0f, 10.0f, 0.0f)); actor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_X, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_Y, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_LINEAR_Z, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_X, true); actor->setRigidDynamicLockFlag(PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z, true); if(gRaycastCCD) registerForRaycastCCD(actor); PxRigidDynamic* actor2 = createDynamic(PxTransform(PxVec3(40.0f, 20.0f, 10.0f)), PxBoxGeometry(0.1f, 1.0f, 1.0f), PxVec3(0.0f), enableLinearCCD, enableSpeculativeCCD); if(gRaycastCCD) registerForRaycastCCD(actor2); } // Create a scenario that requires linear CCD: a fast moving sphere moving towards a box stack. { PxRigidDynamic* actor = createDynamic(PxTransform(PxVec3(0.0f, 18.0f, 100.0f)), PxSphereGeometry(2.0f), PxVec3(0.0f, 0.0f, -1000.0f), enableLinearCCD, enableSpeculativeCCD); if(gRaycastCCD) registerForRaycastCCD(actor); createStack(PxTransform(PxVec3(0, 0, stackZ)), 10, 2.0f, enableLinearCCD, enableSpeculativeCCD); PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); } PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F4 to select a scenario."); switch(PxU32(gScenario)) { case 0: { Snippets::print("Current scenario: linear CCD"); }break; case 1: { Snippets::print("Current scenario: angular CCD"); }break; case 2: { Snippets::print("Current scenario: linear + angular CCD"); }break; case 3: { Snippets::print("Current scenario: raycast CCD"); }break; case 4: { Snippets::print("Current scenario: no CCD"); }break; } #endif } void initPhysics(bool /*interactive*/) { printf("CCD snippet. Use these keys:\n"); printf(" P - enable/disable pause\n"); printf(" O - step simulation for one frame\n"); printf(" R - reset scene\n"); printf(" F1 to F4 - select scenes with different CCD algorithms\n"); printf(" F1 - Using linear CCD\n"); printf(" F2 - Using speculative/angular CCD\n"); printf(" F3 - Using full CCD (linear+angular)\n"); printf(" F4 - Using raycast CCD\n"); printf(" F5 - Using no CCD\n"); printf("\n"); gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true,gPvd); const PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.25f); initScene(); } void stepPhysics(bool /*interactive*/) { if (gPause && !gOneFrame) return; gOneFrame = false; gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); // Simply call this after fetchResults to perform CCD raycasts. if(gRaycastCCD) gRaycastCCD->doRaycastCCD(true); } static void releaseScene() { PX_RELEASE(gScene); PX_DELETE(gRaycastCCD); } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetCCD done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key == 'p' || key == 'P') gPause = !gPause; if(key == 'o' || key == 'O') { gPause = true; gOneFrame = true; } if(gScene) { if(key >= 1 && key <= gScenarioCount) { gScenario = key - 1; releaseScene(); initScene(); } if(key == 'r' || key == 'R') { releaseScene(); initScene(); } } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,270
C++
29.90932
185
0.721027
NVIDIA-Omniverse/PhysX/physx/snippets/snippetspatialtendon/SnippetSpatialTendonRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; extern PxRigidStatic** getAttachments(); extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); Snippets::startRender(sCamera); const PxVec3 attachmentColor(0.25f, 1.0f, 0.5f); const PxVec3 tendonColor(0.8f); const PxVec3 dynLinkColor(1.0f, 0.5f, 0.25f); const PxVec3 baseLinkColor(0.5f, 0.25f, 1.0f); PxScene* scene; PxGetPhysics().getScenes(&scene, 1); PxU32 nbArticulations = scene->getNbArticulations(); for(PxU32 i = 0; i < nbArticulations; i++) { PxArticulationReducedCoordinate* articulation; scene->getArticulations(&articulation, 1, i); const PxU32 nbLinks = articulation->getNbLinks(); std::vector<PxArticulationLink*> links(nbLinks); articulation->getLinks(&links[0], nbLinks); const PxU32 numLinks = static_cast<PxU32>(links.size()); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[0]), 1, true, baseLinkColor); Snippets::renderActors(reinterpret_cast<PxRigidActor**>(&links[1]), numLinks - 1, true, dynLinkColor); } // render attachments and tendon connecting the attachments: Snippets::renderActors(reinterpret_cast<PxRigidActor**>(getAttachments()), 6, true, attachmentColor, NULL, false, false); Snippets::DrawLine(getAttachments()[0]->getGlobalPose().p, getAttachments()[1]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[0]->getGlobalPose().p, getAttachments()[2]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[3]->getGlobalPose().p, getAttachments()[4]->getGlobalPose().p, tendonColor); Snippets::DrawLine(getAttachments()[3]->getGlobalPose().p, getAttachments()[5]->getGlobalPose().p, tendonColor); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { const PxVec3 camEye(0.0f, 4.3f, 5.2f); const PxVec3 camDir(0.0f, -0.27f, -1.0f); sCamera = new Snippets::Camera(camEye, camDir); Snippets::setupDefault("PhysX Snippet Articulation Spatial Tendon", sCamera, NULL, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
4,077
C++
37.471698
122
0.753986
NVIDIA-Omniverse/PhysX/physx/snippets/snippetspatialtendon/SnippetSpatialTendon.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // ***************************************************************************************** // This snippet demonstrates the use of a spatial tendon to actuate a symmetric articulation // ***************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulations[2] = { NULL }; static const PxReal gGravity = 9.81f; static const PxReal gLinkHalfLength = 0.5f; PxRigidStatic** getAttachments() { static PxRigidStatic* attachments[6] = { NULL }; return attachments; } static void createSpatialTendonArticulation(PxArticulationReducedCoordinate* articulation, PxRigidStatic** attachmentRigidStatics, const PxVec3 offset) { // link geometry and density: const PxVec3 linkExtents(gLinkHalfLength, 0.05f, 0.05f); const PxBoxGeometry linkGeom = PxBoxGeometry(linkExtents); const PxReal density = 1000.0f; articulation->setArticulationFlags(PxArticulationFlag::eFIX_BASE); articulation->setSolverIterationCounts(10, 1); PxTransform pose = PxTransform(offset, PxQuat(PxIdentity)); pose.p.y += 3.0f; PxArticulationLink* baseLink = articulation->createLink(NULL, pose); PxRigidActorExt::createExclusiveShape(*baseLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*baseLink, density); pose.p.x -= linkExtents.x * 2.0f; PxArticulationLink* leftLink = articulation->createLink(baseLink, pose); PxRigidActorExt::createExclusiveShape(*leftLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*leftLink, density); pose.p.x += linkExtents.x * 4.0f; PxArticulationLink* rightLink = articulation->createLink(baseLink, pose); PxRigidActorExt::createExclusiveShape(*rightLink, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*rightLink, density); // setup revolute joints: { PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(leftLink->getInboundJoint()); if(joint) { PxVec3 parentOffset(-linkExtents.x, 0.0f, 0.0f); PxVec3 childOffset(linkExtents.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } { PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(rightLink->getInboundJoint()); if(joint) { PxVec3 parentOffset(linkExtents.x, 0.0f, 0.0f); PxVec3 childOffset(-linkExtents.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } // tendon stiffness sizing: // scale articulation geometry: // r: root attachment on left moving link // a: attachment on fixed-base link // l: leaf attachment on right moving link // o: revolute joint // a // // ----r----o---------o----l---- // The root and leaf attachment are at the center of mass of the moving links. // The attachment on the fixed-base link is a link halfLength above the link. // Therefore, the (rest)length of the tendon r-a-l when both joints are at zero is: // 2 * sqrt((2 * gLinkHalfLength)^2 + gLinkHalfLength^2) = 2 * gLinkHalfLength * sqrt(5) const PxReal restLength = 2.0f * gLinkHalfLength * PxSqrt(5.0f); // The goal is to have the revolute joints deviate just a few degrees from the horizontal // and we compute the length of the tendon at that angle: const PxReal deviationAngle = 3.0f * PxPi / 180.0f; // Distances from the base-link attachment to the root and leaf attachments const PxReal verticalDistance = gLinkHalfLength * (1.0f + PxSin(deviationAngle)); const PxReal horizontalDistance = gLinkHalfLength * (1.0f + PxCos(deviationAngle)); const PxReal deviatedLength = 2.0f * PxSqrt(verticalDistance * verticalDistance + horizontalDistance * horizontalDistance); // At rest, the force on the leaf attachment is (deviatedLength - restLength) * tendonStiffness. // This force needs to be equal to the gravity force acting on the link. An equal and opposing // (in the direction of the tendon) force acts on the root link and will hold that link up. // In order to calculate the tendon stiffness that produces that force, we consider the forces // and attachment geometry at zero joint angles. const PxReal linkMass = baseLink->getMass(); const PxReal gravityForce = gGravity * linkMass; // Project onto tendon at rest length / with joints at zero angle const PxReal tendonForce = gravityForce * PxSqrt(5.0f); // gravityForce * 0.5f * restLength / halfLength // and compute stiffness to get tendon force at deviated length to hold the link: const PxReal tendonStiffness = tendonForce / (deviatedLength - restLength); const PxReal tendonDamping = 0.3f * tendonStiffness; PxArticulationSpatialTendon* tendon = articulation->createSpatialTendon(); tendon->setStiffness(tendonStiffness); tendon->setDamping(tendonDamping); PxArticulationAttachment* rootAttachment = tendon->createAttachment(NULL, 1.0f, PxVec3(0.0f), leftLink); PxArticulationAttachment* baseAttachment = tendon->createAttachment(rootAttachment, 1.0f, PxVec3(0.0f, gLinkHalfLength, 0.0f), baseLink); PxArticulationAttachment* leafAttachment = tendon->createAttachment(baseAttachment, 1.0f, PxVec3(0.0f), rightLink); leafAttachment->setRestLength(restLength); // create attachment render shapes attachmentRigidStatics[0] = gPhysics->createRigidStatic(baseLink->getGlobalPose() * PxTransform(PxVec3(0.0f, gLinkHalfLength, 0.0f), PxQuat(PxIdentity))); attachmentRigidStatics[1] = gPhysics->createRigidStatic(leftLink->getGlobalPose()); attachmentRigidStatics[2] = gPhysics->createRigidStatic(rightLink->getGlobalPose()); PxSphereGeometry attachmentGeom(linkExtents.y * 1.5f); // slightly bigger than links to see the attachment on the moving links PxShape* attachmentShape = gPhysics->createShape(attachmentGeom, *gMaterial, false, PxShapeFlags(0)); for(PxU32 i = 0; i < 3; ++i) { PxRigidStatic* attachment = attachmentRigidStatics[i]; attachment->setActorFlag(PxActorFlag::eDISABLE_SIMULATION, true); // attachments are viz only attachment->attachShape(*attachmentShape); } // add articulation to scene: gScene->addArticulation(*articulation); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -gGravity, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); gArticulations[0] = gPhysics->createArticulationReducedCoordinate(); createSpatialTendonArticulation(gArticulations[0], getAttachments(), PxVec3(0.0f)); gArticulations[1] = gPhysics->createArticulationReducedCoordinate(); createSpatialTendonArticulation(gArticulations[1], &getAttachments()[3], PxVec3(0.0f, 0.0f, 2.0f)); } void stepPhysics(bool /*interactive*/) { const PxReal dt = 1.0f / 60.f; static PxReal time = 0.0f; // update articulation that actuates via tendon-length offset: { const PxReal amplitude = 0.3f; // move at 0.25 Hz, and offset sinusoid by an amplitude const PxReal offset = amplitude * (1.0f + PxSin(time * PxTwoPi * 0.25f - PxPiDivTwo)); PxArticulationSpatialTendon* tendon = NULL; gArticulations[0]->getSpatialTendons(&tendon, 1, 0); tendon->setOffset(offset); PxArticulationLink* links[3]; gArticulations[0]->getLinks(links, 3, 0); getAttachments()[1]->setGlobalPose(links[1]->getGlobalPose()); getAttachments()[2]->setGlobalPose(links[2]->getGlobalPose()); } // update articulation that actuates via base link attachment relative pose { const PxReal amplitude = 0.2f; // move at 0.25 Hz, and offset sinusoid by an amplitude const PxReal offset = gLinkHalfLength + amplitude * (1.0f + PxSin(time * PxTwoPi * 0.25f - PxPiDivTwo)); PxArticulationSpatialTendon* tendon = NULL; gArticulations[1]->getSpatialTendons(&tendon, 1, 0); PxArticulationAttachment* baseAttachment = NULL; tendon->getAttachments(&baseAttachment, 1, 1); baseAttachment->setRelativeOffset(PxVec3(0.f, offset, 0.f)); gArticulations[1]->wakeUp(); // wake up articulation (relative offset setting does not wake) PxArticulationLink* links[3]; gArticulations[1]->getLinks(links, 3, 0); PxTransform attachmentPose = links[0]->getGlobalPose(); attachmentPose.p.y += offset; getAttachments()[3]->setGlobalPose(attachmentPose); getAttachments()[4]->setGlobalPose(links[1]->getGlobalPose()); getAttachments()[5]->setGlobalPose(links[2]->getGlobalPose()); } gScene->simulate(dt); gScene->fetchResults(true); time += dt; } void cleanupPhysics(bool /*interactive*/) { gArticulations[0]->release(); gArticulations[1]->release(); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); transport->release(); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetSpatialTendon done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i = 0; i < frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
12,480
C++
43.575
155
0.744551
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTireVehicle.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "../snippetvehicle2common/directdrivetrain/DirectDrivetrain.h" #include "CustomTire.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; // //This class holds the parameters, state and logic needed to implement a vehicle that //is using a custom component for the tire model. // //See BaseVehicle for more details on the snippet code design. // class CustomTireVehicle : public DirectDriveVehicle , public CustomTireComponent { public: bool initialize(PxPhysics& physics, const PxCookingParams& params, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents = true); virtual void destroy(); virtual void initComponentSequence(bool addPhysXBeginEndComponents); virtual void getDataForCustomTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const CustomTireParams>& tireParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) { axleDescription = &mBaseParams.axleDescription; steerResponseStates.setData(mBaseState.steerCommandResponseStates); rigidBodyState = &mBaseState.rigidBodyState; actuationStates.setData(mBaseState.actuationStates); wheelParams.setData(mBaseParams.wheelParams); suspensionParams.setData(mBaseParams.suspensionParams); tireParams.setData(mTireParamsList); roadGeomStates.setData(mBaseState.roadGeomStates); suspensionStates.setData(mBaseState.suspensionStates); suspensionComplianceStates.setData(mBaseState.suspensionComplianceStates); suspensionForces.setData(mBaseState.suspensionForces); wheelRigidBody1DStates.setData(mBaseState.wheelRigidBody1dStates); tireGripStates.setData(mBaseState.tireGripStates); tireDirectionStates.setData(mBaseState.tireDirectionStates); tireSpeedStates.setData(mBaseState.tireSpeedStates); tireSlipStates.setData(mBaseState.tireSlipStates); tireCamberAngleStates.setData(mBaseState.tireCamberAngleStates); tireStickyStates.setData(mBaseState.tireStickyStates); tireForces.setData(mBaseState.tireForces); } //Parameters and states of the vehicle's custom tire. CustomTireParams mCustomTireParams[2]; //One shared parameter set for front and one for rear wheels. CustomTireParams* mTireParamsList[4]; }; }//namespace snippetvehicle2
5,094
C
45.318181
137
0.817236
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/VehicleMFTireData.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VEHICLE_MF_TIRE_DATA_H #define VEHICLE_MF_TIRE_DATA_H #include "foundation/Px.h" #include "foundation/PxMath.h" #include "foundation/PxFlags.h" namespace physx { // requirement: has to return 0 for input 0 template<typename TFloat> PX_FORCE_INLINE PxI32 mfSignum(const TFloat v) { // note: -0.0 returns 0, so sign is lost. +-NaN not covered return (TFloat(0.0) < v) - (v < TFloat(0.0)); } /** \brief Parameters for the Magic Formula Tire Model shared by various components of the model. \note Contains derived parameters that need to be set as well before the model can be evaluated. The helper method mfTireComputeDerivedSharedParams() can be used to compute those parameters. */ template<typename TFloat> struct MFTireSharedParams { TFloat r0; /// wheel radius at no load (SI unit would be metre [m]) TFloat v0; /// reference velocity [m/s] (for normalization. Usually the speed at which measurements were taken, often /// 16.7m/s, i.e., 60km/h are used. SI unit would be metres per second [m/s]) TFloat fz0; /// nominal vertical load (for normalization. SI unit would be Newton [N]). Make sure to call /// mfTireComputeDerivedSharedParams() after changing this parameter. TFloat pi0; /// nominal inflation pressure (for normalization. SI unit would be Pascal [Pa]) TFloat epsilonV; /// small value to add to velocity at contact patch when dividing (to avoid division /// by 0 when vehicle is not moving) TFloat slipReductionLowVelocity; /// at low velocities the model is prone to show large oscillation. Scaling down the slip /// in such scenarios will reduce the oscillation. This parameter defines a threshold for /// the longitudinal velocity below which the divisor for the slip computation will be /// interpolated between the actual longitudinal velocity and the specified threshold. /// At 0 longitudinal velocity, slipReductionLowVelocity will be used as divisor. With /// growing longitudinal velocity, the interpolation weight for slipReductionLowVelocity /// will decrease fast (quadratic) and will show no effect for velocities above the threshold /// anymore. TFloat lambdaFz0; /// user scaling factor for nominal load. Make sure to call mfTireComputeDerivedSharedParams() after /// changing this parameter. TFloat lambdaK_alpha; /// user scaling factor for cornering stiffness TFloat aMu; /// parameter for degressive friction factor computation. Vertical shifts of the force curves /// should vanish slower when friction coefficients go to 0: (aMu * lambdaMu) / (1 + (aMu - 1) * lambdaMu). /// Choose 10 as a good default. Make sure to call mfTireComputeDerivedSharedParams() after changing this parameter. TFloat zeta0; /// scaling factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. TFloat zeta2; /// scaling factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. // derived parameters TFloat recipFz0; /// 1 / fz0. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat fz0Scaled; /// fz0 * lambdaFz0. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat recipFz0Scaled; /// 1 / fz0Scaled. mfTireComputeDerivedSharedParams() can be used to compute this value. TFloat aMuMinus1; /// aMu - 1. mfTireComputeDerivedSharedParams() can be used to compute this value. }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeDerivedSharedParams(MFTireSharedParams<TFloat>& sharedParams) { sharedParams.recipFz0 = TFloat(1.0) / sharedParams.fz0; sharedParams.fz0Scaled = sharedParams.fz0 * sharedParams.lambdaFz0; sharedParams.recipFz0Scaled = TFloat(1.0) / sharedParams.fz0Scaled; sharedParams.aMuMinus1 = sharedParams.aMu - TFloat(1.0); } template<typename TFloat> struct MFTireVolatileSharedParams { // gamma: camber angle // Fz: vertical load // Fz0Scaled: nominal vertical load (scaled by user scaling factor lambdaFz0) // pi: inflation pressure // pi0: nominal inflation pressure TFloat gamma; // camber angle (in radians) TFloat gammaSqr; // gamma^2 TFloat sinGamma; // sin(gamma) TFloat sinGammaAbs; // |sin(gamma)| TFloat sinGammaSqr; // sin(gamma)^2 TFloat fzNormalized; // Fz / Fz0 TFloat fzNormalizedWithScale; // Fz / Fz0Scaled TFloat dFz; // normalized change in vertical load: (Fz - Fz0Scaled) / Fz0Scaled TFloat dFzSqr; // dFz^2 TFloat dpi; // normalized inflation pressure change: (pi - pi0) / pi0 TFloat dpiSqr; // dpi^2 TFloat lambdaMu_longitudinal; /// scaling factor for longitudinal friction mu term and thus peak value. TFloat lambdaMu_lateral; /// scaling factor for lateral friction mu term and thus peak value. }; template<typename TConfig> PX_FORCE_INLINE void mfTireComputeVolatileSharedParams(const typename TConfig::Float gamma, const typename TConfig::Float fz, const typename TConfig::Float lambdaMu_longitudinal, const typename TConfig::Float lambdaMu_lateral, const typename TConfig::Float pi, const MFTireSharedParams<typename TConfig::Float>& sharedParams, MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { if (TConfig::supportCamber) { volatileSharedParams.gamma = gamma; volatileSharedParams.gammaSqr = gamma * gamma; volatileSharedParams.sinGamma = PxSin(gamma); volatileSharedParams.sinGammaAbs = PxAbs(volatileSharedParams.sinGamma); volatileSharedParams.sinGammaSqr = volatileSharedParams.sinGamma * volatileSharedParams.sinGamma; } volatileSharedParams.fzNormalized = fz * sharedParams.recipFz0; volatileSharedParams.fzNormalizedWithScale = fz * sharedParams.recipFz0Scaled; volatileSharedParams.dFz = (fz - sharedParams.fz0Scaled) * sharedParams.recipFz0Scaled; volatileSharedParams.dFzSqr = volatileSharedParams.dFz * volatileSharedParams.dFz; volatileSharedParams.lambdaMu_longitudinal = lambdaMu_longitudinal; volatileSharedParams.lambdaMu_lateral = lambdaMu_lateral; if (TConfig::supportInflationPressure) { volatileSharedParams.dpi = (pi - sharedParams.pi0) / sharedParams.pi0; volatileSharedParams.dpiSqr = volatileSharedParams.dpi * volatileSharedParams.dpi; } } template<typename TFloat> struct MFTireLongitudinalForcePureParams { /** @name magic formula: B (through longitudinal slip stiffness K) */ /**@{*/ TFloat pK1; /// longitudinal slip stiffness (per load unit) Guidance: for many tires /// (almost) linearly dependent on the vertical force. Typically, in the /// range of 14 to 18. May be much higher for racing tires. TFloat pK2; /// variation of slip stiffness (per load unit) with load change TFloat pK3; /// exponential variation of slip stiffness with load change TFloat pp1; /// variation of slip stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat pp2; /// variation of slip stiffness with inflation pressure change squared /// (set to 0 to ignore effect) TFloat lambdaK; /// user scaling factor for slip stiffness TFloat epsilon; /// small value to avoid division by 0 if load is 0. The scale of the values /// the epsilon gets added to is similar to the scale of the longitudinal force. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat pC1; /// shape factor. Guidance: value has to be larger or equal to 1, for example, 1.6 /// is a fair starting point. TFloat lambdaC; /// user scaling factor for shape factor /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat pD1; /// friction mu term (per load unit). Guidance: for highly loaded tires /// the value is below 1, for example around 0.8 on a dry surface. High /// performance tires on racing cars may reach 1.5 or even 2.0 in extreme /// cases. TFloat pD2; /// variation of friction mu term (per load unit) with load change. /// Guidance: normally below 0 (typically between -0.1 and 0.0). Generally, /// pD2 is larger than the counterpart in MFTireLateralForcePureParams. TFloat pD3; /// variation of friction mu term with camber angle squared /// (set to 0 to ignore effect) TFloat pp3; /// variation of friction mu term with inflation pressure change /// (set to 0 to ignore effect) TFloat pp4; /// variation of friction mu term with inflation pressure change squared /// (set to 0 to ignore effect) //TFloat lambdaMu; // user scaling factor for friction mu term (and thus peak value). // (see MFTireVolatileSharedParams::lambdaMu_longitudinal) TFloat zeta1; /// scaling factor for friction mu term to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat pE1; /// curvature factor. Guidance: value has to be smaller or equal to 1. An /// increasing negative value will make the curve more peaky. 0 is a /// fair starting point. TFloat pE2; /// variation of curvature factor with load change TFloat pE3; /// variation of curvature factor with load change squared TFloat pE4; /// scaling factor for curvature factor depending on signum /// of shifted longitudinal slip ratio (to create asymmetry under drive/brake /// torque: 1.0 - pE4*sgn(slipRatioShifted). No effect when no slip) TFloat lambdaE; /// user scaling factor for curvature factor /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat pH1; /// horizontal shift at nominal load TFloat pH2; /// variation of horizontal shift with load change TFloat lambdaH; /// user scaling factor for horizontal shift /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat pV1; /// vertical shift (per load unit) TFloat pV2; /// variation of vertical shift (per load unit) with load change TFloat lambdaV; /// user scaling factor for vertical shift //TFloat lambdaMu; // user scaling factor for vertical shift (peak friction coefficient). See magic formula: D //TFloat zeta1; // scaling factor for vertical shift to take turn slip into account. See magic formula: D /**@}*/ }; template<typename TFloat> struct MFTireLongitudinalForceCombinedParams { /** @name magic formula: B */ /**@{*/ TFloat rB1; /// curvature factor at force reduction peak. Guidance: 8.3 may be used as a starting point. TFloat rB2; /// variation of curvature factor at force reduction peak with longitudinal slip ratio. /// Guidance: 5.0 may be used as a starting point. TFloat rB3; /// variation of curvature factor at force reduction peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaAlpha; /// user scaling factor for influence of lateral slip angle alpha on longitudinal force /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat rC1; /// shape factor. Guidance: 0.9 may be used as a starting point. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat rE1; /// long range falloff at nominal load TFloat rE2; /// variation of long range falloff with load change /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat rH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. /**@}*/ }; template<typename TFloat> struct MFTireLateralForcePureParams { /** @name magic formula: B (through cornering stiffness K_alpha) */ /**@{*/ TFloat pK1; /// maximum cornering stiffness (per load unit) Guidance: values between /// 10 and 20 can be expected (or higher for racing tires). Note: beware of /// the sign when copying values from data sources. If the ISO sign /// convention is used for the tire model, negative values will be seen. TFloat pK2; /// scaling factor for load at which cornering stiffness reaches maximum. /// Guidance: typically, in a range of 1.5 to 3. TFloat pK3; /// variation of cornering stiffness with sine of camber angle /// (set to 0 to ignore effect) TFloat pK4; /// shape factor to control limit and thus shape of stiffness curve /// Guidance: typical value is 2 (especially, if camber angle is 0). TFloat pK5; /// scaling factor (depending on squared sine of camber angle) for load at which /// cornering stiffness reaches maximum /// (set to 0 to ignore effect) TFloat pp1; /// variation of cornering stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat pp2; /// scaling factor (depending on inflation pressure change) for load at which /// cornering stiffness reaches maximum /// (set to 0 to ignore effect) //TFloat lambdaK_alpha; // user scaling factor for cornering stiffness (see MFTireSharedParams::lambdaK_alpha) TFloat epsilon; /// small value to avoid division by 0 if load is 0. The scale of the values /// the epsilon gets added to is similar to the scale of the lareral force. TFloat zeta3; /// scaling factor for cornering stiffness to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat pC1; /// shape factor. Guidance: value has to be larger or equal to 1, for example, 1.3 /// is a fair starting point. TFloat lambdaC; /// user scaling factor for shape factor /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat pD1; /// friction mu term (per load unit). Guidance: for highly loaded tires /// the value is below 1, for example around 0.8 on a dry surface. High /// performance tires on racing cars may reach 1.5 or even 2.0 in extreme /// cases. TFloat pD2; /// variation of friction mu term (per load unit) with load change. /// Guidance: normally below 0 (typically between -0.1 and 0.0). Generally, /// pD2 is smaller than the counterpart in MFTireLongitudinalForcePureParams. TFloat pD3; /// variation of friction mu term with squared sine of camber angle /// (set to 0 to ignore effect) TFloat pp3; /// variation of friction mu term with inflation pressure change /// (set to 0 to ignore effect) TFloat pp4; /// variation of friction mu term with inflation pressure change squared /// (set to 0 to ignore effect) //TFloat lambdaMu; // user scaling factor for friction mu term (and thus peak value). // (see MFTireVolatileSharedParams::lambdaMu_lateral) //TFloat zeta2; // scaling factor for friction mu term to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat pE1; /// curvature factor. Guidance: value has to be smaller or equal to 1. An /// increasing negative value will make the curve more peaky. 0 is a /// fair starting point. TFloat pE2; /// variation of curvature factor with load change TFloat pE3; /// scaling factor for curvature factor depending on signum /// of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip). /// Set to 0 for a symmetric tire. TFloat pE4; /// variation of curvature factor with sine of camber angle and signum /// of shifted slip angle. /// (set to 0 to ignore effect) TFloat pE5; /// variation of curvature factor with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaE; /// user scaling factor for curvature factor /**@}*/ /** @name magic formula: Sh (with a camber stiffness term K_gamma) */ /**@{*/ TFloat pH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. TFloat pH2; /// variation of horizontal shift with load change. Set to 0 for a symmetric tire. TFloat pK6; /// camber stiffness (per load unit) /// (set to 0 to ignore effect) TFloat pK7; /// variation of camber stiffness (per load unit) with load change /// (set to 0 to ignore effect) TFloat pp5; /// variation of camber stiffness with inflation pressure change /// (set to 0 to ignore effect) TFloat lambdaH; /// user scaling factor for horizontal shift //TFloat lambdaK_gamma; // user scaling factor for horizontal shift of camber stiffness term // (no effect if camber angle is 0). // See magic formula: Sv TFloat epsilonK; /// small value to avoid division by 0 in case cornering stiffness is 0 /// (due to load being 0, for example). The scale of the values the /// epsilon gets added to is similar to the scale of the lareral force /// multiplied by the slope/stiffness when slip angle is approaching 0. //TFloat zeta0; // scaling factor for camber stiffness term to take turn slip into account. // See MFTireSharedParams::zeta0. TFloat zeta4; /// horizontal shift term to take turn slip and camber into account. /// If path radius is large and camber small, it can be set to 1 (since 1 gets /// subtracted this will result in a 0 term). /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat pV1; /// vertical shift (per load unit). Set to 0 for a symmetric tire. TFloat pV2; /// variation of vertical shift (per load unit) with load change. Set to 0 for a symmetric tire. TFloat pV3; /// vertical shift (per load unit) depending on sine of camber angle /// (set to 0 to ignore effect) TFloat pV4; /// variation of vertical shift (per load unit) with load change depending on sine /// of camber angle (set to 0 to ignore effect) TFloat lambdaV; /// user scaling factor for vertical shift TFloat lambdaK_gamma; /// user scaling factor for vertical shift depending on sine of camber angle //TFloat lambdaMu; // user scaling factor for vertical shift (peak friction coefficient). See magic formula: D //TFloat zeta2; // scaling factor for vertical shift to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ }; template<typename TFloat> struct MFTireLateralForceCombinedParams { /** @name magic formula: B */ /**@{*/ TFloat rB1; /// curvature factor at force reduction peak. Guidance: 4.9 may be used as a starting point. TFloat rB2; /// variation of curvature factor at force reduction peak with lateral slip /// Guidance: 2.2 may be used as a starting point. TFloat rB3; /// shift term for lateral slip. rB2 gets applied to shifted slip. Set to 0 for a symmetric tire. TFloat rB4; /// variation of curvature factor at force reduction peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaKappa; /// user scaling factor for influence of longitudinal slip ratio kappa on lateral force /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat rC1; /// shape factor. Guidance: 1.0 may be used as a starting point. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat rE1; /// long range falloff at nominal load TFloat rE2; /// variation of long range falloff with load change /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat rH1; /// horizontal shift at nominal load TFloat rH2; /// variation of horizontal shift with load change /**@}*/ /** @name magic formula: Sv */ /**@{*/ TFloat rV1; /// vertical shift (per load unit). Set to 0 for a symmetric tire. TFloat rV2; /// variation of vertical shift (per load unit) with load change. Set to 0 for a symmetric tire. TFloat rV3; /// variation of vertical shift (per load unit) with sine of camber angle /// (set to 0 to ignore effect) TFloat rV4; /// variation of vertical shift (per load unit) with lateral slip angle TFloat rV5; /// variation of vertical shift (per load unit) with longitudinal slip ratio TFloat rV6; /// variation of vertical shift (per load unit) with arctan of longitudinal slip ratio TFloat lambdaV; /// user scaling factor for vertical shift //TFloat zeta2; // scaling factor for vertical shift to take turn slip into account. // See MFTireSharedParams::zeta2. /**@}*/ }; template<typename TFloat> struct MFTireAligningTorqueVolatileSharedParams { // alpha: slip angle // Vcx: longitudinal velocity at contact patch // Vc: velocity at contact patch (longitudinal and lateral combined) TFloat cosAlpha; // cos(slip angle) = Vcx / (Vc + epsilon) (signed value of Vcx allows to support backwards running) TFloat signumVc_longitudinal; // signum of longitudinal velocity at contact patch }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeAligningTorqueVolatileSharedParams(const TFloat vc, const TFloat vc_longitudinal, const TFloat epsilon, MFTireAligningTorqueVolatileSharedParams<TFloat>& volatileSharedParams) { volatileSharedParams.cosAlpha = vc_longitudinal / (vc + epsilon); volatileSharedParams.signumVc_longitudinal = static_cast<TFloat>(mfSignum(vc_longitudinal)); } template<typename TFloat> struct MFTireAligningTorquePurePneumaticTrailParams { /** @name magic formula: B */ /**@{*/ TFloat qB1; /// curvature factor at pneumatic trail peak (at nominal load) TFloat qB2; /// variation of curvature factor at pneumatic trail peak with load change TFloat qB3; /// variation of curvature factor at pneumatic trail peak with load change squared TFloat qB5; /// variation of curvature factor at pneumatic trail peak with sine of camber angle /// (set to 0 to ignore effect) TFloat qB6; /// variation of curvature factor at pneumatic trail peak with squared sine of camber angle /// (set to 0 to ignore effect) //TFloat lambdaK_alpha; // user scaling factor for curvature factor at pneumatic trail peak // (see MFTireSharedParams::lambdaK_alpha) //TFloat lambdaMu; // inverse user scaling factor for curvature factor at pneumatic trail peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat qC1; /// shape factor (has to be greater than 0) /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat qD1; /// pneumatic trail peak (per normalized load-torque unit) TFloat qD2; /// variation of pneumatic trail peak (per normalized load-torque unit) with load change TFloat qD3; /// variation of pneumatic trail peak with sine of camber angle /// (set to 0 to ignore effect). Set to 0 for a symmetric tire. TFloat qD4; /// variation of pneumatic trail peak with squared sine of camber angle /// (set to 0 to ignore effect) TFloat pp1; /// variation of pneumatic trail peak with inflation pressure change /// (set to 0 to ignore effect) TFloat lambdaT; /// user scaling factor for pneumatic trail peak TFloat zeta5; /// scaling factor for pneumatic trail peak to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: E */ /**@{*/ TFloat qE1; /// long range falloff at nominal load TFloat qE2; /// variation of long range falloff with load change TFloat qE3; /// variation of long range falloff with load change squared TFloat qE4; /// scaling factor for long range falloff depending on sign /// of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip). /// Set to 0 for a symmetric tire. TFloat qE5; /// scaling factor for long range falloff depending on sine of camber /// angle and sign of shifted slip angle (to create asymmetry /// under positive/negative slip. No effect when no slip. /// Set to 0 to ignore effect) /**@}*/ /** @name magic formula: Sh */ /**@{*/ TFloat qH1; /// horizontal shift at nominal load. Set to 0 for a symmetric tire. TFloat qH2; /// variation of horizontal shift with load change. Set to 0 for a symmetric tire. TFloat qH3; /// horizontal shift at nominal load depending on sine of camber angle /// (set to 0 to ignore effect) TFloat qH4; /// variation of horizontal shift with load change depending on sine of camber angle /// (set to 0 to ignore effect) /**@}*/ }; template<typename TFloat> struct MFTireAligningTorquePureResidualTorqueParams { /** @name magic formula: B */ /**@{*/ TFloat qB9; /// curvature factor at residual torque peak TFloat qB10; /// curvature factor at residual torque peak (multiplier for B*C term of lateral force under pure slip) //TFloat lambdaK_alpha; // user scaling factor for curvature factor at residual torque peak // (see MFTireSharedParams::lambdaK_alpha) //TFloat lambdaMu; // inverse user scaling factor for curvature factor at residual torque peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) TFloat zeta6; /// scaling factor for curvature factor at residual torque peak to take turn slip /// into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: C */ /**@{*/ TFloat zeta7; /// shape factor to take turn slip into account. /// If path radius is large and camber small, it can be set to 1. /**@}*/ /** @name magic formula: D */ /**@{*/ TFloat qD6; /// residual torque peak (per load-torque unit). Set to 0 for a symmetric tire. TFloat qD7; /// variation of residual torque peak (per load-torque unit) with load change. /// Set to 0 for a symmetric tire. TFloat qD8; /// residual torque peak (per load-torque unit) depending on sine of camber angle /// (set to 0 to ignore effect) TFloat qD9; /// variation of residual torque peak (per load-torque unit) with load /// change and depending on sine of camber angle (set to 0 to ignore effect) TFloat qD10; /// residual torque peak (per load-torque unit) depending on signed square of /// sine of camber angle (set to 0 to ignore effect) TFloat qD11; /// variation of residual torque peak (per load-torque unit) with load /// change and depending on signed square of sine of camber angle /// (set to 0 to ignore effect) TFloat pp2; /// variation of residual torque peak with inflation pressure change and depending /// on sine of camber angle /// (set to 0 to ignore effect) TFloat lambdaR; /// user scaling factor for residual torque peak TFloat lambdaK_gamma; /// user scaling factor for residual torque peak depending on sine of camber angle //TFloat lambdaMu; // user scaling factor for residual torque peak // (see MFTireVolatileSharedParams::lambdaMu_lateral) //TFloat zeta0; // scaling factor for residual torque peak to take turn slip into account. // See MFTireSharedParams::zeta0. //TFloat zeta2; // scaling factor for residual torque peak to take turn slip into account. // See MFTireSharedParams::zeta2. TFloat zeta8; /// additional term for residual torque peak to take turn slip into account. /// If path radius is large and camber small, it can be set to 1 (since 1 gets /// subtracted this will result in a 0 term). /**@}*/ }; template<typename TFloat> struct MFTireAligningTorqueCombinedParams { TFloat sS1; /// effect (per radius unit) of longitudinal force on aligning torque. Set to 0 for a symmetric tire. TFloat sS2; /// effect (per radius unit) of longitudinal force on aligning torque with lateral force TFloat sS3; /// effect (per radius unit) of longitudinal force on aligning torque with sine of camber angle TFloat sS4; /// effect (per radius unit) of longitudinal force on aligning torque with sine of camber angle and load change TFloat lambdaS; /// user scaling factor for effect of longitudinal force on aligning torque }; template<typename TFloat> struct MFTireFreeRotatingRadiusParams { TFloat qre0; /// scaling factor for unloaded tire radius. Guidance: set to 1 if no adaptation to measurements are needed. TFloat qV1; /// increase of radius (per length unit) with normalized velocity squared (the tire radius grows /// due to centrifugal force) }; /** \brief Parameters for the Magic Formula Tire Model related to vertical tire stiffness. \note Contains derived parameters that need to be set as well before the model can be evaluated. The helper method mfTireComputeDerivedVerticalTireStiffnessParams() can be used to compute those parameters. */ template<typename TFloat> struct MFTireVerticalStiffnessParams { TFloat qF1; /// vertical tire stiffness (per load unit and normalized tire deflection (deflection / unloaded radius)). /// If qF2 is set to 0 and the vertical tire stiffness c0 is known, qF1 can be computed as c0 * r0 / F0 /// (r0: unloaded tire radius, F0: nominal tire load). TFloat qF2; /// vertical tire stiffness (per load unit and normalized tire deflection squared) TFloat ppF1; /// variation of vertical tire stiffness with inflation pressure change /// (set to 0 to ignore effect). Guidance: suggested value range is between 0.7 and 0.9. TFloat lambdaC; /// user scaling factor for vertical tire stiffness. // derived parameters TFloat c0; /// vertical tire stiffness at nominal vertical load, nominal inflation pressure, no tangential forces and /// zero forward velocity. mfTireComputeDerivedVerticalTireStiffnessParams() can be used to compute the value. }; template<typename TFloat> PX_FORCE_INLINE void mfTireComputeDerivedVerticalTireStiffnessParams(const TFloat r0, const TFloat fz0, MFTireVerticalStiffnessParams<TFloat>& params) { params.c0 = params.lambdaC * (fz0 / r0) * PxSqrt((params.qF1 * params.qF1) + (TFloat(4.0) * params.qF2)); } template<typename TFloat> struct MFTireEffectiveRollingRadiusParams { TFloat Freff; /// tire compression force (per load unit), linear part. Guidance: for radial tires a value /// around 0.01 is suggested, for bias ply tires a value around 0.333. TFloat Dreff; /// scaling factor for tire compression force, non-linear part. Guidance: for radial tires /// a value around 0.24 is suggested, for bias ply tires a value of 0. TFloat Breff; /// gradient of tire compression force, non-linear part. Guidance: for radial tires a value /// around 8 is suggested, for bias ply tires a value of 0. }; template<typename TFloat> struct MFTireNormalLoadParams { TFloat qV2; /// variation of normal load (per load unit) with normalized longitudinal velocity from tire rotation TFloat qFc_longitudinal; /// decrease of normal load (per load unit) with normalized longitudinal force squared. /// Can be considered optional (set to 0) for passenger car tires but should be considered for racing /// tires. TFloat qFc_lateral; /// decrease of normal load (per load unit) with normalized lateral force squared. /// Can be considered optional (set to 0) for passenger car tires but should be considered for racing /// tires. //TFloat qF1; // see MFTireVerticalStiffnessParams::qF1 //TFloat qF2; // see MFTireVerticalStiffnessParams::qF2 TFloat qF3; /// vertical tire stiffness (per load unit and normalized tire deflection (deflection / unloaded radius)) /// depending on camber angle squared (set to 0 to ignore effect) //TFloat ppF1; // see MFTireVerticalStiffnessParams::ppF1 }; struct MFTireDataFlag { enum Enum { eALIGNING_MOMENT = 1 << 0 /// Compute the aligning moment of the tire. }; }; template<typename TFloat> struct MFTireDataT { MFTireDataT() : flags(0) { } MFTireSharedParams<TFloat> sharedParams; MFTireFreeRotatingRadiusParams<TFloat> freeRotatingRadiusParams; MFTireVerticalStiffnessParams<TFloat> verticalStiffnessParams; MFTireEffectiveRollingRadiusParams<TFloat> effectiveRollingRadiusParams; MFTireNormalLoadParams<TFloat> normalLoadParams; MFTireLongitudinalForcePureParams<TFloat> longitudinalForcePureParams; MFTireLongitudinalForceCombinedParams<TFloat> longitudinalForceCombinedParams; MFTireLateralForcePureParams<TFloat> lateralForcePureParams; MFTireLateralForceCombinedParams<TFloat> lateralForceCombinedParams; MFTireAligningTorquePureResidualTorqueParams<TFloat> aligningTorquePureResidualTorqueParams; MFTireAligningTorquePurePneumaticTrailParams<TFloat> aligningTorquePurePneumaticTrailParams; MFTireAligningTorqueCombinedParams<TFloat> aligningTorqueCombinedParams; PxFlags<MFTireDataFlag::Enum, PxU32> flags; }; } // namespace physx #endif //VEHICLE_MF_TIRE_DATA_H
34,801
C
48.788269
140
0.698514
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/VehicleMFTire.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef VEHICLE_MF_TIRE_H #define VEHICLE_MF_TIRE_H #include "foundation/Px.h" #include "foundation/PxAssert.h" #include "foundation/PxMath.h" #include "VehicleMFTireData.h" namespace physx { template<typename TFloat> struct MFTireOverturningCoupleParams { TFloat qS1; /// overturning couple (per load-torque unit). Set to 0 for a symmetric tire. TFloat qS2; /// variation of overturning couple (per load-torque unit) with camber angle /// (set to 0 to ignore effect) TFloat qS3; /// variation of overturning couple (per load-torque unit) with normalized lateral force TFloat qS4; /// peak of sine * cosine type contribution TFloat qS5; /// shape factor of cosine type contribution depending on normalized load TFloat qS6; /// curvature factor of cosine type contribution depending on normalized load TFloat qS7; /// horizontal shift of sine type contribution depending on camber angle /// (set to 0 to ignore effect) TFloat qS8; /// shape factor of sine type contribution depending on normalized lateral force TFloat qS9; /// stiffness factor of sine type contribution depending on normalized lateral force TFloat qS10; /// shape factor of arctan type contribution depending on normalized load /// and camber angle /// (set to 0 to ignore effect) TFloat qS11; /// stiffness factor of arctan type contribution depending on normalized load /// and camber angle /// (set to 0 to ignore effect) TFloat ppM1; /// variation of camber angle dependent overturning couple with inflation pressure change /// (set to 0 to ignore effect) /// (no effect if camber angle is 0) TFloat lambdaVM; /// user scaling factor for overturning couple coefficient TFloat lambdaM; /// user scaling factor for overturning couple }; template<typename TFloat> struct MFTireRollingResistanceMomentParams { TFloat qS1; /// rolling resistance moment (per load-torque unit) TFloat qS2; /// variation of rolling resistance moment with normalized longitudinal force TFloat qS3; /// variation of rolling resistance moment with normalized longitudinal velocity TFloat qS4; /// variation of rolling resistance moment with normalized longitudinal velocity to the power of 4 TFloat qS5; /// variation of rolling resistance moment with camber angle squared /// (set to 0 to ignore effect) TFloat qS6; /// variation of rolling resistance moment with camber angle squared and normalized load /// (set to 0 to ignore effect) TFloat qS7; /// variation of rolling resistance moment with normalized load to the power of qS7 TFloat qS8; /// variation of rolling resistance moment with normalized inflation pressure to the power of qS8 /// (set to 0 to ignore effect) TFloat lambdaM; /// user scaling factor for rolling resistance moment }; //#define MF_ARCTAN(x) PxAtan(x) #define MF_ARCTAN(x) mfApproximateArctan(x) // more than 10% speedup could be seen template <typename TFloat> PX_FORCE_INLINE TFloat mfApproximateArctan(TFloat x) { const TFloat absX = PxAbs(x); const TFloat a = TFloat(1.1); const TFloat b = TFloat(1.6); const TFloat nom = x * ( TFloat(1.0) + (a * absX) ); const TFloat denom = TFloat(1.0) + ( (TFloat(2.0)/TFloat(PxPi)) * ((b*absX) + (a*x*x)) ); const TFloat result = nom / denom; return result; } PX_FORCE_INLINE PxF32 mfExp(PxF32 x) { return PxExp(x); } PX_FORCE_INLINE PxF64 mfExp(PxF64 x) { return exp(x); } PX_FORCE_INLINE PxF32 mfPow(PxF32 base, PxF32 exponent) { return PxPow(base, exponent); } PX_FORCE_INLINE PxF64 mfPow(PxF64 base, PxF64 exponent) { return pow(base, exponent); } template<typename TFloat> TFloat mfMagicFormulaSine(const TFloat x, const TFloat B, const TFloat C,const TFloat D, const TFloat E) { // // Magic Formula (sine version) // // y(x) = D * sin[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // y // ^ // | // | / // | / // | / // | / __________ // | / ____/ ^ \_____________ // | / ___/ | \_____________________________________ y(x) // | / __/ | // | /_/ | // | / | // | / | // | / | D // | / | // | / | // | / | // | /--- arctan(B*C*D) | // | / \ | // |/ | v // ------------/---------------------------------------------------------------------------------------------> x // /| // / | // / | // / | // // ---------------------------------------------------------------------------------------------------------------- // B: stiffness factor (tune slope at the origin) // ---------------------------------------------------------------------------------------------------------------- // C: shape factor (controls limits and thus general shape of the curve) // ---------------------------------------------------------------------------------------------------------------- // D: peak value (for C >= 1) // ---------------------------------------------------------------------------------------------------------------- // E: curvature factor (controls curvature at peak and horizontal position of peak) // ---------------------------------------------------------------------------------------------------------------- // const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat Dpart = D * PxSin(Cpart); return Dpart; } template<typename TFloat> TFloat mfMagicFormulaCosine(const TFloat x, const TFloat B, const TFloat C,const TFloat D, const TFloat E) { /* // Magic Formula (cosine version) // // y(x) = D * cos[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // y // ^ // | // | // ____|____ // ____/ ^ \____ // ___/ | \___ y(x) // __/ | \__ // _/ | \_ // / | D \ // _/ | \_ // __/ | \__ // ___/ | \___ // ____/ v \____ // ---_____/-------------------------------------------------------------------\_____------------------------> x ^ // __/ | ^ \______ | -ya // | | \_____________ v // | x0 -------------- // | // | // // ---------------------------------------------------------------------------------------------------------------- // B: curvature factor (controls curvature at peak) // ---------------------------------------------------------------------------------------------------------------- // C: shape factor (controls limit ya and thus general shape of the curve) // ---------------------------------------------------------------------------------------------------------------- // D: peak value (for C >= 1) // ---------------------------------------------------------------------------------------------------------------- // E: controls shape at larger values and controls location x0 of intersection with x-axis // ---------------------------------------------------------------------------------------------------------------- */ const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat Dpart = D * PxCos(Cpart); return Dpart; } template<typename TFloat> TFloat mfMagicFormulaCosineNoD(const TFloat x, const TFloat B, const TFloat C,const TFloat E) { // // Magic Formula (cosine version without D factor) // // y(x) = cos[ C * arctan{ B*x - E * (B*x - arctan(B*x)) } ] // // see magicFormulaCosine() for some information // const TFloat Bpart = B * x; const TFloat Epart = E * ( Bpart - MF_ARCTAN(Bpart) ); const TFloat Cpart = C * MF_ARCTAN( Bpart - Epart ); const TFloat result = PxCos(Cpart); return result; } template<typename TFloat> TFloat mfMagicFormulaCosineNoE(const TFloat x, const TFloat B, const TFloat C,const TFloat D) { // // Magic Formula (cosine version without E factor) // // y(x) = D * cos[ C * arctan{ B*x } ] // // see magicFormulaCosine() for some information // const TFloat Bpart = B * x; const TFloat Cpart = C * MF_ARCTAN( Bpart ); const TFloat Dpart = D * PxCos(Cpart); return Dpart; } // Vertical shifts of the longitudinal/lateral force curves should vanish slower when friction coefficients go to 0 template<typename TFloat> PX_FORCE_INLINE TFloat mfTireDegressiveFriction(const TFloat lambdaMu, const TFloat aMu, const TFloat aMuMinus1) { const TFloat lambdaMuDegressive = (aMu * lambdaMu) / ( TFloat(1.0) + (aMuMinus1 * lambdaMu) ); return lambdaMuDegressive; } /** \brief Longitudinal force at pure longitudinal slip \note Ignores interdependency with lateral force (in other words, tire rolling on a straight line with no slip angle [alpha = 0]) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load. fz >= 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] sharedParams Model parameters not just used for longitudinal force \param[in] volatileSharedParams Model parameters not just used for longitudinal force \param[out] K_kappa Magic formula longitudinal slip stiffness factor K \return Longitudinal force. */ template<typename TConfig> typename TConfig::Float mfTireLongitudinalForcePure(const typename TConfig::Float kappa, const typename TConfig::Float fz, const MFTireLongitudinalForcePureParams<typename TConfig::Float>& params, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& K_kappa) { typedef typename TConfig::Float TFloat; // magic formula: // x: longitudinal slip ratio (kappa) // y(x): longitudinal force // // magic formula: Sh; horizontal shift // const TFloat Sh = ( params.pH1 + (params.pH2 * volatileSharedParams.dFz) ) * params.lambdaH; // // magic formula: Sv; vertical shift // const TFloat lambdaMuDegressive = mfTireDegressiveFriction(volatileSharedParams.lambdaMu_longitudinal, sharedParams.aMu, sharedParams.aMuMinus1); TFloat Sv = fz * ( params.pV1 + (params.pV2 * volatileSharedParams.dFz) ) * params.lambdaV * lambdaMuDegressive; if (TConfig::supportTurnSlip) Sv *= params.zeta1; // // // const TFloat kappaShifted = kappa + Sh; // // magic formula: C; shape factor // const TFloat C = params.pC1 * params.lambdaC; PX_ASSERT(C > TFloat(0.0)); // // magic formula: D; peak value // TFloat mu = (params.pD1 + (params.pD2 * volatileSharedParams.dFz)) * volatileSharedParams.lambdaMu_longitudinal; if (TConfig::supportCamber) { const TFloat mu_camberFactor = TFloat(1.0) - (params.pD3 * volatileSharedParams.gammaSqr); mu *= mu_camberFactor; } if (TConfig::supportInflationPressure) { const TFloat mu_inflationPressureFactor = TFloat(1.0) + (params.pp3 * volatileSharedParams.dpi) + (params.pp4 * volatileSharedParams.dpiSqr); mu *= mu_inflationPressureFactor; } TFloat D = mu * fz; if (TConfig::supportTurnSlip) D *= params.zeta1; PX_ASSERT(D >= TFloat(0.0)); // // magic formula: E; curvature factor // const TFloat E = ( params.pE1 + (params.pE2*volatileSharedParams.dFz) + (params.pE3*volatileSharedParams.dFzSqr) ) * ( TFloat(1.0) - (params.pE4*mfSignum(kappaShifted)) ) * params.lambdaE; PX_ASSERT(E <= TFloat(1.0)); // // longitudinal slip stiffness // TFloat K = fz * (params.pK1 + (params.pK2 * volatileSharedParams.dFz)) * mfExp(params.pK3 * volatileSharedParams.dFz) * params.lambdaK; if (TConfig::supportInflationPressure) { const TFloat K_inflationPressureFactor = TFloat(1.0) + (params.pp1 * volatileSharedParams.dpi) + (params.pp2 * volatileSharedParams.dpiSqr); K *= K_inflationPressureFactor; } K_kappa = K; // // magic formula: B; stiffness factor // const TFloat B = K / ((C*D) + params.epsilon); // // resulting force // const TFloat F = mfMagicFormulaSine(kappaShifted, B, C, D, E) + Sv; return F; } /** \brief Longitudinal force with combined slip \note Includes the interdependency with lateral force \param[in] kappa Longitudinal slip ratio. \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fx0 The longitudinal force at pure longitudinal slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for longitudinal force \return Longitudinal force. @see mfTireLongitudinalForcePure() */ template<typename TConfig> typename TConfig::Float mfTireLongitudinalForceCombined(const typename TConfig::Float kappa, const typename TConfig::Float tanAlpha, const typename TConfig::Float fx0, const MFTireLongitudinalForceCombinedParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = params.rH1; // // // const TFloat tanAlphaShifted = tanAlpha + Sh; // // magic formula: B; curvature factor // TFloat B = params.rB1; if (TConfig::supportCamber) { const TFloat B_term_camber = params.rB3 * volatileSharedParams.sinGammaSqr; B += B_term_camber; } const TFloat B_cosFactor = PxCos(MF_ARCTAN(params.rB2 * kappa)); B *= B_cosFactor * params.lambdaAlpha; PX_ASSERT(B > TFloat(0.0)); // // magic formula: C; shape factor // const TFloat C = params.rC1; // // magic formula: E; // const TFloat E = params.rE1 + (params.rE2*volatileSharedParams.dFz); PX_ASSERT(E <= TFloat(1.0)); // // resulting force // const TFloat G0 = mfMagicFormulaCosineNoD(Sh, B, C, E); PX_ASSERT(G0 > TFloat(0.0)); const TFloat G = mfMagicFormulaCosineNoD(tanAlphaShifted, B, C, E) / G0; PX_ASSERT(G > TFloat(0.0)); const TFloat F = G * fx0; return F; } /** \brief Lateral force at pure lateral/side slip \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fz Vertical load (force). fz >= 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] sharedParams Model parameters not just used for lateral force \param[in] volatileSharedParams Model parameters not just used for lateral force \param[in,out] fy0NoCamberNoTurnSlip If not NULL, the lateral force discarding camber and turn slip (basically, the resulting force if both were 0) will be written to the pointer target. \param[out] B_out Magic formula stiffnes factor B \param[out] C_out Magic formula shape factor C \param[out] K_alpha_withEpsilon_out Magic formula cornering stiffness factor K with a small epsilon added to avoid divison by 0. \param[out] Sh_out Magic formula horizontal shift Sh \param[out] Sv_out Magic formula vertical shift Sv \param[out] mu_zeta2_out The friction factor multiplied by MFTireSharedParams::zeta2. Will be needed when computing the lateral force with combined slip. \return Lateral force. */ template<typename TConfig> typename TConfig::Float mfTireLateralForcePure(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const MFTireLateralForcePureParams<typename TConfig::Float>& params, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float* fy0NoCamberNoTurnSlip, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& K_alpha_withEpsilon_out, typename TConfig::Float& Sh_out, typename TConfig::Float& Sv_out, typename TConfig::Float& mu_zeta2_out) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): lateral force // // magic formula: Sv; vertical shift // const TFloat lambdaMuDegressive = mfTireDegressiveFriction(volatileSharedParams.lambdaMu_lateral, sharedParams.aMu, sharedParams.aMuMinus1); const TFloat fz_x_lambdaMuDegressive = fz * lambdaMuDegressive; const TFloat Sv_term_noCamber_noTurnSlip = fz_x_lambdaMuDegressive * ( params.pV1 + (params.pV2 * volatileSharedParams.dFz) ) * params.lambdaV; TFloat Sv = Sv_term_noCamber_noTurnSlip; if (TConfig::supportTurnSlip) { Sv *= sharedParams.zeta2; } TFloat Sv_term_camber; if (TConfig::supportCamber) { Sv_term_camber = fz_x_lambdaMuDegressive * ( params.pV3 + (params.pV4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma * params.lambdaK_gamma; if (TConfig::supportTurnSlip) { Sv_term_camber *= sharedParams.zeta2; } Sv += Sv_term_camber; } // note: fz_x_lambdaMuDegressive and zeta2 are not pulled out because Sv_term_camber // is needed for Sh computation and Sv_term_noCamber_noTurnSlip for lateralForceNoCamberNoTurnSlip Sv_out = Sv; // // cornering stiffness // const TFloat corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip = params.pK1 * sharedParams.fz0Scaled * sharedParams.lambdaK_alpha; TFloat corneringStiffnessPeak = corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip; if (TConfig::supportCamber) { const TFloat corneringStiffnessPeak_camberFactor = TFloat(1.0) - (params.pK3 * volatileSharedParams.sinGammaAbs); corneringStiffnessPeak *= corneringStiffnessPeak_camberFactor; } if (TConfig::supportTurnSlip) { corneringStiffnessPeak *= params.zeta3; } TFloat corneringStiffnessPeak_inflationPressureFactor; if (TConfig::supportInflationPressure) { corneringStiffnessPeak_inflationPressureFactor = TFloat(1.0) + (params.pp1 * volatileSharedParams.dpi); corneringStiffnessPeak *= corneringStiffnessPeak_inflationPressureFactor; } const TFloat loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber = params.pK2; TFloat loadAtCorneringStiffnessPeak = loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber; if (TConfig::supportCamber) { const TFloat loadAtCorneringStiffnessPeak_term_camber = params.pK5 * volatileSharedParams.sinGammaSqr; loadAtCorneringStiffnessPeak += loadAtCorneringStiffnessPeak_term_camber; } TFloat loadAtCorneringStiffnessPeak_inflationPressureFactor; if (TConfig::supportInflationPressure) { loadAtCorneringStiffnessPeak_inflationPressureFactor = TFloat(1.0) + (params.pp2 * volatileSharedParams.dpi); loadAtCorneringStiffnessPeak *= loadAtCorneringStiffnessPeak_inflationPressureFactor; } const TFloat K_alpha = corneringStiffnessPeak * PxSin( params.pK4 * MF_ARCTAN(volatileSharedParams.fzNormalizedWithScale / loadAtCorneringStiffnessPeak) ); const TFloat K_alpha_withEpsilon = K_alpha + params.epsilonK; K_alpha_withEpsilon_out = K_alpha_withEpsilon; // // magic formula: Sh; horizontal shift // const TFloat Sh_term_noCamber_noTurnSlip = ( params.pH1 + (params.pH2 * volatileSharedParams.dFz) ) * params.lambdaH; TFloat Sh = Sh_term_noCamber_noTurnSlip; if (TConfig::supportCamber) { TFloat K_gamma = fz * ( params.pK6 + (params.pK7 * volatileSharedParams.dFz) ) * params.lambdaK_gamma; if (TConfig::supportInflationPressure) { const TFloat K_gamma_inflationPressureFactor = TFloat(1.0) + (params.pp5 * volatileSharedParams.dpi); K_gamma *= K_gamma_inflationPressureFactor; } TFloat Sh_term_camber = ( (K_gamma * volatileSharedParams.sinGamma) - Sv_term_camber ) / K_alpha_withEpsilon; if (TConfig::supportTurnSlip) { Sh_term_camber *= sharedParams.zeta0; } Sh += Sh_term_camber; } if (TConfig::supportTurnSlip) { Sh += params.zeta4 - TFloat(1.0); } Sh_out = Sh; // // // const TFloat tanAlphaShifted = tanAlpha + Sh; // // magic formula: C; shape factor // const TFloat C = params.pC1 * params.lambdaC; PX_ASSERT(C > TFloat(0.0)); C_out = C; // // magic formula: D; peak value // TFloat mu_noCamber_noTurnSlip = (params.pD1 + (params.pD2 * volatileSharedParams.dFz)) * volatileSharedParams.lambdaMu_lateral; if (TConfig::supportInflationPressure) { const TFloat mu_inflationPressureFactor = TFloat(1.0) + (params.pp3 * volatileSharedParams.dpi) + (params.pp4 * volatileSharedParams.dpiSqr); mu_noCamber_noTurnSlip *= mu_inflationPressureFactor; } TFloat mu = mu_noCamber_noTurnSlip; if (TConfig::supportCamber) { const TFloat mu_camberFactor = TFloat(1.0) - (params.pD3 * volatileSharedParams.sinGammaSqr); mu *= mu_camberFactor; } if (TConfig::supportTurnSlip) { mu *= sharedParams.zeta2; } mu_zeta2_out = mu; const TFloat D = mu * fz; PX_ASSERT(D >= TFloat(0.0)); // // magic formula: E; curvature factor // const TFloat E_noCamber_noSignum = ( params.pE1 + (params.pE2*volatileSharedParams.dFz) ) * params.lambdaE; TFloat E = E_noCamber_noSignum; if (TConfig::supportCamber) { const TFloat E_camberFactor = TFloat(1.0) - ( (params.pE3 + (params.pE4 * volatileSharedParams.sinGamma)) * mfSignum(tanAlphaShifted) ) + (params.pE5 * volatileSharedParams.sinGammaSqr); E *= E_camberFactor; } else { const TFloat E_signumFactor = TFloat(1.0) - ( params.pE3 * mfSignum(tanAlphaShifted) ); E *= E_signumFactor; } PX_ASSERT(E <= TFloat(1.0)); // // magic formula: B; stiffness factor // const TFloat B = K_alpha / ((C*D) + params.epsilon); B_out = B; // // resulting force // const TFloat F = mfMagicFormulaSine(tanAlphaShifted, B, C, D, E) + Sv; if (fy0NoCamberNoTurnSlip) { if (TConfig::supportCamber || TConfig::supportTurnSlip) { const TFloat D_noCamber_noTurnSlip = mu_noCamber_noTurnSlip * fz; PX_ASSERT(D_noCamber_noTurnSlip >= TFloat(0.0)); const TFloat tanAlphaShifted_noCamber_noTurnSlip = tanAlpha + Sh_term_noCamber_noTurnSlip; TFloat corneringStiffnessPeak_noCamber_noTurnSlip = corneringStiffnessPeak_atNominalInflationPressure_noCamber_noTurnSlip; TFloat loadAtCorneringStiffnessPeak_noCamber = loadAtCorneringStiffnessPeak_atNominalInflationPressure_noCamber; if (TConfig::supportInflationPressure) { corneringStiffnessPeak_noCamber_noTurnSlip *= corneringStiffnessPeak_inflationPressureFactor; loadAtCorneringStiffnessPeak_noCamber *= loadAtCorneringStiffnessPeak_inflationPressureFactor; } const TFloat K_alpha_noCamber_noTurnSlip = corneringStiffnessPeak_noCamber_noTurnSlip * PxSin( params.pK4 * MF_ARCTAN(volatileSharedParams.fzNormalizedWithScale / loadAtCorneringStiffnessPeak_noCamber) ); const TFloat B_noCamber_noTurnSlip = K_alpha_noCamber_noTurnSlip / ((C*D_noCamber_noTurnSlip) + params.epsilon); const TFloat E_noCamber = E_noCamber_noSignum * ( TFloat(1.0) - (params.pE3 * mfSignum(tanAlphaShifted_noCamber_noTurnSlip)) ); PX_ASSERT(E_noCamber <= TFloat(1.0)); *fy0NoCamberNoTurnSlip = mfMagicFormulaSine(tanAlphaShifted_noCamber_noTurnSlip, B_noCamber_noTurnSlip, C, D_noCamber_noTurnSlip, E_noCamber) + Sv_term_noCamber_noTurnSlip; } else { *fy0NoCamberNoTurnSlip = F; } } return F; } /** \brief Lateral force with combined slip \note Includes the interdependency with longitudinal force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load (force). fz >= 0. \param[in] fy0 The lateral force at pure lateral slip. \param[in] mu_zeta2 The friction factor computed as part of the lateral force at pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for lateral force \param[in,out] fy0WeightNoCamberNoTurnSlip If not NULL, the weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0), will be written to the pointer target. \return Lateral force. @see mfTireLateralForcePure() */ template<typename TConfig> typename TConfig::Float mfTireLateralForceCombined(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappa, const typename TConfig::Float fz, const typename TConfig::Float fy0, const typename TConfig::Float mu_zeta2, const MFTireLateralForceCombinedParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float* fy0WeightNoCamberNoTurnSlip) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = params.rH1 + (params.rH2*volatileSharedParams.dFz); // // magic formula: Sv; vertical shift // TFloat DV = params.rV1 + (params.rV2*volatileSharedParams.dFz); if (TConfig::supportCamber) { const TFloat DV_term_camber = params.rV3 * volatileSharedParams.sinGamma; DV += DV_term_camber; } const TFloat DV_cosFactor = PxCos(MF_ARCTAN(params.rV4 * tanAlpha)); DV *= mu_zeta2 * fz * DV_cosFactor; const TFloat Sv_sinFactor = PxSin(params.rV5 * MF_ARCTAN(params.rV6 * kappa)); const TFloat Sv = DV * Sv_sinFactor * params.lambdaV; // // // const TFloat kappaShifted = kappa + Sh; // // magic formula: B; curvature factor // const TFloat B_term_noCamber = params.rB1; TFloat B = B_term_noCamber; if (TConfig::supportCamber) { const TFloat B_term_camber = params.rB4 * volatileSharedParams.sinGammaSqr; B += B_term_camber; } const TFloat B_cosFactor = PxCos(MF_ARCTAN(params.rB2 * (tanAlpha - params.rB3))); const TFloat B_cosFactor_lambdaKappa = B_cosFactor * params.lambdaKappa; B *= B_cosFactor_lambdaKappa; PX_ASSERT(B > TFloat(0.0)); // // magic formula: C; shape factor // const TFloat C = params.rC1; // // magic formula: E; // const TFloat E = params.rE1 + (params.rE2*volatileSharedParams.dFz); PX_ASSERT(E <= TFloat(1.0)); // // resulting force // const TFloat G0 = mfMagicFormulaCosineNoD(Sh, B, C, E); PX_ASSERT(G0 > TFloat(0.0)); TFloat G = mfMagicFormulaCosineNoD(kappaShifted, B, C, E) / G0; if (G < TFloat(0.0)) { // at very low velocity (or starting from standstill), the longitudinal slip ratio can get // large which can result in negative values G = TFloat(0.0); } const TFloat F = (G * fy0) + Sv; if (fy0WeightNoCamberNoTurnSlip) { if (TConfig::supportCamber || TConfig::supportTurnSlip) { const TFloat B_noCamber = B_term_noCamber * B_cosFactor_lambdaKappa; PX_ASSERT(B_noCamber > TFloat(0.0)); const TFloat G0_noCamber = mfMagicFormulaCosineNoD(Sh, B_noCamber, C, E); PX_ASSERT(G0_noCamber > TFloat(0.0)); TFloat G_noCamber = mfMagicFormulaCosineNoD(kappaShifted, B_noCamber, C, E) / G0_noCamber; if (G_noCamber < TFloat(0.0)) G_noCamber = TFloat(0.0); *fy0WeightNoCamberNoTurnSlip = G_noCamber; } else { *fy0WeightNoCamberNoTurnSlip = G; } } return F; } template<typename TConfig> void mfTireComputeAligningTorquePneumaticTrailIntermediateParams(const typename TConfig::Float tanAlpha, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& tanAlphaShifted_out, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& D_out, typename TConfig::Float& E_out) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // TFloat Sh = params.qH1 + (params.qH2 * volatileSharedParams.dFz); if (TConfig::supportCamber) { const TFloat Sh_term_camber = ( params.qH3 + (params.qH4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma; Sh += Sh_term_camber; } // // // const TFloat tanAlphaShifted = tanAlpha + Sh; tanAlphaShifted_out = tanAlphaShifted; // // magic formula: B; curvature factor // TFloat B = ( params.qB1 + (params.qB2 * volatileSharedParams.dFz) + (params.qB3 * volatileSharedParams.dFzSqr) ) * (sharedParams.lambdaK_alpha / volatileSharedParams.lambdaMu_lateral); if (TConfig::supportCamber) { const TFloat B_camberFactor = TFloat(1.0) + (params.qB5 * volatileSharedParams.sinGammaAbs) + (params.qB6 * volatileSharedParams.sinGammaSqr); B *= B_camberFactor; } PX_ASSERT(B > TFloat(0.0)); B_out = B; // // magic formula: C; shape factor // const TFloat C = params.qC1; PX_ASSERT(C > TFloat(0.0)); C_out = C; // // magic formula: D; peak value // TFloat D = volatileSharedParams.fzNormalizedWithScale * sharedParams.r0 * (params.qD1 + (params.qD2 * volatileSharedParams.dFz)) * params.lambdaT * volatileSharedParamsAligningTorque.signumVc_longitudinal; if (TConfig::supportInflationPressure) { const TFloat D_inflationPressureFactor = TFloat(1.0) - (params.pp1 * volatileSharedParams.dpi); D *= D_inflationPressureFactor; } if (TConfig::supportCamber) { const TFloat D_camberFactor = TFloat(1.0) + (params.qD3 * volatileSharedParams.sinGammaAbs) + (params.qD4 * volatileSharedParams.sinGammaSqr); D *= D_camberFactor; } if (TConfig::supportTurnSlip) { D *= params.zeta5; } D_out = D; // // magic formula: E; // TFloat E = params.qE1 + (params.qE2*volatileSharedParams.dFz) + (params.qE3*volatileSharedParams.dFzSqr); TFloat E_arctanFactor = params.qE4; if (TConfig::supportCamber) { const TFloat E_arctanFactor_term_camber = params.qE5 * volatileSharedParams.sinGamma; E_arctanFactor += E_arctanFactor_term_camber; } E_arctanFactor = TFloat(1.0) + ( E_arctanFactor * (TFloat(2.0) / TFloat(PxPi)) * MF_ARCTAN(B*C*tanAlphaShifted) ); E *= E_arctanFactor; PX_ASSERT(E <= TFloat(1.0)); E_out = E; } /** \brief Aligning torque at pure lateral/side slip (pneumatic trail term) The lateral/side forces act a small distance behind the center of the contact patch. This distance is called the pneumatic trail. The pneumatic trail decreases with increasing slip angle. The pneumatic trail increases with vertical load. The pneumatic trail causes a torque that turns the wheel away from the direction of turn. \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just pneumatic trail term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (pneumatic trail term). */ template<typename TConfig> typename TConfig::Float mfTireAligningTorquePurePneumaticTrail(const typename TConfig::Float tanAlpha, const typename TConfig::Float fy0NoCamberNoTurnSlip, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): pneumatic trail TFloat tanAlphaShifted, B, C, D, E; mfTireComputeAligningTorquePneumaticTrailIntermediateParams<TConfig>(tanAlpha, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D, E); // // pneumatic trail // const TFloat t = mfMagicFormulaCosine(tanAlphaShifted, B, C, D, E) * volatileSharedParamsAligningTorque.cosAlpha; // // resulting torque // const TFloat Mz = -t * fy0NoCamberNoTurnSlip; return Mz; } /** \brief Aligning torque with combined slip (pneumatic trail term) \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappaScaledSquared Longitudinal slip ratio scaled by the ratio of longitudinalStiffness and lateralStiffness and then squared \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] fy0NoCamberNoTurnSlipWeight The weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just pneumatic trail term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (pneumatic trail term). @see mfTireAligningTorquePurePneumaticTrail */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombinedPneumaticTrail(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappaScaledSquared, const typename TConfig::Float fy0NoCamberNoTurnSlip, const typename TConfig::Float fy0NoCamberNoTurnSlipWeight, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): pneumatic trail TFloat tanAlphaShifted, B, C, D, E; mfTireComputeAligningTorquePneumaticTrailIntermediateParams<TConfig>(tanAlpha, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D, E); const TFloat tanAlphaShiftedCombined = PxSqrt( tanAlphaShifted*tanAlphaShifted + kappaScaledSquared ) * mfSignum(tanAlphaShifted); const TFloat fyNoCamberNoTurnSlip = fy0NoCamberNoTurnSlipWeight * fy0NoCamberNoTurnSlip; // // pneumatic trail // const TFloat t = mfMagicFormulaCosine(tanAlphaShiftedCombined, B, C, D, E) * volatileSharedParamsAligningTorque.cosAlpha; // // resulting torque // const TFloat Mz = -t * fyNoCamberNoTurnSlip; return Mz; } template<typename TConfig> void mfTireComputeAligningTorqueResidualTorqueIntermediateParams(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams, typename TConfig::Float& tanAlphaShifted_out, typename TConfig::Float& B_out, typename TConfig::Float& C_out, typename TConfig::Float& D_out) { typedef typename TConfig::Float TFloat; // // magic formula: Sh; horizontal shift // const TFloat Sh = Sh_lateral + ( Sv_lateral / K_alpha_withEpsilon ); // // // tanAlphaShifted_out = tanAlpha + Sh; // // magic formula: B; curvature factor // TFloat B = ( params.qB9 * (sharedParams.lambdaK_alpha / volatileSharedParams.lambdaMu_lateral) ) + ( params.qB10 * B_lateral * C_lateral ); if (TConfig::supportTurnSlip) { B *= params.zeta6; } B_out = B; // // magic formula: C; shape factor // if (TConfig::supportTurnSlip) { C_out = params.zeta7; } else { C_out = TFloat(1.0); } // // magic formula: D; peak value // TFloat D = (params.qD6 + (params.qD7 * volatileSharedParams.dFz)) * params.lambdaR; if (TConfig::supportTurnSlip) { D *= sharedParams.zeta2; } if (TConfig::supportCamber) { TFloat D_term_camber = params.qD8 + (params.qD9 * volatileSharedParams.dFz); if (TConfig::supportInflationPressure) { const TFloat D_term_camber_inflationPressureFactor = TFloat(1.0) + (params.pp2 * volatileSharedParams.dpi); D_term_camber *= D_term_camber_inflationPressureFactor; } D_term_camber += ( params.qD10 + (params.qD11 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGammaAbs; D_term_camber *= volatileSharedParams.sinGamma * params.lambdaK_gamma; if (TConfig::supportTurnSlip) { D_term_camber *= sharedParams.zeta0; } D += D_term_camber; } D *= fz * sharedParams.r0 * volatileSharedParams.lambdaMu_lateral * volatileSharedParamsAligningTorque.signumVc_longitudinal * volatileSharedParamsAligningTorque.cosAlpha; if (TConfig::supportTurnSlip) { D += params.zeta8 - TFloat(1.0); } D_out = D; } /** \brief Aligning torque at pure lateral/side slip (residual torque term) Residual torque is produced by assymetries of the tire and the asymmetrical shape and pressure distribution of the contact patch etc. \note Ignores interdependency with longitudinal force (in other words, assumes no longitudinal slip, that is, longitudinal slip ratio of 0 [kappa = 0]) \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] fz Vertical load (force). fz >= 0. \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just residual torque term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (residual torque term). */ template<typename TConfig> typename TConfig::Float mfTireAligningTorquePureResidualTorque(const typename TConfig::Float tanAlpha, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): residual torque TFloat tanAlphaShifted, B, C, D; mfTireComputeAligningTorqueResidualTorqueIntermediateParams<TConfig>(tanAlpha, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D); // // residual torque // const TFloat Mz = mfMagicFormulaCosineNoE(tanAlphaShifted, B, C, D) * volatileSharedParamsAligningTorque.cosAlpha; return Mz; } /** \brief Aligning torque with combined slip (residual torque term) \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappaScaledSquared Longitudinal slip ratio scaled by the ratio of longitudinalStiffness and lateralStiffness and then squared \param[in] fz Vertical load (force). fz >= 0. \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque (but not just residual torque term) \param[in] sharedParams Model parameters not just used for aligning torque \param[in] volatileSharedParams Model parameters not just used for aligning torque \return Aligning torque (residual torque term). @see mfTireAligningTorquePureResidualTorque() */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombinedResidualTorque(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappaScaledSquared, const typename TConfig::Float fz, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // magic formula: // x: tangens slip angle (tan(alpha)) // y(x): residual torque TFloat tanAlphaShifted, B, C, D; mfTireComputeAligningTorqueResidualTorqueIntermediateParams<TConfig>(tanAlpha, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, params, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams, tanAlphaShifted, B, C, D); const TFloat tanAlphaShiftedCombined = PxSqrt( tanAlphaShifted*tanAlphaShifted + kappaScaledSquared ) * mfSignum(tanAlphaShifted); // // residual torque // const TFloat Mz = mfMagicFormulaCosineNoE(tanAlphaShiftedCombined, B, C, D) * volatileSharedParamsAligningTorque.cosAlpha; return Mz; } /** \brief Aligning torque with combined longitudinal/lateral slip \note Includes the interdependency between longitudinal/lateral force \param[in] tanAlpha Tangens of slip angle (multiplied with sign of longitudinal velocity at contact patch, i.e., -Vcy / |Vcx|, Vcy/Vcx: lateral/longitudinal velocity at contact patch) \param[in] kappa Longitudinal slip ratio. \param[in] fz Vertical load (force). fz >= 0. \param[in] fx Longitudinal force with combined slip. \param[in] fy Lateral force with combined slip. \param[in] fy0NoCamberNoTurnSlip Lateral force at pure lateral slip and camber angle and turn slip equals 0. \param[in] fy0NoCamberNoTurnSlipWeight The weight factor for the lateral force at pure slip, discarding camber and turn slip (basically, if both were 0). \param[in] K_kappa Longitudinal slip stiffness in magic formula for longitudinal force under pure longitudinal slip. \param[in] K_alpha_withEpsilon Cornering stiffness in magic formula for lateral force under pure lateral slip (with a small epsilon value added to avoid division by 0). \param[in] B_lateral B factor in magic formula for lateral force under pure lateral slip. \param[in] C_lateral C factor in magic formula for lateral force under pure lateral slip. \param[in] Sh_lateral Horizontal shift in magic formula for lateral force under pure lateral slip. \param[in] Sv_lateral Vertical shift in magic formula for lateral force under pure lateral slip. \param[in] pneumaticTrailParams The nondimensional model parameters and user scaling factors used for the pneumatic trail term of aligning torque. \param[in] residualTorqueParams The nondimensional model parameters and user scaling factors used for the residual torque term of aligning torque. \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParamsAligningTorque Model parameters used for aligning torque. \param[in] sharedParams Model parameters not just used for aligning torque. \param[in] volatileSharedParams Model parameters not just used for aligning torque. \return Aligning torque. */ template<typename TConfig> typename TConfig::Float mfTireAligningTorqueCombined(const typename TConfig::Float tanAlpha, const typename TConfig::Float kappa, const typename TConfig::Float fz, const typename TConfig::Float fx, const typename TConfig::Float fy, const typename TConfig::Float fy0NoCamberNoTurnSlip, const typename TConfig::Float fy0NoCamberNoTurnSlipWeight, const typename TConfig::Float K_kappa, const typename TConfig::Float K_alpha_withEpsilon, const typename TConfig::Float B_lateral, const typename TConfig::Float C_lateral, const typename TConfig::Float Sh_lateral, const typename TConfig::Float Sv_lateral, const MFTireAligningTorquePurePneumaticTrailParams<typename TConfig::Float>& pneumaticTrailParams, const MFTireAligningTorquePureResidualTorqueParams<typename TConfig::Float>& residualTorqueParams, const MFTireAligningTorqueCombinedParams<typename TConfig::Float>& params, const MFTireAligningTorqueVolatileSharedParams<typename TConfig::Float>& volatileSharedParamsAligningTorque, const MFTireSharedParams<typename TConfig::Float>& sharedParams, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; const TFloat kappaScaled = kappa * (K_kappa / K_alpha_withEpsilon); const TFloat kappaScaledSquared = kappaScaled * kappaScaled; const TFloat Mzp = mfTireAligningTorqueCombinedPneumaticTrail<TConfig>(tanAlpha, kappaScaledSquared, fy0NoCamberNoTurnSlip, fy0NoCamberNoTurnSlipWeight, pneumaticTrailParams, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams); const TFloat Mzr = mfTireAligningTorqueCombinedResidualTorque<TConfig>(tanAlpha, kappaScaledSquared, fz, B_lateral, C_lateral, K_alpha_withEpsilon, Sh_lateral, Sv_lateral, residualTorqueParams, volatileSharedParamsAligningTorque, sharedParams, volatileSharedParams); TFloat s = params.sS1 + ( params.sS2 * (fy * sharedParams.recipFz0Scaled) ); if (TConfig::supportCamber) { const TFloat s_term_camber = ( params.sS3 + (params.sS4 * volatileSharedParams.dFz) ) * volatileSharedParams.sinGamma; s += s_term_camber; } s *= sharedParams.r0 * params.lambdaS; const TFloat Mz = Mzp + Mzr + (s * fx); return Mz; } /** \brief Overturning couple \param[in] fz Vertical load (force). fz >= 0. \param[in] r0 Tire radius under no load. \param[in] fyNormalized Normalized lateral force (fy/fz0, fz0=nominal vertical load). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for overturning couple \return Overturning couple (torque). */ template<typename TConfig> typename TConfig::Float mfTireOverturningCouple(const typename TConfig::Float fz, const typename TConfig::Float r0, const typename TConfig::Float fyNormalized, const MFTireOverturningCoupleParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; TFloat Mx = params.qS1 * params.lambdaVM; if (TConfig::supportCamber) { TFloat Mx_term_camber = params.qS2 * volatileSharedParams.gamma; if (TConfig::supportInflationPressure) { const TFloat Mx_term_camber_inflationPressureFactor = TFloat(1.0) + (params.ppM1 * volatileSharedParams.dpi); Mx_term_camber *= Mx_term_camber_inflationPressureFactor; } Mx -= Mx_term_camber; } const TFloat Mx_term_lateral = params.qS3 * fyNormalized; Mx += Mx_term_lateral; const TFloat atanLoad = MF_ARCTAN(params.qS6 * volatileSharedParams.fzNormalized); const TFloat Mx_cosFactor = PxCos(params.qS5 * atanLoad * atanLoad); TFloat Mx_sinFactor = params.qS8 * MF_ARCTAN(params.qS9 * fyNormalized); if (TConfig::supportCamber) { const TFloat Mx_sinFactor_term_camber = params.qS7 * volatileSharedParams.gamma; Mx_sinFactor += Mx_sinFactor_term_camber; } Mx_sinFactor = PxSin(Mx_sinFactor); Mx += params.qS4 * Mx_cosFactor * Mx_sinFactor; if (TConfig::supportCamber) { const TFloat Mx_term_atan = params.qS10 * MF_ARCTAN(params.qS11 * volatileSharedParams.fzNormalized) * volatileSharedParams.gamma; Mx += Mx_term_atan; } Mx *= fz * r0 * params.lambdaM; return Mx; } /** \brief Rolling resistance moment Deformation of the wheel and the road surface usually results in a loss of energy as some of the deformation remains (not fully elastic). Furthermore, slippage between wheel and surface dissipates energy too. The rolling resistance moment models the force that will make a free rolling wheel stop. Note that similar to sliding friction, rolling resistance is often expressed as a coefficient times the normal force (but is generally much smaller than the coefficient of sliding friction). \param[in] fz Vertical load (force). fz >= 0. \param[in] r0 Tire radius under no load. \param[in] fxNormalized Normalized longitudinal force (fx/fz0, fz0=nominal vertical load). \param[in] vxNormalized Normalized longitudinal velocity (vx/v0, v0=reference velocity). \param[in] piNormalized Normalized tire inflation pressure (pi/pi0, pi0=nominal tire inflation pressure). \param[in] params The nondimensional model parameters and user scaling factors. \param[in] volatileSharedParams Model parameters not just used for rolling resistance moment \return Rolling resistance moment. */ template<typename TConfig> typename TConfig::Float mfTireRollingResistanceMoment(const typename TConfig::Float fz, const typename TConfig::Float r0, const typename TConfig::Float fxNormalized, const typename TConfig::Float vxNormalized, const typename TConfig::Float piNormalized, const MFTireRollingResistanceMomentParams<typename TConfig::Float>& params, const MFTireVolatileSharedParams<typename TConfig::Float>& volatileSharedParams) { typedef typename TConfig::Float TFloat; // // rolling resistance force Fr: // // Fr = cr * Fn // // cr: rolling resistance coefficient // Fn: normal force // // Given a drive/break moment Md, part of Md will flow into the longitudinal force and a part into the // rolling resistance moment: // // Md = My + Fx*Rl // // My: rolling resistance moment My (with respect to contact patch) // Fx: longitudinal force at contact patch // Rl: loaded wheel radius // // The rolling resistance moment My can be derived from this: // // My = Fr*Re + Fx*(Re-Rl) // = (Fr+Fx)*Re - Fx*Rl // // Re: effective rolling radius of wheel // const TFloat absVxNormalized = PxAbs(vxNormalized); const TFloat vxNormalizedSqr = absVxNormalized * absVxNormalized; const TFloat vxNormalizedPow4 = vxNormalizedSqr * vxNormalizedSqr; TFloat My = params.qS1 + (params.qS2 * fxNormalized) + (params.qS3 * absVxNormalized) + (params.qS4 * vxNormalizedPow4); if (TConfig::supportCamber) { const TFloat My_term_camber = ( params.qS5 + (params.qS6 * volatileSharedParams.fzNormalized) ) * volatileSharedParams.gammaSqr; My += My_term_camber; } if (volatileSharedParams.fzNormalized > TFloat(0.0)) { TFloat My_powFactor = mfPow(volatileSharedParams.fzNormalized, params.qS7); if (TConfig::supportInflationPressure) { if (piNormalized > TFloat(0.0)) { const TFloat My_powFactor_inflationPressureFactor = mfPow(piNormalized, params.qS8); My_powFactor *= My_powFactor_inflationPressureFactor; } else return TFloat(0.0); } My *= My_powFactor; } else return TFloat(0.0); My *= fz * r0 * params.lambdaM; return My; } /** \brief Free radius of rotating tire The free tire radius of the rotating tire when taking centrifugal growth into account. \param[in] r0 Tire radius under no load. \param[in] omega Tire angular velocity. \param[in] v0 Reference velocity (for normalization. Usually the speed at which measurements were taken, often 16.7m/s, i.e., 60km/h) \param[in] params The nondimensional model parameters. \param[out] normalizedVelR0 Normalized longitudinal velocity due to rotation at unloaded radius (omega * r0 / v0). \return Free radius of rotating tire. */ template<typename TFloat> PX_FORCE_INLINE TFloat mfTireFreeRotatingRadius(const TFloat r0, const TFloat omega, const TFloat v0, const MFTireFreeRotatingRadiusParams<TFloat>& params, TFloat& normalizedVelR0) { const TFloat normalizedVel = (r0 * omega) / v0; normalizedVelR0 = normalizedVel; const TFloat normalizedVelSqr = normalizedVel * normalizedVel; const TFloat rOmega = r0 * ( params.qre0 + (params.qV1*normalizedVelSqr) ); return rOmega; } /** \brief Vertical tire stiffness \param[in] dpi Normalized inflation pressure change: (pi - pi0) / pi0 (with inflation pressure pi and nominal inflation pressure pi0). \param[in] params The nondimensional and derived model parameters. \return Vertical tire stiffness. */ template<typename TConfig> PX_FORCE_INLINE typename TConfig::Float mfTireVerticalStiffness(const typename TConfig::Float dpi, const MFTireVerticalStiffnessParams<typename TConfig::Float>& params) { typedef typename TConfig::Float TFloat; TFloat c = params.c0; if (TConfig::supportInflationPressure) { const TFloat c_inflationPressureFactor = TFloat(1.0) + (params.ppF1 * dpi); c *= c_inflationPressureFactor; } return c; } /** \brief Effective rolling radius The effective rolling radius (re) is the radius that matches the angular velocity (omega) and the velocity at the contact patch (V) under free rolling conditions (no drive/break torque), i.e., re = V / omega. This radius is bounded by the free tire radius of the rotating tire on one end and the loaded tire radius on the other end. The effective rolling radius changes with the load (fast for low values of load but only marginally at higher load values). \param[in] rOmega The free tire radius of the rotating tire when taking centrifugal growth into account. \param[in] cz Vertical stiffness of the tire. \param[in] fz0 Nominal vertical load (force). fz0 >= 0. \param[in] fzNormalized Normalized vertical load: fz / fz0. fzNormalized >= 0. \param[in] params The nondimensional model parameters. \return Effective rolling radius. */ template<typename TFloat> PX_FORCE_INLINE TFloat mfTireEffectiveRollingRadius(const TFloat rOmega, const TFloat cz, const TFloat fz0, const TFloat fzNormalized, const MFTireEffectiveRollingRadiusParams<TFloat>& params) { // // effective rolling radius // const TFloat B_term = params.Breff * fzNormalized; const TFloat D_term = params.Dreff * MF_ARCTAN(B_term); const TFloat F_term = (params.Freff * fzNormalized) + D_term; const TFloat re = rOmega - (fz0 * (F_term / cz)); return re; } /** \brief Normal load of the tire \param[in] fz0 Nominal vertical load (force). fz0 >= 0. \param[in] normalizedVelR0 Normalized longitudinal velocity due to rotation at unloaded radius (omega * r0 / v0, omega: tire angular velocity, r0: unloaded radius, v0: reference velocity for normalization) \param[in] r0 Tire radius under no load. \param[in] fxNormalized Normalized longitudinal force (fx/fz0). \param[in] fyNormalized Normalized lateral force (fy/fz0). \param[in] gammaSqr Camber angle squared. \param[in] deflection Tire normal deflection (difference between free rolling radius and loaded radius). \param[in] dpi Normalized inflation pressure change: (pi - pi0) / pi0 (with inflation pressure pi and nominal inflation pressure pi0). \param[in] params The nondimensional model parameters. \param[in] verticalStiffnessParams The nondimensional model parameters for vertical tire stiffness. \return Normal load (force) of the tire. */ template<typename TConfig> typename TConfig::Float mfTireNormalLoad(const typename TConfig::Float fz0, const typename TConfig::Float normalizedVelR0, const typename TConfig::Float r0, const typename TConfig::Float fxNormalized, const typename TConfig::Float fyNormalized, const typename TConfig::Float gammaSqr, const typename TConfig::Float deflection, const typename TConfig::Float dpi, const MFTireNormalLoadParams<typename TConfig::Float>& params, const MFTireVerticalStiffnessParams<typename TConfig::Float>& verticalStiffnessParams) { typedef typename TConfig::Float TFloat; const TFloat F_term_vel = params.qV2 * PxAbs(normalizedVelR0); const TFloat F_term_long = params.qFc_longitudinal * fxNormalized; const TFloat F_term_longSqr = F_term_long * F_term_long; const TFloat F_term_lat = params.qFc_lateral * fyNormalized; const TFloat F_term_latSqr = F_term_lat * F_term_lat; TFloat F_term_deflection = verticalStiffnessParams.qF1; if (TConfig::supportCamber) { const TFloat F_term_deflection_term_camber = params.qF3 * gammaSqr; F_term_deflection += F_term_deflection_term_camber; } const TFloat normalizedDeflection = deflection / r0; const TFloat F_deflectionFactor = ( F_term_deflection + (verticalStiffnessParams.qF2 * normalizedDeflection) ) * normalizedDeflection; TFloat F = (TFloat(1.0) + F_term_vel - F_term_longSqr - F_term_latSqr) * F_deflectionFactor; if (TConfig::supportInflationPressure) { const TFloat F_inflationPressureFactor = TFloat(1.0) + (verticalStiffnessParams.ppF1 * dpi); F *= F_inflationPressureFactor; } F *= fz0; return F; } template<typename TConfig> PX_FORCE_INLINE typename TConfig::Float mfTireComputeLoad( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float wheelOmega, const typename TConfig::Float tireDeflection, const typename TConfig::Float gammaSqr, const typename TConfig::Float longTireForce, const typename TConfig::Float latTireForce, const typename TConfig::Float tireInflationPressure) { typedef typename TConfig::Float TFloat; PX_ASSERT(tireDeflection >= TFloat(0.0)); const TFloat longTireForceNormalized = longTireForce * tireData.sharedParams.recipFz0; const TFloat latTireForceNormalized = latTireForce * tireData.sharedParams.recipFz0; const TFloat normalizedVelR0 = (wheelOmega * tireData.sharedParams.r0) / tireData.sharedParams.v0; TFloat dpi; if (TConfig::supportInflationPressure) dpi = (tireInflationPressure - tireData.sharedParams.pi0) / tireData.sharedParams.pi0; else dpi = TFloat(0.0); TFloat tireLoad = mfTireNormalLoad<TConfig>(tireData.sharedParams.fz0, normalizedVelR0, tireData.sharedParams.r0, longTireForceNormalized, latTireForceNormalized, gammaSqr, tireDeflection, dpi, tireData.normalLoadParams, tireData.verticalStiffnessParams); return tireLoad; } template<typename TConfig> PX_FORCE_INLINE void mfTireComputeSlip( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float longVelocity, const typename TConfig::Float latVelocity, const typename TConfig::Float wheelOmega, const typename TConfig::Float tireLoad, const typename TConfig::Float tireInflationPressure, typename TConfig::Float& longSlip, typename TConfig::Float& tanLatSlip, typename TConfig::Float& effectiveRollingRadius) { // // see mfTireComputeForce() for the coordinate system used // typedef typename TConfig::Float TFloat; TFloat dpi; if (TConfig::supportInflationPressure) dpi = (tireInflationPressure - tireData.sharedParams.pi0) / tireData.sharedParams.pi0; else dpi = TFloat(0.0); const TFloat fzNormalized = tireLoad * tireData.sharedParams.recipFz0; TFloat normalizedVelR0; PX_UNUSED(normalizedVelR0); const TFloat rOmega = mfTireFreeRotatingRadius(tireData.sharedParams.r0, wheelOmega, tireData.sharedParams.v0, tireData.freeRotatingRadiusParams, normalizedVelR0); const TFloat vertTireStiffness = mfTireVerticalStiffness<TConfig>(dpi, tireData.verticalStiffnessParams); const TFloat re = mfTireEffectiveRollingRadius(rOmega, vertTireStiffness, tireData.sharedParams.fz0, fzNormalized, tireData.effectiveRollingRadiusParams); effectiveRollingRadius = re; const TFloat absLongVelocityPlusEpsilon = PxAbs(longVelocity) + tireData.sharedParams.epsilonV; const bool isAboveOrEqLongVelThreshold = absLongVelocityPlusEpsilon >= tireData.sharedParams.slipReductionLowVelocity; TFloat absLongVelocityInterpolated; if (isAboveOrEqLongVelThreshold) absLongVelocityInterpolated = absLongVelocityPlusEpsilon; else { // interpolation with a quadratic weight change for the threshold velocity such that the effect reduces // fast with growing velocity. Read section about oscillation further below. const TFloat longVelRatio = absLongVelocityPlusEpsilon / tireData.sharedParams.slipReductionLowVelocity; TFloat interpFactor = TFloat(1.0) - longVelRatio; interpFactor = interpFactor * interpFactor; absLongVelocityInterpolated = (interpFactor * tireData.sharedParams.slipReductionLowVelocity) + ((TFloat(1.0) - interpFactor) * absLongVelocityPlusEpsilon); } // // longitudinal slip ratio (kappa): // // kappa = - (Vsx / |Vcx|) // // note: sign is chosen to get positive value under drive torque and negative under break torque // // ---------------------------------------------------------------------------------------------------------------- // Vcx: velocity of wheel contact center, projected onto wheel x-axis (direction wheel is pointing to) // ---------------------------------------------------------------------------------------------------------------- // Vsx: longitudinal slip velocity // = Vcx - (omega * Re) // (difference between the actual velocity at the wheel contact point and the "orbital" velocity from the // wheel rotation) // ----------------------------------------------------------------------------------------------------------- // omega: wheel rotational velocity // ----------------------------------------------------------------------------------------------------------- // Re: effective rolling radius (at free rolling of the tire, no brake/drive torque) // At constant speed with no brake/drive torque, using Re will result in Vsx (and thus kappa) being 0. // ---------------------------------------------------------------------------------------------------------------- // // Problems at low velocities and starting from standstill etc. // - oscillation: // division by small velocity values results in large slip values and thus in large forces. For large // time steps this results in overshooting a stable state. // The applied formulas are for the steady-state only. This will add to the overshooting too. // Furthermore, the algorithm is prone to oscillation at low velocities to begin with. // - zero slip does not mean zero force: // the formulas include shift terms in the function input and output values. That will result in non-zero forces // even if the slip is 0. // // Reducing these problems: // - run at smaller time steps // - artificially lower slip values when the velocity is below a threshold. This is done by replacing the actual Vcx // velocity with an interpolation between the real Vcx and a threshold velocity if Vcx is below the threshold // velocity (for example, if Vcx was 0, the threshold velocity would be used instead). The larger the threshold // velocity, the less oscillation is observed at the cost of affecting the simulation behavior at normal speeds. // const TFloat longSlipVelocityNeg = (wheelOmega * re) - longVelocity; // = -Vsx const TFloat longSlipRatio = longSlipVelocityNeg / absLongVelocityInterpolated; longSlip = longSlipRatio; // // lateral slip angle (alpha): // // alpha = arctan(-Vcy / |Vcx|) // // note: sign is chosen to get positive force value if the slip is positive // // ---------------------------------------------------------------------------------------------------------------- // Vcx: velocity of wheel contact center, projected onto wheel x-axis (direction wheel is pointing to) // ---------------------------------------------------------------------------------------------------------------- // Vcy: velocity of wheel contact center, projected onto wheel y-axis (direction pointing to the side of the wheel, // that is, perpendicular to x-axis mentioned above) // ---------------------------------------------------------------------------------------------------------------- // const TFloat tanSlipAngle = (-latVelocity) / absLongVelocityInterpolated; tanLatSlip = tanSlipAngle; } template<typename TConfig> PX_FORCE_INLINE void mfTireComputeForce( const MFTireDataT<typename TConfig::Float>& tireData, const typename TConfig::Float tireFriction, const typename TConfig::Float longSlip, const typename TConfig::Float tanLatSlip, const typename TConfig::Float camber, const typename TConfig::Float effectiveRollingRadius, const typename TConfig::Float tireLoad, const typename TConfig::Float tireInflationPressure, const typename TConfig::Float longVelocity, const typename TConfig::Float latVelocity, typename TConfig::Float& wheelTorque, typename TConfig::Float& tireLongForce, typename TConfig::Float& tireLatForce, typename TConfig::Float& tireAlignMoment) { typedef typename TConfig::Float TFloat; PX_ASSERT(tireFriction > 0); PX_ASSERT(tireLoad >= 0); wheelTorque = TFloat(0.0); tireLongForce = TFloat(0.0); tireLatForce = TFloat(0.0); tireAlignMoment = TFloat(0.0); /* // Magic Formula Tire Model // // Implementation follows pretty closely the description in the book: // Tire and Vehicle Dynamics, 3rd Edition, Hans Pacejka // The steady-state model is implemented only. // // General limitations: // - expects rather smooth road surface (surface wavelengths longer than a tire radius) up to frequencies of 8 Hz // (for steady-state model around 1 Hz only) // // // The magic formula (see magicFormulaSine(), magicFormulaCosine()) is used as a basis for describing curves for // longitudinal/lateral force, aligning torque etc. // // // The model uses the following coordinate system for the tire: // // top view: side view: // // // ________________________ __________ // | | ___/ \___ // | ----------------> x __/ \__ // |____________|___________| / \ // | | | // | / \ // | | | // | | ---------------------> x // | \ | / // v | | | // y \__ | __/ // \___ | ___/ // _ _ _ _ _ _ \_____|____/ _ _ _ _ _ _ // | // | // v // z */ MFTireVolatileSharedParams<TFloat> volatileSharedParams; { mfTireComputeVolatileSharedParams<TConfig>(camber, tireLoad, tireFriction, tireFriction, tireInflationPressure, tireData.sharedParams, volatileSharedParams); } // note: even if long slip/lat slip/camber are all zero, the computation takes place as the model can take effects like // conicity etc. into account (thus, forces might not be 0 even if slip and camber are 0) TFloat K_kappa_longitudinal; const TFloat longForcePure = mfTireLongitudinalForcePure<TConfig>(longSlip, tireLoad, tireData.longitudinalForcePureParams, tireData.sharedParams, volatileSharedParams, K_kappa_longitudinal); const TFloat longForceCombined = mfTireLongitudinalForceCombined<TConfig>(longSlip, tanLatSlip, longForcePure, tireData.longitudinalForceCombinedParams, volatileSharedParams); tireLongForce = longForceCombined; TFloat latForcePureNoCamberNoTurnSlip; TFloat latForcePureNoCamberNoTurnSlipWeight; TFloat* latForcePureNoCamberNoTurnSlipPtr; TFloat* latForcePureNoCamberNoTurnSlipWeightPtr; if (tireData.flags & MFTireDataFlag::eALIGNING_MOMENT) { latForcePureNoCamberNoTurnSlipPtr = &latForcePureNoCamberNoTurnSlip; latForcePureNoCamberNoTurnSlipWeightPtr = &latForcePureNoCamberNoTurnSlipWeight; } else { latForcePureNoCamberNoTurnSlipPtr = NULL; latForcePureNoCamberNoTurnSlipWeightPtr = NULL; } TFloat B_lateral, C_lateral, K_alpha_withEpsilon_lateral, Sh_lateral, Sv_lateral, mu_zeta2; const TFloat latForcePure = mfTireLateralForcePure<TConfig>(tanLatSlip, tireLoad, tireData.lateralForcePureParams, tireData.sharedParams, volatileSharedParams, latForcePureNoCamberNoTurnSlipPtr, B_lateral, C_lateral, K_alpha_withEpsilon_lateral, Sh_lateral, Sv_lateral, mu_zeta2); const TFloat latForceCombined = mfTireLateralForceCombined<TConfig>(tanLatSlip, longSlip, tireLoad, latForcePure, mu_zeta2, tireData.lateralForceCombinedParams, volatileSharedParams, latForcePureNoCamberNoTurnSlipWeightPtr); tireLatForce = latForceCombined; if (tireData.flags & MFTireDataFlag::eALIGNING_MOMENT) { MFTireAligningTorqueVolatileSharedParams<TFloat> aligningTorqueVolatileSharedParams; const TFloat combinedVelocity = PxSqrt((longVelocity*longVelocity) + (latVelocity*latVelocity)); mfTireComputeAligningTorqueVolatileSharedParams(combinedVelocity, longVelocity, tireData.sharedParams.epsilonV, aligningTorqueVolatileSharedParams); const TFloat aligningTorque = mfTireAligningTorqueCombined<TConfig>(tanLatSlip, longSlip, tireLoad, longForceCombined, latForceCombined, *latForcePureNoCamberNoTurnSlipPtr, *latForcePureNoCamberNoTurnSlipWeightPtr, K_kappa_longitudinal, K_alpha_withEpsilon_lateral, B_lateral, C_lateral, Sh_lateral, Sv_lateral, tireData.aligningTorquePurePneumaticTrailParams, tireData.aligningTorquePureResidualTorqueParams, tireData.aligningTorqueCombinedParams, aligningTorqueVolatileSharedParams, tireData.sharedParams, volatileSharedParams); tireAlignMoment = aligningTorque; } wheelTorque = -tireLongForce * effectiveRollingRadius; } #if !PX_DOXYGEN } // namespace physx #endif #endif //VEHICLE_MF_TIRE_H
75,720
C
41.587739
209
0.69617
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTire.h
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #pragma once #include "PxPhysicsAPI.h" #include "VehicleMFTireData.h" namespace snippetvehicle2 { using namespace physx; using namespace physx::vehicle2; /** \brief Struct to configure the templated functions of the Magic Formula Tire Model. A typedef named "Float" declares the floating point type to use (to configure for 32bit or 64bit precision). Some static boolean members allow to enable/disable code at compile time depending on the desired feature set and complexity. */ struct MFTireConfig { typedef PxF32 Float; static const bool supportInflationPressure = false; //PhysX vehicles do not model inflation pressure (nore can it be derived/estimated //from the PhysX state values). static const bool supportCamber = true; static const bool supportTurnSlip = false; //Turn slip effects will be ignored (same as having all parameters named "zeta..." set to 1). }; typedef MFTireDataT<MFTireConfig::Float> MFTireData; /** \brief Custom method to compute tire grip values. \note If the suspension cannot place the wheel on the ground, the tire load and friction will be 0. \param[in] isWheelOnGround True if the wheel is touching the ground. \param[in] unfilteredLoad The force pushing the tire to the ground. \param[in] restLoad The nominal vertical load of the tire (the expected load at rest). \param[in] maxNormalizedLoad The maximum normalized load (load / restLoad). Values above will result in the load being clamped. This can avoid instabilities when dealing with discontinuities that generate large load (like the suspension compressing by a large delta for a small simulation timestep). \param[in] friction The friction coefficient to use. \param[out] tireGripState The computed load and friction experienced by the tire. */ void CustomTireGripUpdate( bool isWheelOnGround, PxF32 unfilteredLoad, PxF32 restLoad, PxF32 maxNormalizedLoad, PxF32 friction, PxVehicleTireGripState& tireGripState); /** \brief Custom method to compute tire slip values. \note See MFTireConfig for the configuration this method is defined for. \param[in] tireData The tire parameters of the Magic Formula Tire Model. \param[in] tireSpeedState The velocity at the tire contact point projected along the tire's longitudinal and lateral axes. \param[in] wheelOmega The wheel rotation speed in radians per second. \param[in] tireLoad The force pushing the tire to the ground. \param[out] tireSlipState The computed tire longitudinal and lateral slips. \param[out] effectiveRollingRadius The radius re that matches the angular velocity (omega) and the velocity at the contact patch (V) under free rolling conditions (no drive/break torque), i.e., re = V / omega. This radius is bounded by the free tire radius of the rotating tire on one end and the loaded tire radius on the other end. The effective rolling radius changes with the load (fast for low values of load but only marginally at higher load values). */ void CustomTireSlipsUpdate( const MFTireData& tireData, const PxVehicleTireSpeedState& tireSpeedState, PxF32 wheelOmega, PxF32 tireLoad, PxVehicleTireSlipState& tireSlipState, PxF32& effectiveRollingRadius); /** \brief Custom method to compute the longitudinal and lateral tire forces using the Magic Formula Tire Model. \note See MFTireConfig for the configuration this method is defined for. \note This tire model requires running with a high simulation update rate (1kHz is recommended). \param[in] tireData The tire parameters of the Magic Formula Tire Model. \param[in] tireSlipState The tire longitudinal and lateral slips. \param[in] tireSpeedState The velocity at the tire contact point projected along the tire's longitudinal and lateral axes. \param[in] tireDirectionState The tire's longitudinal and lateral directions in the ground plane. \param[in] tireGripState The load and friction experienced by the tire. \param[in] tireStickyState Description of the sticky state of the tire in the longitudinal and lateral directions. \param[in] bodyPose The world transform of the vehicle body. \param[in] suspensionAttachmentPose The transform of the suspension attachment (in vehicle body space). \param[in] tireForceApplicationPoint The tire force application point (in suspension attachment space). \param[in] camber The camber angle of the tire expressed in radians. \param[in] effectiveRollingRadius The radius under free rolling conditions (see CustomTireSlipsUpdate for details). \param[out] tireForce The computed tire forces in the world frame. */ void CustomTireForcesUpdate( const MFTireData& tireData, const PxVehicleTireSlipState& tireSlipState, const PxVehicleTireSpeedState& tireSpeedState, const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireGripState& tireGripState, const PxVehicleTireStickyState& tireStickyState, const PxTransform& bodyPose, const PxTransform& suspensionAttachmentPose, const PxVec3& tireForceApplicationPoint, PxF32 camber, PxF32 effectiveRollingRadius, PxVehicleTireForce& tireForce); struct CustomTireParams { MFTireData mfTireData; PxReal maxNormalizedLoad; // maximum normalized load (load / restLoad). Values above will be clamped. // Large discontinuities can cause unnaturally large load values which the // Magic Formula Tire Model does not support (for example having the wheel // go from one frame with no ground contact to a highly compressed suspension // in the next frame). }; class CustomTireComponent : public PxVehicleComponent { public: CustomTireComponent() : PxVehicleComponent() {} virtual void getDataForCustomTireComponent( const PxVehicleAxleDescription*& axleDescription, PxVehicleArrayData<const PxReal>& steerResponseStates, const PxVehicleRigidBodyState*& rigidBodyState, PxVehicleArrayData<const PxVehicleWheelActuationState>& actuationStates, PxVehicleArrayData<const PxVehicleWheelParams>& wheelParams, PxVehicleArrayData<const PxVehicleSuspensionParams>& suspensionParams, PxVehicleArrayData<const CustomTireParams>& tireParams, PxVehicleArrayData<const PxVehicleRoadGeometryState>& roadGeomStates, PxVehicleArrayData<const PxVehicleSuspensionState>& suspensionStates, PxVehicleArrayData<const PxVehicleSuspensionComplianceState>& suspensionComplianceStates, PxVehicleArrayData<const PxVehicleSuspensionForce>& suspensionForces, PxVehicleArrayData<const PxVehicleWheelRigidBody1dState>& wheelRigidBody1DStates, PxVehicleArrayData<PxVehicleTireGripState>& tireGripStates, PxVehicleArrayData<PxVehicleTireDirectionState>& tireDirectionStates, PxVehicleArrayData<PxVehicleTireSpeedState>& tireSpeedStates, PxVehicleArrayData<PxVehicleTireSlipState>& tireSlipStates, PxVehicleArrayData<PxVehicleTireCamberAngleState>& tireCamberAngleStates, PxVehicleArrayData<PxVehicleTireStickyState>& tireStickyStates, PxVehicleArrayData<PxVehicleTireForce>& tireForces) = 0; virtual bool update(const PxReal dt, const PxVehicleSimulationContext& context) { const PxVehicleAxleDescription* axleDescription; PxVehicleArrayData<const PxReal> steerResponseStates; const PxVehicleRigidBodyState* rigidBodyState; PxVehicleArrayData<const PxVehicleWheelActuationState> actuationStates; PxVehicleArrayData<const PxVehicleWheelParams> wheelParams; PxVehicleArrayData<const PxVehicleSuspensionParams> suspensionParams; PxVehicleArrayData<const CustomTireParams> tireParams; PxVehicleArrayData<const PxVehicleRoadGeometryState> roadGeomStates; PxVehicleArrayData<const PxVehicleSuspensionState> suspensionStates; PxVehicleArrayData<const PxVehicleSuspensionComplianceState> suspensionComplianceStates; PxVehicleArrayData<const PxVehicleSuspensionForce> suspensionForces; PxVehicleArrayData<const PxVehicleWheelRigidBody1dState> wheelRigidBody1DStates; PxVehicleArrayData<PxVehicleTireGripState> tireGripStates; PxVehicleArrayData<PxVehicleTireDirectionState> tireDirectionStates; PxVehicleArrayData<PxVehicleTireSpeedState> tireSpeedStates; PxVehicleArrayData<PxVehicleTireSlipState> tireSlipStates; PxVehicleArrayData<PxVehicleTireCamberAngleState> tireCamberAngleStates; PxVehicleArrayData<PxVehicleTireStickyState> tireStickyStates; PxVehicleArrayData<PxVehicleTireForce> tireForces; getDataForCustomTireComponent(axleDescription, steerResponseStates, rigidBodyState, actuationStates, wheelParams, suspensionParams, tireParams, roadGeomStates, suspensionStates, suspensionComplianceStates, suspensionForces, wheelRigidBody1DStates, tireGripStates, tireDirectionStates, tireSpeedStates, tireSlipStates, tireCamberAngleStates, tireStickyStates, tireForces); for (PxU32 i = 0; i < axleDescription->nbWheels; i++) { const PxU32 wheelId = axleDescription->wheelIdsInAxleOrder[i]; const PxReal& steerResponseState = steerResponseStates[wheelId]; const PxVehicleWheelParams& wheelParam = wheelParams[wheelId]; const PxVehicleSuspensionParams& suspensionParam = suspensionParams[wheelId]; const CustomTireParams& tireParam = tireParams[wheelId]; const PxVehicleRoadGeometryState& roadGeomState = roadGeomStates[wheelId]; const PxVehicleSuspensionState& suspensionState = suspensionStates[wheelId]; const PxVehicleSuspensionComplianceState& suspensionComplianceState = suspensionComplianceStates[wheelId]; const PxVehicleWheelRigidBody1dState& wheelRigidBody1dState = wheelRigidBody1DStates[wheelId]; const bool isWheelOnGround = PxVehicleIsWheelOnGround(suspensionState); //Compute the tire slip directions PxVehicleTireDirectionState& tireDirectionState = tireDirectionStates[wheelId]; PxVehicleTireDirsUpdate( suspensionParam, steerResponseState, roadGeomState.plane.n, isWheelOnGround, suspensionComplianceState, *rigidBodyState, context.frame, tireDirectionState); //Compute the rigid body speeds along the tire slip directions. PxVehicleTireSpeedState& tireSpeedState = tireSpeedStates[wheelId]; PxVehicleTireSlipSpeedsUpdate( wheelParam, suspensionParam, steerResponseState, suspensionState, tireDirectionState, *rigidBodyState, roadGeomState, context.frame, tireSpeedState); //Compute grip state PxVehicleTireGripState& tireGripState = tireGripStates[wheelId]; CustomTireGripUpdate( isWheelOnGround, suspensionForces[wheelId].normalForce, PxF32(tireParam.mfTireData.sharedParams.fz0), tireParam.maxNormalizedLoad, roadGeomState.friction, tireGripState); //Compute the tire slip values. PxVehicleTireSlipState& tireSlipState = tireSlipStates[wheelId]; PxF32 effectiveRollingRadius; //Ensure radius is in sync #if PX_ENABLE_ASSERTS // avoid warning about unusued local typedef typedef MFTireConfig::Float TFloat; #endif PX_ASSERT(PxAbs(tireParam.mfTireData.sharedParams.r0 - TFloat(wheelParam.radius)) < (tireParam.mfTireData.sharedParams.r0 * TFloat(0.01))); CustomTireSlipsUpdate( tireParam.mfTireData, tireSpeedState, wheelRigidBody1dState.rotationSpeed, tireGripState.load, tireSlipState, effectiveRollingRadius); //Update the camber angle PxVehicleTireCamberAngleState& tireCamberAngleState = tireCamberAngleStates[wheelId]; PxVehicleTireCamberAnglesUpdate( suspensionParam, steerResponseState, roadGeomState.plane.n, isWheelOnGround, suspensionComplianceState, *rigidBodyState, context.frame, tireCamberAngleState); //Update the tire sticky state // //Note: this should be skipped if tires do not use the sticky feature PxVehicleTireStickyState& tireStickyState = tireStickyStates[wheelId]; PxVehicleTireStickyStateUpdate( *axleDescription, wheelParam, context.tireStickyParams, actuationStates, tireGripState, tireSpeedState, wheelRigidBody1dState, dt, tireStickyState); //If sticky tire is active set the slip values to zero. // //Note: this should be skipped if tires do not use the sticky feature PxVehicleTireSlipsAccountingForStickyStatesUpdate( tireStickyState, tireSlipState); //Compute the tire forces PxVehicleTireForce& tireForce = tireForces[wheelId]; CustomTireForcesUpdate( tireParam.mfTireData, tireSlipState, tireSpeedState, tireDirectionState, tireGripState, tireStickyState, rigidBodyState->pose, suspensionParam.suspensionAttachment, suspensionComplianceState.tireForceAppPoint, tireCamberAngleState.camberAngle, effectiveRollingRadius, tireForce); } return true; } }; }//namespace snippetvehicle2
14,361
C
43.741433
142
0.795766
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTireVehicle.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "CustomTireVehicle.h" namespace snippetvehicle2 { template<typename TFloat> static void setExampleSharedParams(MFTireSharedParams<TFloat>& sharedParams, const TFloat lengthScale) { sharedParams.r0 = TFloat(0.3135) * lengthScale; // tire radius under no load (base unit is [m]) sharedParams.v0 = TFloat(16.7) * lengthScale; // reference velocity (=60km/h) (base unit is [m/s]) sharedParams.fz0 = TFloat(4000.0) * lengthScale; // nominal load (base unit is [N]) sharedParams.pi0 = TFloat(220000.0) / lengthScale; // nominal inflation pressure (=2.2 bar) (base unit is [Pa]) sharedParams.epsilonV = TFloat(0.01) * lengthScale; sharedParams.slipReductionLowVelocity = TFloat(7.0) * lengthScale; sharedParams.lambdaFz0 = TFloat(1.0); sharedParams.lambdaK_alpha = TFloat(1.0); sharedParams.aMu = TFloat(10.0); sharedParams.zeta0 = TFloat(1.0); sharedParams.zeta2 = TFloat(1.0); mfTireComputeDerivedSharedParams(sharedParams); } template<typename TFloat> static void setExampleLongitudinalForcePureParams(MFTireLongitudinalForcePureParams<TFloat>& longitudinalForcePureParams, const TFloat lengthScale) { longitudinalForcePureParams.pK1 = TFloat(21.687); longitudinalForcePureParams.pK2 = TFloat(13.728); longitudinalForcePureParams.pK3 = TFloat(-0.4098); longitudinalForcePureParams.pp1 = TFloat(-0.3485); longitudinalForcePureParams.pp2 = TFloat(0.37824); longitudinalForcePureParams.lambdaK = TFloat(1.0); longitudinalForcePureParams.epsilon = TFloat(1.0) * lengthScale; //--- longitudinalForcePureParams.pC1 = TFloat(1.579); longitudinalForcePureParams.lambdaC = TFloat(1.0); //--- longitudinalForcePureParams.pD1 = TFloat(1.0422); longitudinalForcePureParams.pD2 = TFloat(-0.08285); longitudinalForcePureParams.pD3 = TFloat(0.0); longitudinalForcePureParams.pp3 = TFloat(-0.09603); longitudinalForcePureParams.pp4 = TFloat(0.06518); //--- longitudinalForcePureParams.pE1 = TFloat(0.11113); longitudinalForcePureParams.pE2 = TFloat(0.3143); longitudinalForcePureParams.pE3 = TFloat(0.0); longitudinalForcePureParams.pE4 = TFloat(0.001719); longitudinalForcePureParams.lambdaE = TFloat(1.0); //--- longitudinalForcePureParams.pH1 = TFloat(2.1615e-4); longitudinalForcePureParams.pH2 = TFloat(0.0011598); longitudinalForcePureParams.lambdaH = TFloat(1.0); //--- longitudinalForcePureParams.pV1 = TFloat(2.0283e-5); longitudinalForcePureParams.pV2 = TFloat(1.0568e-4); longitudinalForcePureParams.lambdaV = TFloat(1.0); longitudinalForcePureParams.zeta1 = TFloat(1.0); } template<typename TFloat> static void setExampleLongitudinalForceCombinedParams(MFTireLongitudinalForceCombinedParams<TFloat>& longitudinalForceCombinedParams) { longitudinalForceCombinedParams.rB1 = TFloat(13.046); longitudinalForceCombinedParams.rB2 = TFloat(9.718); longitudinalForceCombinedParams.rB3 = TFloat(0.0); longitudinalForceCombinedParams.lambdaAlpha = TFloat(1.0); //--- longitudinalForceCombinedParams.rC1 = TFloat(0.9995); //--- longitudinalForceCombinedParams.rE1 = TFloat(-0.4403); longitudinalForceCombinedParams.rE2 = TFloat(-0.4663); //--- longitudinalForceCombinedParams.rH1 = TFloat(-9.968e-5); } template<typename TFloat> static void setExampleLateralForcePureParams(MFTireLateralForcePureParams<TFloat>& lateralForcePureParams, const TFloat lengthScale) { lateralForcePureParams.pK1 = TFloat(15.324); // note: original source uses ISO sign convention and thus the value was negative lateralForcePureParams.pK2 = TFloat(1.715); lateralForcePureParams.pK3 = TFloat(0.3695); lateralForcePureParams.pK4 = TFloat(2.0005); lateralForcePureParams.pK5 = TFloat(0.0); lateralForcePureParams.pp1 = TFloat(-0.6255); lateralForcePureParams.pp2 = TFloat(-0.06523); lateralForcePureParams.epsilon = TFloat(1.0) * lengthScale; lateralForcePureParams.zeta3 = TFloat(1.0); //--- lateralForcePureParams.pC1 = TFloat(1.338); lateralForcePureParams.lambdaC = TFloat(1.0); //--- lateralForcePureParams.pD1 = TFloat(0.8785); lateralForcePureParams.pD2 = TFloat(-0.06452); lateralForcePureParams.pD3 = TFloat(0.0); lateralForcePureParams.pp3 = TFloat(-0.16666); lateralForcePureParams.pp4 = TFloat(0.2811); //--- lateralForcePureParams.pE1 = TFloat(-0.8057); lateralForcePureParams.pE2 = TFloat(-0.6046); lateralForcePureParams.pE3 = TFloat(0.09854); lateralForcePureParams.pE4 = TFloat(-6.697); lateralForcePureParams.pE5 = TFloat(0.0); lateralForcePureParams.lambdaE = TFloat(1.0); //--- lateralForcePureParams.pH1 = TFloat(-0.001806); lateralForcePureParams.pH2 = TFloat(0.00352); lateralForcePureParams.pK6 = TFloat(-0.8987); lateralForcePureParams.pK7 = TFloat(-0.23303); lateralForcePureParams.pp5 = TFloat(0.0); lateralForcePureParams.lambdaH = TFloat(1.0); lateralForcePureParams.epsilonK = TFloat(10.0) * lengthScale; lateralForcePureParams.zeta4 = TFloat(1.0); //--- lateralForcePureParams.pV1 = TFloat(-0.00661); lateralForcePureParams.pV2 = TFloat(0.03592); lateralForcePureParams.pV3 = TFloat(-0.162); lateralForcePureParams.pV4 = TFloat(-0.4864); lateralForcePureParams.lambdaV = TFloat(1.0); lateralForcePureParams.lambdaK_gamma = TFloat(1.0); } template<typename TFloat> static void setExampleLateralForceCombinedParams(MFTireLateralForceCombinedParams<TFloat>& lateralForceCombinedParams) { lateralForceCombinedParams.rB1 = TFloat(10.622); lateralForceCombinedParams.rB2 = TFloat(7.82); lateralForceCombinedParams.rB3 = TFloat(0.002037); lateralForceCombinedParams.rB4 = TFloat(0.0); lateralForceCombinedParams.lambdaKappa = TFloat(1.0); //--- lateralForceCombinedParams.rC1 = TFloat(1.0587); //-- lateralForceCombinedParams.rE1 = TFloat(0.3148); lateralForceCombinedParams.rE2 = TFloat(0.004867); //--- lateralForceCombinedParams.rH1 = TFloat(0.009472); lateralForceCombinedParams.rH2 = TFloat(0.009754); //--- lateralForceCombinedParams.rV1 = TFloat(0.05187); lateralForceCombinedParams.rV2 = TFloat(4.853e-4); lateralForceCombinedParams.rV3 = TFloat(0.0); lateralForceCombinedParams.rV4 = TFloat(94.63); lateralForceCombinedParams.rV5 = TFloat(1.8914); lateralForceCombinedParams.rV6 = TFloat(23.8); lateralForceCombinedParams.lambdaV = TFloat(1.0); } template<typename TFloat> static void setExampleAligningTorquePurePneumaticTrailParams(MFTireAligningTorquePurePneumaticTrailParams<TFloat>& aligningTorquePurePneumaticTrailParams) { aligningTorquePurePneumaticTrailParams.qB1 = TFloat(12.035); aligningTorquePurePneumaticTrailParams.qB2 = TFloat(-1.33); aligningTorquePurePneumaticTrailParams.qB3 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.qB5 = TFloat(-0.14853); aligningTorquePurePneumaticTrailParams.qB6 = TFloat(0.0); //--- aligningTorquePurePneumaticTrailParams.qC1 = TFloat(1.2923); //--- aligningTorquePurePneumaticTrailParams.qD1 = TFloat(0.09068); aligningTorquePurePneumaticTrailParams.qD2 = TFloat(-0.00565); aligningTorquePurePneumaticTrailParams.qD3 = TFloat(0.3778); aligningTorquePurePneumaticTrailParams.qD4 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.pp1 = TFloat(-0.4408); aligningTorquePurePneumaticTrailParams.lambdaT = TFloat(1.0); aligningTorquePurePneumaticTrailParams.zeta5 = TFloat(1.0); //--- aligningTorquePurePneumaticTrailParams.qE1 = TFloat(-1.7924); aligningTorquePurePneumaticTrailParams.qE2 = TFloat(0.8975); aligningTorquePurePneumaticTrailParams.qE3 = TFloat(0.0); aligningTorquePurePneumaticTrailParams.qE4 = TFloat(0.2895); aligningTorquePurePneumaticTrailParams.qE5 = TFloat(-0.6786); //--- aligningTorquePurePneumaticTrailParams.qH1 = TFloat(0.0014333); aligningTorquePurePneumaticTrailParams.qH2 = TFloat(0.0024087); aligningTorquePurePneumaticTrailParams.qH3 = TFloat(0.24973); aligningTorquePurePneumaticTrailParams.qH4 = TFloat(-0.21205); } template<typename TFloat> static void setExampleAligningTorquePureResidualTorqueParams(MFTireAligningTorquePureResidualTorqueParams<TFloat>& aligningTorquePureResidualTorqueParams) { aligningTorquePureResidualTorqueParams.qB9 = TFloat(34.5); aligningTorquePureResidualTorqueParams.qB10 = TFloat(0.0); aligningTorquePureResidualTorqueParams.zeta6 = TFloat(1.0); //--- aligningTorquePureResidualTorqueParams.zeta7 = TFloat(1.0); //--- aligningTorquePureResidualTorqueParams.qD6 = TFloat(0.0017015); aligningTorquePureResidualTorqueParams.qD7 = TFloat(-0.002091); aligningTorquePureResidualTorqueParams.qD8 = TFloat(-0.1428); aligningTorquePureResidualTorqueParams.qD9 = TFloat(0.00915); aligningTorquePureResidualTorqueParams.qD10 = TFloat(0.0); aligningTorquePureResidualTorqueParams.qD11 = TFloat(0.0); aligningTorquePureResidualTorqueParams.pp2 = TFloat(0.0); aligningTorquePureResidualTorqueParams.lambdaR = TFloat(1.0); aligningTorquePureResidualTorqueParams.lambdaK_gamma = TFloat(1.0); aligningTorquePureResidualTorqueParams.zeta8 = TFloat(1.0); } template<typename TFloat> static void setExampleAligningTorqueCombinedParams(MFTireAligningTorqueCombinedParams<TFloat>& aligningTorqueCombinedParams) { aligningTorqueCombinedParams.sS1 = TFloat(0.00918); aligningTorqueCombinedParams.sS2 = TFloat(0.03869); aligningTorqueCombinedParams.sS3 = TFloat(0.0); aligningTorqueCombinedParams.sS4 = TFloat(0.0); aligningTorqueCombinedParams.lambdaS = TFloat(1.0); } //For completeness but not used in this example /*template<typename TFloat> static void setExampleOverturningCoupleParams(MFTireOverturningCoupleParams<TFloat>& overturningCoupleParams) { overturningCoupleParams.qS1 = TFloat(-0.007764); overturningCoupleParams.qS2 = TFloat(1.1915); overturningCoupleParams.qS3 = TFloat(0.013948); overturningCoupleParams.qS4 = TFloat(4.912); overturningCoupleParams.qS5 = TFloat(1.02); overturningCoupleParams.qS6 = TFloat(22.83); overturningCoupleParams.qS7 = TFloat(0.7104); overturningCoupleParams.qS8 = TFloat(-0.023393); overturningCoupleParams.qS9 = TFloat(0.6581); overturningCoupleParams.qS10 = TFloat(0.2824); overturningCoupleParams.qS11 = TFloat(5.349); overturningCoupleParams.ppM1 = TFloat(0.0); overturningCoupleParams.lambdaVM = TFloat(1.0); overturningCoupleParams.lambdaM = TFloat(1.0); } template<typename TFloat> static void setExampleRollingResistanceMomentParams(MFTireRollingResistanceMomentParams<TFloat>& rollingResistanceMomentParams) { rollingResistanceMomentParams.qS1 = TFloat(0.00702); rollingResistanceMomentParams.qS2 = TFloat(0.0); rollingResistanceMomentParams.qS3 = TFloat(0.001515); rollingResistanceMomentParams.qS4 = TFloat(8.514e-5); rollingResistanceMomentParams.qS5 = TFloat(0.0); rollingResistanceMomentParams.qS6 = TFloat(0.0); rollingResistanceMomentParams.qS7 = TFloat(0.9008); rollingResistanceMomentParams.qS8 = TFloat(-0.4089); rollingResistanceMomentParams.lambdaM = TFloat(1.0); }*/ template<typename TFloat> static void setExampleFreeRotatingRadiusParams(MFTireFreeRotatingRadiusParams<TFloat>& freeRotatingRadiusParams) { freeRotatingRadiusParams.qre0 = TFloat(0.9974); freeRotatingRadiusParams.qV1 = TFloat(7.742e-4); } template<typename TFloat> static void setExampleVerticalStiffnessParams(const TFloat r0, const TFloat fz0, MFTireVerticalStiffnessParams<TFloat>& verticalStiffnessParams) { verticalStiffnessParams.qF1 = TFloat(14.435747); verticalStiffnessParams.qF2 = TFloat(15.4); verticalStiffnessParams.ppF1 = TFloat(0.7098); verticalStiffnessParams.lambdaC = TFloat(1.0); mfTireComputeDerivedVerticalTireStiffnessParams(r0, fz0, verticalStiffnessParams); } template<typename TFloat> static void setExampleNormalLoadParams(MFTireNormalLoadParams<TFloat>& normalLoadParams) { normalLoadParams.qV2 = TFloat(0.04667); normalLoadParams.qFc_longitudinal = TFloat(0.0); normalLoadParams.qFc_lateral = TFloat(0.0); normalLoadParams.qF3 = TFloat(0.0); } template<typename TFloat> static void setExampleEffectiveRollingRadiusParams(MFTireEffectiveRollingRadiusParams<TFloat>& effectiveRollingRadiusParams) { effectiveRollingRadiusParams.Freff = TFloat(0.07394); effectiveRollingRadiusParams.Dreff = TFloat(0.25826); effectiveRollingRadiusParams.Breff = TFloat(8.386); } template<typename TFloat> static void setExampleTireData(const TFloat lengthScale, const bool computeAligningMoment, MFTireDataT<TFloat>& tireData) { setExampleSharedParams(tireData.sharedParams, lengthScale); setExampleFreeRotatingRadiusParams(tireData.freeRotatingRadiusParams); setExampleVerticalStiffnessParams(tireData.sharedParams.r0, tireData.sharedParams.fz0, tireData.verticalStiffnessParams); setExampleEffectiveRollingRadiusParams(tireData.effectiveRollingRadiusParams); setExampleNormalLoadParams(tireData.normalLoadParams); setExampleLongitudinalForcePureParams(tireData.longitudinalForcePureParams, lengthScale); setExampleLongitudinalForceCombinedParams(tireData.longitudinalForceCombinedParams); setExampleLateralForcePureParams(tireData.lateralForcePureParams, lengthScale); setExampleLateralForceCombinedParams(tireData.lateralForceCombinedParams); setExampleAligningTorquePurePneumaticTrailParams(tireData.aligningTorquePurePneumaticTrailParams); setExampleAligningTorquePureResidualTorqueParams(tireData.aligningTorquePureResidualTorqueParams); setExampleAligningTorqueCombinedParams(tireData.aligningTorqueCombinedParams); if (computeAligningMoment) tireData.flags |= MFTireDataFlag::eALIGNING_MOMENT; else tireData.flags.clear(MFTireDataFlag::eALIGNING_MOMENT); } //Adjust those parameters that describe lateral asymmetry and as such lead more easily to drift. //Can be useful when using the same dataset for all wheels. template<typename TFloat> static void makeTireSymmetric(MFTireDataT<TFloat>& tireData) { tireData.longitudinalForceCombinedParams.rH1 = TFloat(0.0); tireData.lateralForcePureParams.pE3 = TFloat(0.0); tireData.lateralForcePureParams.pH1 = TFloat(0.0); tireData.lateralForcePureParams.pH2 = TFloat(0.0); tireData.lateralForcePureParams.pV1 = TFloat(0.0); tireData.lateralForcePureParams.pV2 = TFloat(0.0); tireData.lateralForceCombinedParams.rB3 = TFloat(0.0); tireData.lateralForceCombinedParams.rV1 = TFloat(0.0); tireData.lateralForceCombinedParams.rV2 = TFloat(0.0); tireData.aligningTorquePureResidualTorqueParams.qD6 = TFloat(0.0); tireData.aligningTorquePureResidualTorqueParams.qD7 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qD3 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qE4 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qH1 = TFloat(0.0); tireData.aligningTorquePurePneumaticTrailParams.qH2 = TFloat(0.0); tireData.aligningTorqueCombinedParams.sS1 = TFloat(0.0); } bool CustomTireVehicle::initialize(PxPhysics& physics, const PxCookingParams& cookingParams, PxMaterial& defaultMaterial, bool addPhysXBeginEndComponents) { typedef MFTireConfig::Float TFloat; if (!DirectDriveVehicle::initialize(physics, cookingParams, defaultMaterial, addPhysXBeginEndComponents)) return false; //Set the custom parameters for the vehicle tires. const PxTolerancesScale& tolerancesScale = physics.getTolerancesScale(); const bool computeAligningMoment = false; //Not used in this snippet const PxU32 tireDataParameterSetCount = sizeof(mCustomTireParams) / sizeof(mCustomTireParams[0]); for (PxU32 i = 0; i < tireDataParameterSetCount; i++) { //Note: in this example, the same parameter values are used for all wheels. CustomTireParams& customTireParams = mCustomTireParams[i]; setExampleTireData<TFloat>(tolerancesScale.length, computeAligningMoment, customTireParams.mfTireData); customTireParams.maxNormalizedLoad = 3.0f; //For the given parameter set, larger loads than this resulted in values //going out of the expected range in the Magic Formula Tire Model makeTireSymmetric(customTireParams.mfTireData); } PX_ASSERT(mBaseParams.axleDescription.getAxle(0) == 0); PX_ASSERT(mBaseParams.axleDescription.getAxle(1) == 0); mTireParamsList[0] = mCustomTireParams + 0; mTireParamsList[1] = mCustomTireParams + 0; PX_ASSERT(mBaseParams.axleDescription.getAxle(2) == 1); PX_ASSERT(mBaseParams.axleDescription.getAxle(3) == 1); mTireParamsList[2] = mCustomTireParams + 1; mTireParamsList[3] = mCustomTireParams + 1; const PxReal chassisMass = 1630.0f; const PxVec3 chassisMoi(2589.9f, 2763.1f, 607.0f); const PxReal massScale = chassisMass / mBaseParams.rigidBodyParams.mass; //Adjust some non custom parameters to match more closely with the wheel the custom tire model //parameters were taken from. const PxU32 wheelCount = mBaseParams.axleDescription.getNbWheels(); for (PxU32 i = 0; i < wheelCount; i++) { PxVehicleWheelParams& wp = mBaseParams.wheelParams[i]; wp.radius = PxReal(mTireParamsList[i]->mfTireData.sharedParams.r0); wp.halfWidth = 0.5f * 0.205f; wp.mass = 9.3f + 7.247f; wp.moi = 0.736f + 0.5698f; //Map the sprung masses etc. to the new total mass PxVehicleSuspensionForceParams& sfp = mBaseParams.suspensionForceParams[i]; sfp.sprungMass *= massScale; sfp.stiffness *= massScale; //Adjust damping to a range that is not ultra extreme const PxReal dampingRatio = 0.3f; sfp.damping = dampingRatio * 2.0f * PxSqrt(sfp.sprungMass * sfp.stiffness); } mBaseParams.rigidBodyParams.mass = chassisMass; mBaseParams.rigidBodyParams.moi = chassisMoi; //Adjust some non custom parameters given that the model should be higher fidelity. mBaseParams.suspensionStateCalculationParams.limitSuspensionExpansionVelocity = true; mBaseParams.suspensionStateCalculationParams.suspensionJounceCalculationType = PxVehicleSuspensionJounceCalculationType::eSWEEP; mPhysXParams.physxRoadGeometryQueryParams.roadGeometryQueryType = PxVehiclePhysXRoadGeometryQueryType::eSWEEP; //Recreate PhysX actor and shapes since related properties changed mPhysXState.destroy(); mPhysXState.create(mBaseParams, mPhysXParams, physics, cookingParams, defaultMaterial); return true; } void CustomTireVehicle::destroy() { DirectDriveVehicle::destroy(); } void CustomTireVehicle::initComponentSequence(const bool addPhysXBeginEndComponents) { //Wake up the associated PxRigidBody if it is asleep and the vehicle commands signal an //intent to change state. //Read from the physx actor and write the state (position, velocity etc) to the vehicle. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorBeginComponent*>(this)); //Read the input commands (throttle, brake etc) and forward them as torques and angles to the wheels on each axle. mComponentSequence.add(static_cast<PxVehicleDirectDriveCommandResponseComponent*>(this)); //Work out which wheels have a non-zero drive torque and non-zero brake torque. //This is used to determine if any tire is to enter the "sticky" regime that will bring the //vehicle to rest. mComponentSequence.add(static_cast<PxVehicleDirectDriveActuationStateComponent*>(this)); //Start a substep group that can be ticked multiple times per update. //In this example, we perform multiple updates of the road geometry queries, suspensions, //tires and wheels. Some tire models might need small time steps to be stable and running //the road geometry queries every substep can reduce large discontinuities (for example //having the wheel go from one frame with no ground contact to a highly compressed suspension //in the next frame). Running substeps on a subset of the operations is computationally //cheaper than simulating the entire sequence. mComponentSequenceSubstepGroupHandle = mComponentSequence.beginSubstepGroup(16); //16 to get more or less a 1kHz update frequence, assuming main update is 60Hz //Perform a scene query against the physx scene to determine the plane and friction under each wheel. mComponentSequence.add(static_cast<PxVehiclePhysXRoadGeometrySceneQueryComponent*>(this)); //Update the suspension compression given the plane under each wheel. //Update the kinematic compliance from the compression state of each suspension. //Convert suspension state to suspension force and torque. mComponentSequence.add(static_cast<PxVehicleSuspensionComponent*>(this)); //Compute the load on the tire, the friction experienced by the tire //and the lateral/longitudinal slip angles. //Convert load/friction/slip to tire force and torque. //If the vehicle is to come rest then compute the "sticky" velocity constraints to apply to the //vehicle. mComponentSequence.add(static_cast<CustomTireComponent*>(this)); //Apply any velocity constraints to a data buffer that will be consumed by the physx scene //during the next physx scene update. mComponentSequence.add(static_cast<PxVehiclePhysXConstraintComponent*>(this)); //Apply the tire force, brake force and drive force to each wheel and //forward integrate the rotation speed of each wheel. mComponentSequence.add(static_cast<PxVehicleDirectDrivetrainComponent*>(this)); //Apply the suspension and tire forces to the vehicle's rigid body and forward //integrate the state of the rigid body. mComponentSequence.add(static_cast<PxVehicleRigidBodyComponent*>(this)); //Mark the end of the substep group. mComponentSequence.endSubstepGroup(); //Update the rotation angle of the wheel by forwarding integrating the rotational //speed of each wheel. //Compute the local pose of the wheel in the rigid body frame after accounting //suspension compression and compliance. mComponentSequence.add(static_cast<PxVehicleWheelComponent*>(this)); //Write the local poses of each wheel to the corresponding shapes on the physx actor. //Write the momentum change applied to the vehicle's rigid body to the physx actor. //The physx scene can now try to apply that change to the physx actor. //The physx scene will account for collisions and constraints to be applied to the vehicle //that occur by applying the change. if(addPhysXBeginEndComponents) mComponentSequence.add(static_cast<PxVehiclePhysXActorEndComponent*>(this)); } }//namespace snippetvehicle2
23,707
C++
44.945736
161
0.797149
NVIDIA-Omniverse/PhysX/physx/snippets/snippetvehicle2customtire/CustomTire.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "CustomTire.h" #include "VehicleMFTire.h" namespace snippetvehicle2 { void CustomTireGripUpdate( bool isWheelOnGround, PxF32 unfilteredLoad, PxF32 restLoad, PxF32 maxNormalizedLoad, PxF32 friction, PxVehicleTireGripState& trGripState) { trGripState.setToDefault(); //If the wheel is not touching the ground then carry on with zero grip state. if (!isWheelOnGround) return; //Note: in a future release the tire load might be recomputed here using // mfTireComputeLoad(). The missing piece is the tire normal deflection // value (difference between free rolling radius and loaded radius). // With a two degree of freedom quarter car model, this value could // be estimated using the compression length of the tire spring. //Compute load and friction. const PxF32 normalizedLoad = unfilteredLoad / restLoad; if (normalizedLoad < maxNormalizedLoad) trGripState.load = unfilteredLoad; else trGripState.load = maxNormalizedLoad * restLoad; trGripState.friction = friction; } void CustomTireSlipsUpdate( const MFTireData& tireData, const PxVehicleTireSpeedState& tireSpeedState, PxF32 wheelOmega, PxF32 tireLoad, PxVehicleTireSlipState& tireSlipState, PxF32& effectiveRollingRadius) { typedef MFTireConfig::Float TFloat; TFloat longSlipTmp, tanLatSlipTmp, effectiveRollingRadiusTmp; mfTireComputeSlip<MFTireConfig>(tireData, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL], tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL], wheelOmega, tireLoad, tireData.sharedParams.pi0, longSlipTmp, tanLatSlipTmp, effectiveRollingRadiusTmp); tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL] = PxReal(longSlipTmp); tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL] = PxReal(MF_ARCTAN(-tanLatSlipTmp)); // note: implementation of Magic Formula Tire Model has lateral axis flipped. // Furthermore, to be consistent with the default PhysX states, the angle is returned. effectiveRollingRadius = PxF32(effectiveRollingRadiusTmp); } void CustomTireForcesUpdate( const MFTireData& tireData, const PxVehicleTireSlipState& tireSlipState, const PxVehicleTireSpeedState& tireSpeedState, const PxVehicleTireDirectionState& tireDirectionState, const PxVehicleTireGripState& tireGripState, const PxVehicleTireStickyState& tireStickyState, const PxTransform& bodyPose, const PxTransform& suspensionAttachmentPose, const PxVec3& tireForceApplicationPoint, PxF32 camber, PxF32 effectiveRollingRadius, PxVehicleTireForce& tireForce) { typedef MFTireConfig::Float TFloat; PxF32 wheelTorque; PxF32 tireLongForce; PxF32 tireLatForce; PxF32 tireAlignMoment; if ((tireGripState.friction > 0.0f) && (tireGripState.load > 0.0f)) { // note: implementation of Magic Formula Tire Model has lateral axis flipped. Furthermore, it expects the // tangens of the angle. const TFloat tanLatSlipNeg = PxTan(-tireSlipState.slips[PxVehicleTireDirectionModes::eLATERAL]); TFloat wheelTorqueTmp, tireLongForceTmp, tireLatForceTmp, tireAlignMomentTmp; mfTireComputeForce<MFTireConfig>(tireData, tireGripState.friction, tireSlipState.slips[PxVehicleTireDirectionModes::eLONGITUDINAL], tanLatSlipNeg, camber, effectiveRollingRadius, tireGripState.load, tireData.sharedParams.pi0, tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLONGITUDINAL], tireSpeedState.speedStates[PxVehicleTireDirectionModes::eLATERAL], wheelTorqueTmp, tireLongForceTmp, tireLatForceTmp, tireAlignMomentTmp); wheelTorque = PxF32(wheelTorqueTmp); tireLongForce = PxF32(tireLongForceTmp); tireLatForce = PxF32(tireLatForceTmp); tireAlignMoment = PxF32(tireAlignMomentTmp); // In the Magic Formula Tire Model, having 0 longitudinal slip does not necessarily mean that // the longitudinal force will be 0 too. The graph used to compute the force allows for vertical // and horizontal shift to model certain effects. Similarly, the lateral force will not necessarily // be 0 just because lateral slip and camber are 0. If the 0 => 0 behavior is desired, then the // parameters need to be set accordingly (see the parameters related to the Sh, Sv parts of the // Magic Formula. The user scaling factors lambdaH and lambdaV can be set to 0, for example, to // eliminate the effect of the parameters that shift the graphs). // // For parameter configurations where 0 slip does not result in 0 force, vehicles might never come // fully to rest. The PhysX default tire model has the sticky tire concept that drives the velocity // towards 0 once velocities stay below a threshold for a defined amount of time. This might not // be enough to cancel the constantly applied force at 0 slip or the sticky tire damping coefficient // needs to be very high. Thus, the following code is added to set the forces to 0 when the tire // fulfills the "stickiness" condition and overrules the results from the Magic Formula Tire Model. const bool clearLngForce = tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLONGITUDINAL]; const bool clearLatForce = tireStickyState.activeStatus[PxVehicleTireDirectionModes::eLATERAL]; if (clearLngForce) { wheelTorque = 0.0f; tireLongForce = 0.0f; } if (clearLatForce) // note: small camber angle could also be seen as requirement but the sticky tire active state is seen as reference here { tireLatForce = 0.0f; } if (clearLngForce && clearLatForce) { tireAlignMoment = 0.0f; } } else { wheelTorque = 0.0f; tireLongForce = 0.0f; tireLatForce = 0.0f; tireAlignMoment = 0.0f; } const PxVec3 tireLongForceVec = tireDirectionState.directions[PxVehicleTireDirectionModes::eLONGITUDINAL] * tireLongForce; const PxVec3 tireLatForceVec = tireDirectionState.directions[PxVehicleTireDirectionModes::eLATERAL] * tireLatForce; tireForce.forces[PxVehicleTireDirectionModes::eLONGITUDINAL] = tireLongForceVec; tireForce.forces[PxVehicleTireDirectionModes::eLATERAL] = tireLatForceVec; const PxVec3 r = bodyPose.rotate(suspensionAttachmentPose.transform(tireForceApplicationPoint)); tireForce.torques[PxVehicleTireDirectionModes::eLONGITUDINAL] = r.cross(tireLongForceVec); tireForce.torques[PxVehicleTireDirectionModes::eLATERAL] = r.cross(tireLatForceVec); tireForce.aligningMoment = tireAlignMoment; tireForce.wheelTorque = wheelTorque; } }//namespace snippetvehicle2
8,116
C++
42.406417
142
0.786594
NVIDIA-Omniverse/PhysX/physx/snippets/snippetquerysystemallqueries/SnippetQuerySystemAllQueries.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates all queries supported by the low-level query system. // Please get yourself familiar with SnippetStandaloneQuerySystem first. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "GuQuerySystem.h" #include "GuFactory.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace Gu; #ifdef RENDER_SNIPPET using namespace Snippets; #endif static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxConvexMesh* gConvexMesh = NULL; static PxTriangleMesh* gTriangleMesh = NULL; static const bool gManualBoundsComputation = false; static const bool gUseDelayedUpdates = true; static const float gBoundsInflation = 0.001f; static bool gPause = false; static bool gOneFrame = false; enum QueryScenario { RAYCAST_CLOSEST, RAYCAST_ANY, RAYCAST_MULTIPLE, SWEEP_CLOSEST, SWEEP_ANY, SWEEP_MULTIPLE, OVERLAP_ANY, OVERLAP_MULTIPLE, NB_SCENES }; static QueryScenario gSceneIndex = RAYCAST_CLOSEST; // Tweak number of created objects per scene static const PxU32 gFactor[NB_SCENES] = { 2, 1, 2, 2, 1, 2, 1, 2 }; // Tweak amplitude of created objects per scene static const float gAmplitude[NB_SCENES] = { 4.0f, 4.0f, 4.0f, 4.0f, 8.0f, 4.0f, 4.0f, 4.0f }; static const PxVec3 gCamPos[NB_SCENES] = { PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-3.404853f, 4.865191f, 17.692263f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), PxVec3(-2.199769f, 3.448516f, 10.943871f), }; static const PxVec3 gCamDir[NB_SCENES] = { PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), PxVec3(0.172155f, -0.202382f, -0.964056f), }; #define MAX_NB_OBJECTS 32 /////////////////////////////////////////////////////////////////////////////// // The following functions determine how we use the pruner payloads in this snippet static PX_FORCE_INLINE void setupPayload(PrunerPayload& payload, PxU32 objectIndex, const PxGeometryHolder* gh) { payload.data[0] = objectIndex; payload.data[1] = size_t(gh); } static PX_FORCE_INLINE PxU32 getObjectIndexFromPayload(const PrunerPayload& payload) { return PxU32(payload.data[0]); } static PX_FORCE_INLINE const PxGeometry& getGeometryFromPayload(const PrunerPayload& payload) { const PxGeometryHolder* gh = reinterpret_cast<const PxGeometryHolder*>(payload.data[1]); return gh->any(); } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomRaycastHit : PxGeomRaycastHit { PxU32 mObjectIndex; }; struct CustomSweepHit : PxGeomSweepHit { PxU32 mObjectIndex; }; class CustomScene : public Adapter { public: CustomScene(); ~CustomScene() {} // Adapter virtual const PxGeometry& getGeometry(const PrunerPayload& payload) const; //~Adapter void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose, bool isDynamic); void render(); void updateObjects(); void runQueries(); bool raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const; bool raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const; bool raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const; bool sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const; bool sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const; bool sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const; bool overlapAny(const PxGeometry& geom, const PxTransform& pose) const; bool overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const; struct Object { PxGeometryHolder mGeom; ActorShapeData mData; PxVec3 mTouchedColor; bool mTouched; }; PxU32 mNbObjects; Object mObjects[MAX_NB_OBJECTS]; QuerySystem* mQuerySystem; PxU32 mPrunerIndex; }; const PxGeometry& CustomScene::getGeometry(const PrunerPayload& payload) const { PX_ASSERT(!gManualBoundsComputation); return getGeometryFromPayload(payload); } void CustomScene::release() { PX_DELETE(mQuerySystem); PX_DELETE_THIS; } CustomScene::CustomScene() : mNbObjects(0) { const PxU64 contextID = PxU64(this); mQuerySystem = PX_NEW(QuerySystem)(contextID, gBoundsInflation, *this); Pruner* pruner = createAABBPruner(contextID, true, COMPANION_PRUNER_INCREMENTAL, BVH_SPLATTER_POINTS, 4); mPrunerIndex = mQuerySystem->addPruner(pruner, 0); const PxU32 nb = gFactor[gSceneIndex]; for(PxU32 i=0;i<nb;i++) { addGeom(PxBoxGeometry(PxVec3(1.0f, 2.0f, 0.5f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f)), true); addGeom(PxSphereGeometry(1.5f), PxTransform(PxVec3(4.0f, 0.0f, 0.0f)), true); addGeom(PxCapsuleGeometry(1.0f, 1.0f), PxTransform(PxVec3(-4.0f, 0.0f, 0.0f)), true); addGeom(PxConvexMeshGeometry(gConvexMesh), PxTransform(PxVec3(0.0f, 0.0f, 4.0f)), true); addGeom(PxTriangleMeshGeometry(gTriangleMesh), PxTransform(PxVec3(0.0f, 0.0f, -4.0f)), true); } #ifdef RENDER_SNIPPET Camera* camera = getCamera(); camera->setPose(gCamPos[gSceneIndex], gCamDir[gSceneIndex]); #endif } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose, bool isDynamic) { PX_ASSERT(mQuerySystem); Object& obj = mObjects[mNbObjects]; obj.mGeom.storeAny(geom); PrunerPayload payload; setupPayload(payload, mNbObjects, &obj.mGeom); if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, geom, pose, 0.0f, 1.0f + gBoundsInflation); obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, &bounds); } else { obj.mData = mQuerySystem->addPrunerShape(payload, mPrunerIndex, isDynamic, pose, NULL); } mNbObjects++; } void CustomScene::updateObjects() { if(!mQuerySystem) return; if(gPause && !gOneFrame) { mQuerySystem->update(true, true); return; } gOneFrame = false; static float time = 0.0f; time += 0.005f; const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; if(!getDynamic(getPrunerInfo(obj.mData))) continue; // const float coeff = float(i)/float(nbObjects); const float coeff = float(i); const float amplitude = gAmplitude[gSceneIndex]; // Compute an arbitrary new pose for this object PxTransform pose; { const float phase = PxPi * 2.0f * float(i)/float(nbObjects); pose.p.z = 0.0f; pose.p.y = sinf(phase+time*1.17f)*amplitude; pose.p.x = cosf(phase+time*1.17f)*amplitude; PxMat33 rotX; PxSetRotX(rotX, time+coeff); PxMat33 rotY; PxSetRotY(rotY, time*1.17f+coeff); PxMat33 rotZ; PxSetRotZ(rotZ, time*0.33f+coeff); PxMat33 rot = rotX * rotY * rotZ; pose.q = PxQuat(rot); pose.q.normalize(); } if(gManualBoundsComputation) { PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj.mGeom.any(), pose, 0.0f, 1.0f + gBoundsInflation); mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, &bounds); } else { mQuerySystem->updatePrunerShape(obj.mData, !gUseDelayedUpdates, pose, NULL); } } mQuerySystem->update(true, true); } namespace { struct CustomPrunerFilterCallback : public PrunerFilterCallback { virtual const PxGeometry* validatePayload(const PrunerPayload& payload, PxHitFlags& /*hitFlags*/) { return &getGeometryFromPayload(payload); } }; } static CustomPrunerFilterCallback gFilterCallback; static CachedFuncs gCachedFuncs; /////////////////////////////////////////////////////////////////////////////// // Custom queries. It is not mandatory to use e.g. different raycast queries for different usages - one could just use the same code // for everything. But it is -possible- to do so, the system is flexible enough to let users decide what to do. // Common raycast usage, returns the closest touched object (single hit). bool CustomScene::raycastClosest(const PxVec3& origin, const PxVec3& unitDir, float maxDist, CustomRaycastHit& hit) const { DefaultPrunerRaycastClosestCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist, PxHitFlag::eDEFAULT); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); if(CB.mFoundHit) { static_cast<PxGeomRaycastHit&>(hit) = CB.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(CB.mClosestPayload); } return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// // "Shadow feeler" usage, returns boolean result, early exits as soon as an impact is found. bool CustomScene::raycastAny(const PxVec3& origin, const PxVec3& unitDir, float maxDist) const { DefaultPrunerRaycastAnyCallback CB(gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return CB.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { // Beware, there is something a bit subtle here. The query can return multiple hits per query and/or // multiple hits per object. For example a raycast against a scene can touch multiple simple objects, // like e.g. multiple spheres, and return the set of touched spheres to users. But a single raycast // against a complex object like a mesh can also return multiple hits, against multiple triangles of // that same mesh. There are use cases for all of these, and it is up to users to decide what they // need. In this example we do "multiple hits per query", but a single hit per mesh. That is, we do // not use PxHitFlag::eMESH_MULTIPLE. That is why our CustomRaycastCallback only has a single // PxGeomRaycastHit member (mLocalHit). struct CustomRaycastMultipleCallback : public DefaultPrunerRaycastCallback { // This mandatory local hit structure is where DefaultPrunerRaycastCallback writes its // temporary hit when traversing the pruners. PxGeomRaycastHit mLocalHit; // This is the user-provided array where we'll write our results. PxArray<CustomRaycastHit>& mHits; CustomRaycastMultipleCallback(PxArray<CustomRaycastHit>& hits, PrunerFilterCallback& filterCB, const GeomRaycastTable& funcs, const PxVec3& origin, const PxVec3& dir, float distance) : DefaultPrunerRaycastCallback(filterCB, funcs, origin, dir, distance, 1, &mLocalHit, PxHitFlag::eDEFAULT, false), mHits (hits) {} // So far this looked similar to the DefaultPrunerRaycastClosestCallback code. But we customize the behavior in // the following function. virtual bool reportHits(const PrunerPayload& payload, PxU32 nbHits, PxGeomRaycastHit* hits) { // Because we didn't use PxHitFlag::eMESH_MULTIPLE we should only be called for a single hit PX_ASSERT(nbHits==1); PX_UNUSED(nbHits); // We process each hit the way we processed the closest hit at the end of CustomScene::raycastClosest CustomRaycastHit customHit; static_cast<PxGeomRaycastHit&>(customHit) = hits[0]; customHit.mObjectIndex = getObjectIndexFromPayload(payload); // Then we gather the new hit in our user-provided array. This is written for clarity, not performance. // Here we could instead call a user-provided callback. mHits.pushBack(customHit); // We return false to tell the system to ignore that hit now (otherwise the code would shrink the ray etc). // This is also the way one does "post filtering". return false; } PX_NOCOPY(CustomRaycastMultipleCallback) }; } // Generic usage, returns all hits touched by the ray, it's up to users to process them / sort them / etc. // We're using a PxArray here but it's an arbitrary choice, one could also return hits via a callback, etc. bool CustomScene::raycastMultiple(const PxVec3& origin, const PxVec3& unitDir, float maxDist, PxArray<CustomRaycastHit>& hits) const { CustomRaycastMultipleCallback CB(hits, gFilterCallback, gCachedFuncs.mCachedRaycastFuncs, origin, unitDir, maxDist); mQuerySystem->raycast(origin, unitDir, maxDist, CB, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// namespace { // The sweep code is more complicated because the swept geometry is arbitrary (to some extent), and for performance reason there is no // generic sweep callback available operating on an anonymous PxGeometry. So the code below is what you can do instead. // It can be simplified in your app though if you know you only need to sweep one kind of geometry (say sphere sweeps). template<class CallbackT> static bool _sweepClosestT(CustomSweepHit& hit, const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eDEFAULT | PxHitFlag::ePRECISE_SWEEP, false); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); if(pcb.mFoundHit) { static_cast<PxGeomSweepHit&>(hit) = pcb.mClosestHit; hit.mObjectIndex = getObjectIndexFromPayload(pcb.mClosestPayload); } return pcb.mFoundHit; } } // Common sweep usage, returns the closest touched object (single hit). bool CustomScene::sweepClosest(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, CustomSweepHit& hit) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepClosestT<DefaultPrunerSphereSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepClosestT<DefaultPrunerCapsuleSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepClosestT<DefaultPrunerBoxSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepClosestT<DefaultPrunerConvexSweepCallback>(hit, *mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { // This could easily be combined with _sweepClosestT to make the code shorter. template<class CallbackT> static bool _sweepAnyT(const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CallbackT pcb(gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist, PxHitFlag::eMESH_ANY | PxHitFlag::ePRECISE_SWEEP, true); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return pcb.mFoundHit; } } // Returns boolean result, early exits as soon as an impact is found. bool CustomScene::sweepAny(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepAnyT<DefaultPrunerSphereSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepAnyT<DefaultPrunerCapsuleSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepAnyT<DefaultPrunerBoxSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepAnyT<DefaultPrunerConvexSweepCallback>(*mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { // We use a similar strategy as for raycasts. Please refer to CustomRaycastMultipleCallback above. template<class BaseCallbackT> struct CustomSweepMultipleCallback : public BaseCallbackT { PxArray<CustomSweepHit>& mHits; CustomSweepMultipleCallback(PxArray<CustomSweepHit>& hits, PrunerFilterCallback& filterCB, const GeomSweepFuncs& funcs, const PxGeometry& geom, const PxTransform& pose, const ShapeData& queryVolume, const PxVec3& dir, float distance) : BaseCallbackT (filterCB, funcs, geom, pose, queryVolume, dir, distance, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, false), mHits (hits) {} virtual bool reportHit(const PrunerPayload& payload, PxGeomSweepHit& hit) { CustomSweepHit customHit; static_cast<PxGeomSweepHit&>(customHit) = hit; customHit.mObjectIndex = getObjectIndexFromPayload(payload); mHits.pushBack(customHit); return false; } PX_NOCOPY(CustomSweepMultipleCallback) }; // Previous template was customizing the callback for multiple hits, this template customizes the previous template for different geoms. template<class CallbackT> static bool _sweepMultipleT(PxArray<CustomSweepHit>& hits, const QuerySystem& sqs, const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist) { const ShapeData queryVolume(geom, pose, 0.0f); CustomSweepMultipleCallback<CallbackT> pcb(hits, gFilterCallback, gCachedFuncs.mCachedSweepFuncs, geom, pose, queryVolume, unitDir, maxDist); sqs.sweep(queryVolume, unitDir, pcb.mClosestHit.distance, pcb, NULL); return hits.size()!=0; } } // Generic usage, returns all hits touched by the swept volume, it's up to users to process them / sort them / etc. // We're using a PxArray here but it's an arbitrary choice, one could also return hits via a callback, etc. bool CustomScene::sweepMultiple(const PxGeometry& geom, const PxTransform& pose, const PxVec3& unitDir, float maxDist, PxArray<CustomSweepHit>& hits) const { switch(PxU32(geom.getType())) { case PxGeometryType::eSPHERE: { return _sweepMultipleT<DefaultPrunerSphereSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCAPSULE: { return _sweepMultipleT<DefaultPrunerCapsuleSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eBOX: { return _sweepMultipleT<DefaultPrunerBoxSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } case PxGeometryType::eCONVEXMESH: { return _sweepMultipleT<DefaultPrunerConvexSweepCallback>(hits, *mQuerySystem, geom, pose, unitDir, maxDist); } default: { PX_ASSERT(0); return false; } } } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapAnyCallback : public DefaultPrunerOverlapCallback { bool mFoundHit; CustomOverlapAnyCallback(PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mFoundHit(false) {} virtual bool reportHit(const PrunerPayload& /*payload*/) { mFoundHit = true; return false; // Early exits as soon as we hit something } }; } // Simple boolean overlap. The query returns true if the passed shape touches anything, otherwise it returns false if space was free. bool CustomScene::overlapAny(const PxGeometry& geom, const PxTransform& pose) const { CustomOverlapAnyCallback pcb(gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return pcb.mFoundHit; } /////////////////////////////////////////////////////////////////////////////// namespace { struct CustomOverlapMultipleCallback : public DefaultPrunerOverlapCallback { PxArray<PxU32>& mHits; CustomOverlapMultipleCallback(PxArray<PxU32>& hits, PrunerFilterCallback& filterCB, const GeomOverlapTable* funcs, const PxGeometry& geometry, const PxTransform& pose) : DefaultPrunerOverlapCallback(filterCB, funcs, geometry, pose), mHits(hits) {} virtual bool reportHit(const PrunerPayload& payload) { // In this example we only return touched objects but we don't go deeper. For triangle meshes we could // here go to the triangle-level and return all touched triangles of a mesh, if needed. To do that we'd // fetch the PxTriangleMeshGeometry from the payload and use PxMeshQuery::findOverlapTriangleMesh. That // call is part of the regular PxMeshQuery API though so it's beyond the scope of this snippet, which is // about the Gu-level query system. Instead here we just retrieve & output the touched object's index: mHits.pushBack(getObjectIndexFromPayload(payload)); return true; // Continue query, call us again for next touched object } PX_NOCOPY(CustomOverlapMultipleCallback) }; } // Gather-touched-objects overlap. The query returns all objects touched by query volume, in an array. // This is an arbitrary choice in this snippet, it would be equally easy to report each object individually // to a user-callback, etc. bool CustomScene::overlapMultiple(const PxGeometry& geom, const PxTransform& pose, PxArray<PxU32>& hits) const { CustomOverlapMultipleCallback pcb(hits, gFilterCallback, gCachedFuncs.mCachedOverlapFuncs, geom, pose); const ShapeData queryVolume(geom, pose, 0.0f); mQuerySystem->overlap(queryVolume, pcb, NULL); return hits.size()!=0; } /////////////////////////////////////////////////////////////////////////////// void CustomScene::runQueries() { if(!mQuerySystem) return; // Reset all touched flags & colors const PxVec3 touchedColor(0.25f, 0.5f, 1.0f); for(PxU32 i=0;i<mNbObjects;i++) { mObjects[i].mTouched = false; mObjects[i].mTouchedColor = touchedColor; } // This is optional, the SIMD guard can be ommited if your app already // setups the FPU/SIMD control word per thread. If not, try to use one // PX_SIMD_GUARD for many queries, rather than one for each query. PX_SIMD_GUARD if(0) mQuerySystem->commitUpdates(); switch(gSceneIndex) { case RAYCAST_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; CustomRaycastHit hit; const bool hasHit = raycastClosest(origin, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, hit.position, PxVec3(1.0f)); DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const bool hasHit = raycastAny(origin, unitDir, maxDist); #ifdef RENDER_SNIPPET if(hasHit) DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f, 0.0f, 0.0f)); else DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.0f, 1.0f, 0.0f)); #else PX_UNUSED(hasHit); #endif } break; case RAYCAST_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; PxArray<CustomRaycastHit> hits; const bool hasHit = raycastMultiple(origin, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET if(hasHit) { DrawLine(origin, origin + unitDir * maxDist, PxVec3(0.5f)); const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const CustomRaycastHit& hit = hits[i]; DrawLine(hit.position, hit.position + hit.normal, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 0.5f); mObjects[hit.mObjectIndex].mTouched = true; } } else { DrawLine(origin, origin + unitDir * maxDist, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_CLOSEST: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxSphereGeometry sweptGeom(0.5f); //const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); CustomSweepHit hit; const bool hasHit = sweepClosest(sweptGeom, pose, unitDir, maxDist, hit); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); if(hasHit) { const PxVec3 sweptPos = origin + unitDir * hit.distance; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(1.0f, 0.0f, 0.0f)); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, PxVec3(0.0f, 1.0f, 0.0f)); } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_ANY: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxBoxGeometry sweptGeom(PxVec3(0.5f)); PxQuat q(1.1f, 0.1f, 0.8f, 1.4f); q.normalize(); const PxTransform pose(origin, q); const bool hasHit = sweepAny(sweptGeom, pose, unitDir, maxDist); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); { // We only have a boolean result so we're just going to draw a sequence of geoms along // the sweep direction in the appropriate color. const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); const PxU32 nb = 20; for(PxU32 i=0;i<nb;i++) { const float coeff = float(i)/float(nb-1); const PxVec3 sweptPos = origin + unitDir * coeff * maxDist; const PxTransform impactPose(sweptPos, q); renderGeoms(1, &gh, &impactPose, false, color); } } #else PX_UNUSED(hasHit); #endif } break; case SWEEP_MULTIPLE: { const PxVec3 origin(0.0f, 10.0f, 0.0f); const PxVec3 unitDir(0.0f, -1.0f, 0.0f); const float maxDist = 20.0f; const PxCapsuleGeometry sweptGeom(0.5f, 0.5f); const PxTransform pose(origin); PxArray<CustomSweepHit> hits; const bool hasHit = sweepMultiple(sweptGeom, pose, unitDir, maxDist, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(sweptGeom); renderGeoms(1, &gh, &pose, false, PxVec3(0.0f, 1.0f, 0.0f)); if(hasHit) { { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(0.5f)); } // It can be difficult to see what is touching what so we use different colors to make it clearer. const PxVec3 touchedColors[] = { PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f), PxVec3(1.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 1.0f), PxVec3(1.0f, 1.0f, 0.0f), PxVec3(1.0f, 1.0f, 1.0f), PxVec3(0.5f, 0.5f, 0.5f), }; const PxU32 nbHits = hits.size(); for(PxU32 i=0;i<nbHits;i++) { const PxVec3& shapeTouchedColor = touchedColors[i]; const CustomSweepHit& hit = hits[i]; const PxVec3 sweptPos = origin + unitDir * hit.distance; const PxTransform impactPose(sweptPos); renderGeoms(1, &gh, &impactPose, false, shapeTouchedColor); DrawLine(hit.position, hit.position + hit.normal*2.0f, PxVec3(1.0f, 1.0f, 0.0f)); DrawFrame(hit.position, 2.0f); mObjects[hit.mObjectIndex].mTouched = true; mObjects[hit.mObjectIndex].mTouchedColor = shapeTouchedColor; } } else { const PxVec3 sweptPos = origin + unitDir * maxDist; DrawLine(origin, sweptPos, PxVec3(1.0f)); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_ANY: { const PxVec3 origin(0.0f, 4.0f, 0.0f); const PxSphereGeometry queryGeom(0.5f); const PxTransform pose(origin); const bool hasHit = overlapAny(queryGeom, pose); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); } #else PX_UNUSED(hasHit); #endif } break; case OVERLAP_MULTIPLE: { const PxVec3 origin(0.0f, 4.0f, 0.0f); const PxSphereGeometry queryGeom(0.5f); const PxTransform pose(origin); PxArray<PxU32> hits; const bool hasHit = overlapMultiple(queryGeom, pose, hits); #ifdef RENDER_SNIPPET const PxGeometryHolder gh(queryGeom); { const PxVec3 color = hasHit ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); renderGeoms(1, &gh, &pose, false, color); for(PxU32 i=0;i<hits.size();i++) mObjects[hits[i]].mTouched = true; } #else PX_UNUSED(hasHit); #endif } break; case NB_SCENES: // Blame pedantic compilers { } break; } } void CustomScene::render() { updateObjects(); runQueries(); #ifdef RENDER_SNIPPET const PxVec3 color(1.0f, 0.5f, 0.25f); const PxU32 nbObjects = mNbObjects; for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; PrunerPayloadData ppd; mQuerySystem->getPayloadData(obj.mData, &ppd); //DrawBounds(*bounds); const PxVec3& objectColor = obj.mTouched ? obj.mTouchedColor : color; renderGeoms(1, &obj.mGeom, ppd.mTransform, false, objectColor); } //mQuerySystem->visualize(true, true, PxRenderOutput) #endif } } static CustomScene* gScene = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); const PxTolerancesScale scale; PxCookingParams params(scale); params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); // params.midphaseDesc.mBVH34Desc.quantized = false; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_ACTIVE_EDGES_PRECOMPUTE; params.meshPreprocessParams |= PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; { { const PxF32 width = 3.0f; const PxF32 radius = 1.0f; PxVec3 points[2*16]; for(PxU32 i = 0; i < 16; i++) { const PxF32 cosTheta = PxCos(i*PxPi*2.0f/16.0f); const PxF32 sinTheta = PxSin(i*PxPi*2.0f/16.0f); const PxF32 y = radius*cosTheta; const PxF32 z = radius*sinTheta; points[2*i+0] = PxVec3(-width/2.0f, y, z); points[2*i+1] = PxVec3(+width/2.0f, y, z); } PxConvexMeshDesc convexDesc; convexDesc.points.count = 32; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = points; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; gConvexMesh = PxCreateConvexMesh(params, convexDesc); } { PxTriangleMeshDesc meshDesc; meshDesc.points.count = SnippetUtils::Bunny_getNbVerts(); meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = SnippetUtils::Bunny_getVerts(); meshDesc.triangles.count = SnippetUtils::Bunny_getNbFaces(); meshDesc.triangles.stride = sizeof(int)*3; meshDesc.triangles.data = SnippetUtils::Bunny_getFaces(); gTriangleMesh = PxCreateTriangleMesh(params, meshDesc); } } gScene = new CustomScene; } void renderScene() { if(gScene) gScene->render(); #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F8 to select a scenario."); switch(PxU32(gSceneIndex)) { case RAYCAST_CLOSEST: { Snippets::print("Current scenario: raycast closest"); }break; case RAYCAST_ANY: { Snippets::print("Current scenario: raycast any"); }break; case RAYCAST_MULTIPLE: { Snippets::print("Current scenario: raycast multiple"); }break; case SWEEP_CLOSEST: { Snippets::print("Current scenario: sweep closest"); }break; case SWEEP_ANY: { Snippets::print("Current scenario: sweep any"); }break; case SWEEP_MULTIPLE: { Snippets::print("Current scenario: sweep multiple"); }break; case OVERLAP_ANY: { Snippets::print("Current scenario: overlap any"); }break; case OVERLAP_MULTIPLE: { Snippets::print("Current scenario: overlap multiple"); }break; } #endif } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gConvexMesh); PX_RELEASE(gFoundation); printf("SnippetQuerySystemAllQueries done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(gScene) { if(key=='p' || key=='P') { gPause = !gPause; } else if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } else { if(key>=1 && key<=NB_SCENES) { gSceneIndex = QueryScenario(key-1); PX_RELEASE(gScene); gScene = new CustomScene; } } } } int snippetMain(int, const char*const*) { printf("Query System All Queries snippet.\n"); printf("Press F1 to F8 to select a scene:\n"); printf(" F1......raycast closest\n"); printf(" F2..........raycast any\n"); printf(" F3.....raycast multiple\n"); printf(" F4........sweep closest\n"); printf(" F5............sweep any\n"); printf(" F6.......sweep multiple\n"); printf(" F7..........overlap any\n"); printf(" F8.....overlap multiple\n"); printf("\n"); printf("Press P to Pause.\n"); printf("Press O to step the simulation One frame.\n"); printf("Press the cursor keys to move the camera.\n"); printf("Use the mouse/left mouse button to rotate the camera.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
36,068
C++
32.182153
186
0.6999
NVIDIA-Omniverse/PhysX/physx/snippets/snippetfixedtendon/SnippetFixedTendon.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // *************************************************************************************** // This snippet demonstrates the use of a fixed tendon to mirror articulation joint angles // *************************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxArticulationReducedCoordinate* gArticulation = NULL; static PxArticulationJointReducedCoordinate* gDriveJoint = NULL; static const PxReal gGravity = 9.81f; static PxReal gDriveTargetPos = 0.0f; static void createArticulation() { gArticulation->setArticulationFlags(PxArticulationFlag::eFIX_BASE); gArticulation->setSolverIterationCounts(10, 1); // link geometry and density: const PxVec3 halfLengths(0.50f, 0.05f, 0.05f); const PxBoxGeometry linkGeom = PxBoxGeometry(halfLengths); const PxReal density = 1000.0f; //Create links PxTransform pose = PxTransform(PxIdentity); pose.p.y = 3.0f; pose.p.x -= 2.0f * halfLengths.x; PxArticulationLink* parent = NULL; const PxU32 numLinks = 3; for(PxU32 j = 0; j < numLinks; ++j) { pose.p.x += 2.0f * halfLengths.x; parent = gArticulation->createLink(parent, pose); PxRigidActorExt::createExclusiveShape(*parent, linkGeom, *gMaterial); PxRigidBodyExt::updateMassAndInertia(*parent, density); PxArticulationJointReducedCoordinate *joint = static_cast<PxArticulationJointReducedCoordinate*>(parent->getInboundJoint()); if(joint) { PxVec3 parentOffset(halfLengths.x, 0.0f, 0.0f); PxVec3 childOffset(-halfLengths.x, 0.0f, 0.0f); joint->setParentPose(PxTransform(parentOffset, PxQuat(PxIdentity))); joint->setChildPose(PxTransform(childOffset, PxQuat(PxIdentity))); joint->setJointType(PxArticulationJointType::eREVOLUTE); joint->setMotion(PxArticulationAxis::eSWING2, PxArticulationMotion::eFREE); } } // tendon and drive stiffness sizing // assuming all links extend horizontally, size to allow for two degrees // deviation due to gravity const PxReal linkMass = parent->getMass(); const PxReal deflectionAngle = 2.0f * PxPi / 180.0f; // two degrees // moment arm of first link is one half-length, for second it is three half-lengths const PxReal gravityTorque = gGravity * linkMass * (halfLengths.x + 3.0f * halfLengths.x); const PxReal driveStiffness = gravityTorque / deflectionAngle; const PxReal driveDamping = 0.2f * driveStiffness; // same idea for the tendon, but it has to support only a single link const PxReal tendonStiffness = gGravity * linkMass * halfLengths.x / deflectionAngle; const PxReal tendonDamping = 0.2f * tendonStiffness; // compute drive target angle that compensates, statically, for the first fixed tendon joint // torque acting on the drive joint: const PxReal targetAngle = PxPiDivFour; const PxReal tendonTorque = targetAngle * tendonStiffness; gDriveTargetPos = targetAngle + tendonTorque / driveStiffness; // setup fixed tendon PxArticulationLink* links[numLinks]; gArticulation->getLinks(links, numLinks, 0u); PxArticulationFixedTendon* tendon = gArticulation->createFixedTendon(); tendon->setLimitStiffness(0.0f); tendon->setDamping(tendonDamping); tendon->setStiffness(tendonStiffness); tendon->setRestLength(0.f); tendon->setOffset(0.f); PxArticulationTendonJoint* tendonParentJoint = NULL; // root fixed-tendon joint - does not contribute to length so its coefficient and axis are irrelevant // but its parent link experiences all tendon-joint reaction forces tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, 42.0f, 1.f/42.f, links[0]); // drive joint tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, 1.0f, 1.f, links[1]); // second joint that is driven only by the tendon - negative coefficient to mirror angle of drive joint tendonParentJoint = tendon->createTendonJoint(tendonParentJoint, PxArticulationAxis::eSWING2, -1.0f, -1.0f, links[2]); // configure joint drive gDriveJoint = links[1]->getInboundJoint(); PxArticulationDrive driveConfiguration; driveConfiguration.damping = driveDamping; driveConfiguration.stiffness = driveStiffness; driveConfiguration.maxForce = PX_MAX_F32; driveConfiguration.driveType = PxArticulationDriveType::eFORCE; gDriveJoint->setDriveParams(PxArticulationAxis::eSWING2, driveConfiguration); gDriveJoint->setDriveVelocity(PxArticulationAxis::eSWING2, 0.0f); gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, 0.0f); // add articulation to scene: gScene->addArticulation(*gArticulation); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -gGravity, 0.0f); PxU32 numCores = SnippetUtils::getNbPhysicalCores(); gDispatcher = PxDefaultCpuDispatcherCreate(numCores == 0 ? 0 : numCores - 1); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.solverType = PxSolverType::eTGS; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.f); gArticulation = gPhysics->createArticulationReducedCoordinate(); createArticulation(); } void stepPhysics(bool /*interactive*/) { static bool dir = false; static PxReal time = 0.0f; const PxReal switchTime = 3.0f; const PxReal dt = 1.0f / 60.f; time += dt; if(time > switchTime) { if(dir) { gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, 0.0f); } else { gDriveJoint->setDriveTarget(PxArticulationAxis::eSWING2, gDriveTargetPos); } dir = !dir; time = 0.0f; } gScene->simulate(dt); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gArticulation); PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); PxPvdTransport* transport = gPvd->getTransport(); PX_RELEASE(gPvd); PX_RELEASE(transport); PxCloseExtensions(); PX_RELEASE(gFoundation); printf("SnippetFixedTendon done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
8,907
C++
38.591111
126
0.74593
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatearticulation/SnippetImmediateArticulationRender.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifdef RENDER_SNIPPET #include <vector> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "../snippetrender/SnippetRender.h" #include "../snippetrender/SnippetCamera.h" using namespace physx; using namespace immediate; extern void initPhysics(bool interactive); extern void stepPhysics(bool interactive); extern void cleanupPhysics(bool interactive); extern void keyPress(unsigned char key, const PxTransform& camera); extern PxU32 getNbGeoms(); extern const PxGeometryHolder* getGeoms(); extern const PxTransform* getGeomPoses(); extern PxU32 getNbContacts(); extern const PxContactPoint* getContacts(); extern PxU32 getNbArticulations(); extern PxArticulationHandle* getArticulations(); extern PxU32 getNbBounds(); extern const PxBounds3* getBounds(); extern void renderText(); namespace { Snippets::Camera* sCamera; void renderCallback() { stepPhysics(true); /* if(0) { PxVec3 camPos = sCamera->getEye(); PxVec3 camDir = sCamera->getDir(); printf("camPos: (%ff, %ff, %ff)\n", camPos.x, camPos.y, camPos.z); printf("camDir: (%ff, %ff, %ff)\n", camDir.x, camDir.y, camDir.z); }*/ Snippets::startRender(sCamera); const PxVec3 color(0.6f, 0.8f, 1.0f); // const PxVec3 color(0.75f, 0.75f, 1.0f); // const PxVec3 color(1.0f); Snippets::renderGeoms(getNbGeoms(), getGeoms(), getGeomPoses(), true, color); /* PxU32 getNbGeoms(); const PxGeometry* getGeoms(); const PxTransform* getGeomPoses(); Snippets::renderGeoms(getNbGeoms(), getGeoms(), getGeomPoses(), true, PxVec3(1.0f));*/ /* PxBoxGeometry boxGeoms[10]; for(PxU32 i=0;i<10;i++) boxGeoms[i].halfExtents = PxVec3(1.0f); PxTransform poses[10]; for(PxU32 i=0;i<10;i++) { poses[i] = PxTransform(PxIdentity); poses[i].p.y += 1.5f; poses[i].p.x = float(i)*2.5f; } Snippets::renderGeoms(10, boxGeoms, poses, true, PxVec3(1.0f));*/ if(1) { const PxU32 nbContacts = getNbContacts(); const PxContactPoint* contacts = getContacts(); for(PxU32 j=0;j<nbContacts;j++) { Snippets::DrawFrame(contacts[j].point, 1.0f); } } if(0) { const PxU32 nbArticulations = getNbArticulations(); PxArticulationHandle* articulations = getArticulations(); for(PxU32 j=0;j<nbArticulations;j++) { immediate::PxArticulationLinkDerivedDataRC data[64]; const PxU32 nbLinks = immediate::PxGetAllLinkData(articulations[j], data); for(PxU32 i=0;i<nbLinks;i++) { Snippets::DrawFrame(data[i].pose.p, 1.0f); } } } const PxBounds3* bounds = getBounds(); const PxU32 nbBounds = getNbBounds(); for(PxU32 i=0;i<nbBounds;i++) { Snippets::DrawBounds(bounds[i]); } renderText(); Snippets::finishRender(); } void exitCallback(void) { delete sCamera; cleanupPhysics(true); } } void renderLoop() { sCamera = new Snippets::Camera( PxVec3(8.526230f, 5.546278f, 5.448466f), PxVec3(-0.784231f, -0.210605f, -0.583632f)); Snippets::setupDefault("PhysX Snippet Immediate Articulation", sCamera, keyPress, renderCallback, exitCallback); initPhysics(true); glutMainLoop(); } #endif
4,717
C++
29.24359
113
0.728641
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatearticulation/SnippetImmediateArticulation.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet demonstrates the use of immediate articulations. // **************************************************************************** #include "PxImmediateMode.h" #include "PxMaterial.h" #include "geometry/PxGeometryQuery.h" #include "geometry/PxConvexMesh.h" #include "foundation/PxPhysicsVersion.h" #include "foundation/PxArray.h" #include "foundation/PxHashSet.h" #include "foundation/PxHashMap.h" #include "foundation/PxMathUtils.h" #include "foundation/PxFPU.h" #include "cooking/PxCooking.h" #include "cooking/PxConvexMeshDesc.h" #include "ExtConstraintHelper.h" #include "extensions/PxMassProperties.h" #include "extensions/PxDefaultAllocator.h" #include "extensions/PxDefaultErrorCallback.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetutils/SnippetImmUtils.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetRender.h" #endif //Enables TGS or PGS solver #define USE_TGS 0 //#define PRINT_TIMINGS #define TEST_IMMEDIATE_JOINTS //Enables whether we want persistent state caching (contact cache, friction caching) or not. Avoiding persistency results in one-shot collision detection and zero friction //correlation but simplifies code by not longer needing to cache persistent pairs. #define WITH_PERSISTENCY 1 //Toggles whether we batch constraints or not. Constraint batching is an optional process which can improve performance by grouping together independent constraints. These independent constraints //can be solved in parallel by using multiple lanes of SIMD registers. #define BATCH_CONTACTS 1 using namespace physx; using namespace immediate; using namespace SnippetImmUtils; static const PxVec3 gGravity(0.0f, -9.81f, 0.0f); static const float gContactDistance = 0.1f; static const float gMeshContactMargin = 0.01f; static const float gToleranceLength = 1.0f; static const float gBounceThreshold = -2.0f; static const float gFrictionOffsetThreshold = 0.04f; static const float gCorrelationDistance = 0.025f; static const float gBoundsInflation = 0.02f; static const float gStaticFriction = 0.5f; static const float gDynamicFriction = 0.5f; static const float gRestitution = 0.0f; static const float gMaxDepenetrationVelocity = 10.0f; static const float gMaxContactImpulse = FLT_MAX; static const float gLinearDamping = 0.1f; static const float gAngularDamping = 0.05f; static const float gMaxLinearVelocity = 100.0f; static const float gMaxAngularVelocity = 100.0f; static const float gJointFrictionCoefficient = 0.05f; static const PxU32 gNbIterPos = 4; static const PxU32 gNbIterVel = 1; static bool gPause = false; static bool gOneFrame = false; static bool gDrawBounds = false; static PxU32 gSceneIndex = 2; static float gTime = 0.0f; #if WITH_PERSISTENCY struct PersistentContactPair { PersistentContactPair() { reset(); } PxCache cache; PxU8* frictions; PxU32 nbFrictions; PX_FORCE_INLINE void reset() { cache = PxCache(); frictions = NULL; nbFrictions = 0; } }; #endif struct IDS { PX_FORCE_INLINE IDS(PxU32 id0, PxU32 id1) : mID0(id0), mID1(id1) {} PxU32 mID0; PxU32 mID1; PX_FORCE_INLINE bool operator == (const IDS& other) const { return mID0 == other.mID0 && mID1 == other.mID1; } }; PX_FORCE_INLINE uint32_t PxComputeHash(const IDS& p) { return PxComputeHash(uint64_t(p.mID0)|(uint64_t(p.mID1)<<32)); } struct MassProps { PxVec3 mInvInertia; float mInvMass; }; static void computeMassProps(MassProps& props, const PxGeometry& geometry, float mass) { if(mass!=0.0f) { PxMassProperties inertia(geometry); inertia = inertia * (mass/inertia.mass); PxQuat orient; const PxVec3 diagInertia = PxMassProperties::getMassSpaceInertia(inertia.inertiaTensor, orient); props.mInvMass = 1.0f/inertia.mass; props.mInvInertia.x = diagInertia.x == 0.0f ? 0.0f : 1.0f/diagInertia.x; props.mInvInertia.y = diagInertia.y == 0.0f ? 0.0f : 1.0f/diagInertia.y; props.mInvInertia.z = diagInertia.z == 0.0f ? 0.0f : 1.0f/diagInertia.z; } else { props.mInvMass = 0.0f; props.mInvInertia = PxVec3(0.0f); } } #ifdef TEST_IMMEDIATE_JOINTS struct MyJointData : Ext::JointData { PxU32 mActors[2]; PxTransform mLocalFrames[2]; void initInvMassScale() { invMassScale.linear0 = 1.0f; invMassScale.angular0 = 1.0f; invMassScale.linear1 = 1.0f; invMassScale.angular1 = 1.0f; } }; #endif class ImmediateScene { PX_NOCOPY(ImmediateScene) public: ImmediateScene(); ~ImmediateScene(); void reset(); PxU32 createActor(const PxGeometry& geometry, const PxTransform& pose, const MassProps* massProps=NULL, PxArticulationLinkCookie* linkCookie=0); void createGroundPlane() { createActor(PxPlaneGeometry(), PxTransformFromPlaneEquation(PxPlane(0.0f, 1.0f, 0.0f, 0.0f))); } void createScene(); #ifdef TEST_IMMEDIATE_JOINTS void createSphericalJoint(PxU32 id0, PxU32 id1, const PxTransform& localFrame0, const PxTransform& localFrame1, const PxTransform* pose0=NULL, const PxTransform* pose1=NULL); #endif void updateArticulations(float dt); void updateBounds(); void broadPhase(); void narrowPhase(); void buildSolverBodyData(float dt); void buildSolverConstraintDesc(); void createContactConstraints(float dt, float invDt, float lengthScale, PxU32 nbPositionIterations); void solveAndIntegrate(float dt); TestCacheAllocator* mCacheAllocator; TestConstraintAllocator* mConstraintAllocator; // PT: TODO: revisit this basic design once everything works PxArray<PxGeometryHolder> mGeoms; PxArray<PxTransform> mPoses; PxArray<PxBounds3> mBounds; class ImmediateActor { public: ImmediateActor() {} ~ImmediateActor() {} enum Type { eSTATIC, eDYNAMIC, eLINK, }; Type mType; PxU32 mCollisionGroup; MassProps mMassProps; PxVec3 mLinearVelocity; PxVec3 mAngularVelocity; // PT: ### TODO: revisit, these two could be a union, the cookie is only needed for a brief time during scene creation // Or move them to a completely different / hidden array PxArticulationLinkCookie mLinkCookie; PxArticulationLinkHandle mLink; }; PxArray<ImmediateActor> mActors; #if USE_TGS PxArray<PxTGSSolverBodyData> mSolverBodyData; PxArray<PxTGSSolverBodyVel> mSolverBodies; PxArray<PxTGSSolverBodyTxInertia> mSolverBodyTxInertias; #else PxArray<PxSolverBodyData> mSolverBodyData; PxArray<PxSolverBody> mSolverBodies; #endif PxArray<PxArticulationHandle> mArticulations; PxArray<PxSpatialVector> mTempZ; PxArray<PxSpatialVector> mTempDeltaV; #ifdef TEST_IMMEDIATE_JOINTS PxArray<MyJointData> mJointData; #endif PxArray<IDS> mBroadphasePairs; PxHashSet<IDS> mFilteredPairs; struct ContactPair { PxU32 mID0; PxU32 mID1; PxU32 mNbContacts; PxU32 mStartContactIndex; }; // PT: we use separate arrays here because the immediate mode API expects an array of PxContactPoint PxArray<ContactPair> mContactPairs; PxArray<PxContactPoint> mContactPoints; #if WITH_PERSISTENCY PxHashMap<IDS, PersistentContactPair> mPersistentPairs; #endif PxArray<PxSolverConstraintDesc> mSolverConstraintDesc; #if BATCH_CONTACTS PxArray<PxSolverConstraintDesc> mOrderedSolverConstraintDesc; #endif PxArray<PxConstraintBatchHeader> mHeaders; PxArray<PxReal> mContactForces; PxArray<PxVec3> mMotionLinearVelocity; // Persistent to avoid runtime allocations but could be managed on the stack PxArray<PxVec3> mMotionAngularVelocity; // Persistent to avoid runtime allocations but could be managed on the stack PxU32 mNbStaticActors; PxU32 mNbArticulationLinks; PxU32 mMaxNumArticulationsLinks; PX_FORCE_INLINE void disableCollision(PxU32 i, PxU32 j) { if(i>j) PxSwap(i, j); mFilteredPairs.insert(IDS(i, j)); } PX_FORCE_INLINE bool isCollisionDisabled(PxU32 i, PxU32 j) const { if(i>j) PxSwap(i, j); return mFilteredPairs.contains(IDS(i, j)); } PxArticulationLinkCookie mMotorLinkCookie; PxArticulationLinkHandle mMotorLink; PxArticulationHandle endCreateImmediateArticulation(PxArticulationCookie immArt); void allocateTempBuffer(const PxU32 maxLinks); }; ImmediateScene::ImmediateScene() : mNbStaticActors (0), mNbArticulationLinks (0), mMaxNumArticulationsLinks (0), mMotorLinkCookie (PxCreateArticulationLinkCookie()), mMotorLink (PxArticulationLinkHandle()) { mCacheAllocator = new TestCacheAllocator; mConstraintAllocator = new TestConstraintAllocator; } ImmediateScene::~ImmediateScene() { reset(); PX_DELETE(mConstraintAllocator); PX_DELETE(mCacheAllocator); } void ImmediateScene::reset() { mGeoms.clear(); mPoses.clear(); mBounds.clear(); mActors.clear(); mSolverBodyData.clear(); mSolverBodies.clear(); #if USE_TGS mSolverBodyTxInertias.clear(); #endif mBroadphasePairs.clear(); mFilteredPairs.clear(); mContactPairs.clear(); mContactPoints.clear(); mSolverConstraintDesc.clear(); #if BATCH_CONTACTS mOrderedSolverConstraintDesc.clear(); #endif mHeaders.clear(); mContactForces.clear(); mMotionLinearVelocity.clear(); mMotionAngularVelocity.clear(); const PxU32 size = mArticulations.size(); for(PxU32 i=0;i<size;i++) PxReleaseArticulation(mArticulations[i]); mArticulations.clear(); #ifdef TEST_IMMEDIATE_JOINTS mJointData.clear(); #endif #if WITH_PERSISTENCY mPersistentPairs.clear(); #endif mNbStaticActors = mNbArticulationLinks = 0; mMotorLinkCookie = PxCreateArticulationLinkCookie(); mMotorLink = PxArticulationLinkHandle(); gTime = 0.0f; } PxU32 ImmediateScene::createActor(const PxGeometry& geometry, const PxTransform& pose, const MassProps* massProps, PxArticulationLinkCookie* linkCookie) { const PxU32 id = mActors.size(); // PT: we don't support compounds in this simple snippet. 1 actor = 1 shape/geom. PX_ASSERT(mGeoms.size()==id); PX_ASSERT(mPoses.size()==id); PX_ASSERT(mBounds.size()==id); const bool isStaticActor = !massProps; if(isStaticActor) { PX_ASSERT(!linkCookie); mNbStaticActors++; } else { // PT: make sure we don't create dynamic actors after static ones. We could reorganize the array but // in this simple snippet we just enforce the order in which actors are created. PX_ASSERT(!mNbStaticActors); if(linkCookie) mNbArticulationLinks++; } ImmediateActor actor; if(isStaticActor) actor.mType = ImmediateActor::eSTATIC; else if(linkCookie) actor.mType = ImmediateActor::eLINK; else actor.mType = ImmediateActor::eDYNAMIC; actor.mCollisionGroup = 0; actor.mLinearVelocity = PxVec3(0.0f); actor.mAngularVelocity = PxVec3(0.0f); actor.mLinkCookie = linkCookie ? *linkCookie : PxCreateArticulationLinkCookie(); actor.mLink = PxArticulationLinkHandle(); // Not available yet if(massProps) actor.mMassProps = *massProps; else { actor.mMassProps.mInvMass = 0.0f; actor.mMassProps.mInvInertia = PxVec3(0.0f); } mActors.pushBack(actor); #if USE_TGS mSolverBodyData.pushBack(PxTGSSolverBodyData()); mSolverBodies.pushBack(PxTGSSolverBodyVel()); mSolverBodyTxInertias.pushBack(PxTGSSolverBodyTxInertia()); #else mSolverBodyData.pushBack(PxSolverBodyData()); mSolverBodies.pushBack(PxSolverBody()); #endif mGeoms.pushBack(geometry); mPoses.pushBack(pose); mBounds.pushBack(PxBounds3()); return id; } static PxArticulationCookie beginCreateImmediateArticulation(bool fixBase) { PxArticulationDataRC data; data.flags = fixBase ? PxArticulationFlag::eFIX_BASE : PxArticulationFlag::Enum(0); return PxBeginCreateArticulationRC(data); } void ImmediateScene::allocateTempBuffer(const PxU32 maxLinks) { mTempZ.resize(maxLinks); mTempDeltaV.resize(maxLinks); } PxArticulationHandle ImmediateScene::endCreateImmediateArticulation(PxArticulationCookie immArt) { PxU32 expectedNbLinks = 0; const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mLinkCookie.articulation) expectedNbLinks++; } PxArticulationLinkHandle* realLinkHandles = PX_ALLOCATE(PxArticulationLinkHandle, sizeof(PxArticulationLinkHandle) * expectedNbLinks, "PxArticulationLinkHandle"); PxArticulationHandle immArt2 = PxEndCreateArticulationRC(immArt, realLinkHandles, expectedNbLinks); mArticulations.pushBack(immArt2); mMaxNumArticulationsLinks = PxMax(mMaxNumArticulationsLinks, expectedNbLinks); PxU32 nbLinks = 0; for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mLinkCookie.articulation) mActors[i].mLink = realLinkHandles[nbLinks++]; } PX_ASSERT(expectedNbLinks==nbLinks); PX_FREE(realLinkHandles); return immArt2; } static void setupCommonLinkData(PxArticulationLinkDataRC& data, const PxTransform& pose, const MassProps& massProps) { data.pose = pose; data.inverseMass = massProps.mInvMass; data.inverseInertia = massProps.mInvInertia; data.linearDamping = gLinearDamping; data.angularDamping = gAngularDamping; data.maxLinearVelocitySq = gMaxLinearVelocity * gMaxLinearVelocity; data.maxAngularVelocitySq = gMaxAngularVelocity * gMaxAngularVelocity; data.inboundJoint.frictionCoefficient = gJointFrictionCoefficient; } #ifdef TEST_IMMEDIATE_JOINTS void ImmediateScene::createSphericalJoint(PxU32 id0, PxU32 id1, const PxTransform& localFrame0, const PxTransform& localFrame1, const PxTransform* pose0, const PxTransform* pose1) { const bool isStatic0 = mActors[id0].mType == ImmediateActor::eSTATIC; const bool isStatic1 = mActors[id1].mType == ImmediateActor::eSTATIC; MyJointData jointData; jointData.mActors[0] = id0; jointData.mActors[1] = id1; jointData.mLocalFrames[0] = localFrame0; jointData.mLocalFrames[1] = localFrame1; if(isStatic0) jointData.c2b[0] = pose0->getInverse().transformInv(localFrame0); else jointData.c2b[0] = localFrame0; if(isStatic1) jointData.c2b[1] = pose1->getInverse().transformInv(localFrame1); else jointData.c2b[1] = localFrame1; jointData.initInvMassScale(); mJointData.pushBack(jointData); disableCollision(id0, id1); } #endif void ImmediateScene::createScene() { mMotorLink = PxArticulationLinkHandle(); const PxU32 index = gSceneIndex; if(index==0) { // Box stack { const PxVec3 extents(0.5f, 0.5f, 0.5f); const PxBoxGeometry boxGeom(extents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); // for(PxU32 i=0;i<8;i++) // createBox(extents, PxTransform(PxVec3(0.0f, extents.y + float(i)*extents.y*2.0f, 0.0f)), 1.0f); PxU32 size = 8; // PxU32 size = 2; // PxU32 size = 1; float y = extents.y; float x = 0.0f; while(size) { for(PxU32 i=0;i<size;i++) createActor(boxGeom, PxTransform(PxVec3(x+float(i)*extents.x*2.0f, y, 0.0f)), &massProps); x += extents.x; y += extents.y*2.0f; size--; } } createGroundPlane(); } else if(index==1) { // Simple scene with regular spherical joint #ifdef TEST_IMMEDIATE_JOINTS const float boxSize = 1.0f; const PxVec3 extents(boxSize, boxSize, boxSize); const PxBoxGeometry boxGeom(extents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxVec3 staticPos(0.0f, 6.0f, 0.0f); const PxVec3 dynamicPos = staticPos - extents*2.0f; const PxTransform dynPose(dynamicPos); const PxTransform staticPose(staticPos); const PxU32 dynamicObject = createActor(boxGeom, dynPose, &massProps); const PxU32 staticObject = createActor(boxGeom, staticPose); createSphericalJoint(staticObject, dynamicObject, PxTransform(-extents), PxTransform(extents), &staticPose, &dynPose); #endif } else if(index==2) { // RC articulation with contacts if(1) { const PxBoxGeometry boxGeom(PxVec3(1.0f)); MassProps massProps; computeMassProps(massProps, boxGeom, 0.5f); createActor(boxGeom, PxTransform(PxVec3(0.0f, 1.0f, 0.0f)), &massProps); } const PxU32 nbLinks = 6; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); createGroundPlane(); } else if(index==3) { // RC articulation with limits const PxU32 nbLinks = 4; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi/8.0f; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi/8.0f; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); } else if(index==4) { if(0) { const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(false); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); PX_UNUSED(baseID); } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); return; } // RC articulation with drive const PxU32 nbLinks = 1; const float Altitude = 6.0f; const PxTransform basePose(PxVec3(0.f, Altitude, 0.f)); const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const PxBoxGeometry boxGeom(boxExtents); const float s = boxExtents.x*1.1f; MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); PxArticulationCookie immArt = beginCreateImmediateArticulation(true); PxArticulationLinkCookie base; PxU32 baseID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, basePose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, basePose, &massProps, &base); } PxArticulationLinkCookie parent = base; PxU32 parentID = baseID; PxTransform linkPose = basePose; for(PxU32 i=0;i<nbLinks;i++) { linkPose.p.z += s*2.0f; PxArticulationLinkCookie link; PxU32 linkID; { PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, linkPose, massProps); // linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].stiffness = 0.0f; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].damping = 1000.0f; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].maxForce = FLT_MAX; linkData.inboundJoint.drives[PxArticulationAxis::eTWIST].driveType = PxArticulationDriveType::eFORCE; linkData.inboundJoint.targetVel[PxArticulationAxis::eTWIST] = 4.0f; link = PxAddArticulationLink(immArt, &parent, linkData); linkID = createActor(boxGeom, linkPose, &massProps, &link); disableCollision(parentID, linkID); mMotorLinkCookie = link; mMotorLink = PxArticulationLinkHandle(); } parent = link; parentID = linkID; } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); //### not nice, revisit mMotorLink = mActors[1].mLink; } else if(index==5) { // Scissor lift const PxReal runnerLength = 2.f; const PxReal placementDistance = 1.8f; const PxReal cosAng = (placementDistance) / (runnerLength); const PxReal angle = PxAcos(cosAng); const PxReal sinAng = PxSin(angle); const PxQuat leftRot(-angle, PxVec3(1.f, 0.f, 0.f)); const PxQuat rightRot(angle, PxVec3(1.f, 0.f, 0.f)); PxArticulationCookie immArt = beginCreateImmediateArticulation(false); // PxArticulationLinkCookie base; PxU32 baseID; { const PxBoxGeometry boxGeom(0.5f, 0.25f, 1.5f); MassProps massProps; computeMassProps(massProps, boxGeom, 3.0f); const PxTransform pose(PxVec3(0.f, 0.25f, 0.f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); base = PxAddArticulationLink(immArt, 0, linkData); baseID = createActor(boxGeom, pose, &massProps, &base); } // PxArticulationLinkCookie leftRoot; PxU32 leftRootID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, 0.55f, -0.9f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eFIX; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.25f, -0.9f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.05f, 0.f)); leftRoot = PxAddArticulationLink(immArt, &base, linkData); leftRootID = createActor(boxGeom, pose, &massProps, &leftRoot); disableCollision(baseID, leftRootID); } // PxArticulationLinkCookie rightRoot; PxU32 rightRootID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, 0.55f, 0.9f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::ePRISMATIC; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.25f, 0.9f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.05f, 0.f)); linkData.inboundJoint.motion[PxArticulationAxis::eZ] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eZ].low = -1.4f; linkData.inboundJoint.limits[PxArticulationAxis::eZ].high = 0.2f; if(0) { linkData.inboundJoint.drives[PxArticulationAxis::eZ].stiffness = 100000.f; linkData.inboundJoint.drives[PxArticulationAxis::eZ].damping = 0.f; linkData.inboundJoint.drives[PxArticulationAxis::eZ].maxForce = PX_MAX_F32; linkData.inboundJoint.drives[PxArticulationAxis::eZ].driveType = PxArticulationDriveType::eFORCE; } rightRoot = PxAddArticulationLink(immArt, &base, linkData); rightRootID = createActor(boxGeom, pose, &massProps, &rightRoot); disableCollision(baseID, rightRootID); } // const PxU32 linkHeight = 3; PxU32 currLeftID = leftRootID; PxU32 currRightID = rightRootID; PxArticulationLinkCookie currLeft = leftRoot; PxArticulationLinkCookie currRight = rightRoot; PxQuat rightParentRot(PxIdentity); PxQuat leftParentRot(PxIdentity); for(PxU32 i=0; i<linkHeight; ++i) { const PxVec3 pos(0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLinkCookie leftLink; PxU32 leftLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currLeftID].transformInv(leftAnchorLocation), leftParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = angle; leftLink = PxAddArticulationLink(immArt, &currLeft, linkData); leftLinkID = createActor(boxGeom, pose, &massProps, &leftLink); disableCollision(currLeftID, leftLinkID); mActors[leftLinkID].mCollisionGroup = 1; } leftParentRot = leftRot; // PxArticulationLinkCookie rightLink; PxU32 rightLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currRightID].transformInv(rightAnchorLocation), rightParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -angle; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi; rightLink = PxAddArticulationLink(immArt, &currRight, linkData); rightLinkID = createActor(boxGeom, pose, &massProps, &rightLink); disableCollision(currRightID, rightLinkID); mActors[rightLinkID].mCollisionGroup = 1; } rightParentRot = rightRot; #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(leftLinkID, rightLinkID, PxTransform(PxIdentity), PxTransform(PxIdentity)); #else disableCollision(leftLinkID, rightLinkID); #endif currLeftID = rightLinkID; currRightID = leftLinkID; currLeft = rightLink; currRight = leftLink; } // PxArticulationLinkCookie leftTop; PxU32 leftTopID; { const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(mPoses[currLeftID].transform(PxTransform(PxVec3(-0.5f, 0.f, -1.0f), leftParentRot))); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.f, -1.f), mPoses[currLeftID].q.getConjugate()); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.5f, 0.f, 0.f), pose.q.getConjugate()); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; leftTop = PxAddArticulationLink(immArt, &currLeft, linkData); leftTopID = createActor(boxGeom, pose, &massProps, &leftTop); disableCollision(currLeftID, leftTopID); mActors[leftTopID].mCollisionGroup = 1; } // PxArticulationLinkCookie rightTop; PxU32 rightTopID; { // TODO: use a capsule here // PxRigidActorExt::createExclusiveShape(*rightTop, PxCapsuleGeometry(0.05f, 0.8f), *gMaterial); const PxBoxGeometry boxGeom(0.5f, 0.05f, 0.05f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(mPoses[currRightID].transform(PxTransform(PxVec3(-0.5f, 0.f, 1.0f), rightParentRot))); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.f, 1.f), mPoses[currRightID].q.getConjugate()); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.5f, 0.f, 0.f), pose.q.getConjugate()); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eFREE; rightTop = PxAddArticulationLink(immArt, &currRight, linkData); rightTopID = createActor(boxGeom, pose, &massProps, &rightTop); disableCollision(currRightID, rightTopID); mActors[rightTopID].mCollisionGroup = 1; } // currLeftID = leftRootID; currRightID = rightRootID; currLeft = leftRoot; currRight = rightRoot; rightParentRot = PxQuat(PxIdentity); leftParentRot = PxQuat(PxIdentity); for(PxU32 i=0; i<linkHeight; ++i) { const PxVec3 pos(-0.5f, 0.55f + 0.1f*(1 + i), 0.f); PxArticulationLinkCookie leftLink; PxU32 leftLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), leftRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 leftAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), -0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currLeftID].transformInv(leftAnchorLocation), leftParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, -1.f), rightRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -PxPi; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = angle; leftLink = PxAddArticulationLink(immArt, &currLeft, linkData); leftLinkID = createActor(boxGeom, pose, &massProps, &leftLink); disableCollision(currLeftID, leftLinkID); mActors[leftLinkID].mCollisionGroup = 1; } leftParentRot = leftRot; // PxArticulationLinkCookie rightLink; PxU32 rightLinkID; { const PxBoxGeometry boxGeom(0.05f, 0.05f, 1.f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(pos + PxVec3(0.f, sinAng*(2 * i + 1), 0.f), rightRot); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); const PxVec3 rightAnchorLocation = pos + PxVec3(0.f, sinAng*(2 * i), 0.9f); linkData.inboundJoint.type = PxArticulationJointType::eREVOLUTE; linkData.inboundJoint.parentPose = PxTransform(mPoses[currRightID].transformInv(rightAnchorLocation), rightParentRot); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, 0.f, 1.f), leftRot); linkData.inboundJoint.motion[PxArticulationAxis::eTWIST] = PxArticulationMotion::eLIMITED; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].low = -angle; linkData.inboundJoint.limits[PxArticulationAxis::eTWIST].high = PxPi; rightLink = PxAddArticulationLink(immArt, &currRight, linkData); rightLinkID = createActor(boxGeom, pose, &massProps, &rightLink); disableCollision(currRightID, rightLinkID); mActors[rightLinkID].mCollisionGroup = 1; } rightParentRot = rightRot; #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(leftLinkID, rightLinkID, PxTransform(PxIdentity), PxTransform(PxIdentity)); #else disableCollision(leftLinkID, rightLinkID); #endif currLeftID = rightLinkID; currRightID = leftLinkID; currLeft = rightLink; currRight = leftLink; } // #ifdef TEST_IMMEDIATE_JOINTS createSphericalJoint(currLeftID, leftTopID, PxTransform(PxVec3(0.f, 0.f, -1.f)), PxTransform(PxVec3(-0.5f, 0.f, 0.f))); createSphericalJoint(currRightID, rightTopID, PxTransform(PxVec3(0.f, 0.f, 1.f)), PxTransform(PxVec3(-0.5f, 0.f, 0.f))); #else disableCollision(currLeftID, leftTopID); disableCollision(currRightID, rightTopID); #endif // // Create top { PxArticulationLinkCookie top; PxU32 topID; { const PxBoxGeometry boxGeom(0.5f, 0.1f, 1.5f); MassProps massProps; computeMassProps(massProps, boxGeom, 1.0f); const PxTransform pose(PxVec3(0.f, mPoses[leftTopID].p.y + 0.15f, 0.f)); PxArticulationLinkDataRC linkData; setupCommonLinkData(linkData, pose, massProps); linkData.inboundJoint.type = PxArticulationJointType::eFIX; linkData.inboundJoint.parentPose = PxTransform(PxVec3(0.f, 0.0f, 0.f)); linkData.inboundJoint.childPose = PxTransform(PxVec3(0.f, -0.15f, -0.9f)); top = PxAddArticulationLink(immArt, &leftTop, linkData); topID = createActor(boxGeom, pose, &massProps, &top); disableCollision(leftTopID, topID); } } endCreateImmediateArticulation(immArt); allocateTempBuffer(mMaxNumArticulationsLinks); createGroundPlane(); } else if(index==6) { //const float scaleFactor = 0.25f; const float scaleFactor = 1.0f; const float halfHeight = 1.0f*scaleFactor; const float radius = 1.0f*scaleFactor; const PxU32 nbCirclePts = 20; const PxU32 totalNbVerts = nbCirclePts*2; PxVec3 verts[totalNbVerts]; const float step = 3.14159f*2.0f/float(nbCirclePts); for(PxU32 i=0;i<nbCirclePts;i++) { verts[i].x = sinf(float(i) * step) * radius; verts[i].y = cosf(float(i) * step) * radius; verts[i].z = 0.0f; } const PxVec3 offset(0.0f, 0.0f, halfHeight); PxVec3* verts2 = verts + nbCirclePts; for(PxU32 i=0;i<nbCirclePts;i++) { const PxVec3 P = verts[i]; verts[i] = P - offset; verts2[i] = P + offset; } const PxTolerancesScale scale; PxCookingParams params(scale); PxConvexMeshDesc convexDesc; convexDesc.points.count = totalNbVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; PxConvexMesh* convexMesh = PxCreateConvexMesh(params, convexDesc); const PxConvexMeshGeometry convexGeom(convexMesh); MassProps massProps; computeMassProps(massProps, convexGeom, 1.0f); const PxQuat rot = PxShortestRotation(PxVec3(0.0f, 0.0f, 1.0f), PxVec3(0.0f, 1.0f, 0.0f)); PxU32 Nb = 14; float altitude = radius; float offsetX = 0.0f; while(Nb) { for(PxU32 i=0;i<Nb;i++) { createActor(convexGeom, PxTransform(PxVec3(offsetX + float(i)*radius*2.2f, altitude, 0.0f), rot), &massProps); } Nb--; altitude += halfHeight*2.0f+0.01f; offsetX += radius*1.1f; } createGroundPlane(); } } void ImmediateScene::updateArticulations(float dt) { #if USE_TGS const float stepDt = dt/gNbIterPos; const float invTotalDt = 1.0f/dt; const float stepInvDt = 1.0f/stepDt; #endif const PxU32 nbArticulations = mArticulations.size(); for(PxU32 i=0;i<nbArticulations;i++) { PxArticulationHandle articulation = mArticulations[i]; #if USE_TGS PxComputeUnconstrainedVelocitiesTGS(articulation, gGravity, stepDt, dt, stepInvDt, invTotalDt, 1.0f); #else PxComputeUnconstrainedVelocities(articulation, gGravity, dt, 1.0f); #endif } } void ImmediateScene::updateBounds() { PX_SIMD_GUARD // PT: in this snippet we simply recompute all bounds each frame (i.e. even static ones) const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) PxGeometryQuery::computeGeomBounds(mBounds[i], mGeoms[i].any(), mPoses[i], gBoundsInflation, 1.0f, PxGeometryQueryFlag::Enum(0)); } void ImmediateScene::broadPhase() { // PT: in this snippet we simply do a brute-force O(n^2) broadphase between all actors mBroadphasePairs.clear(); const PxU32 nbActors = mActors.size(); for(PxU32 i=0; i<nbActors; i++) { const ImmediateActor::Type type0 = mActors[i].mType; for(PxU32 j=i+1; j<nbActors; j++) { const ImmediateActor::Type type1 = mActors[j].mType; // Filtering { if(type0==ImmediateActor::eSTATIC && type1==ImmediateActor::eSTATIC) continue; if(mActors[i].mCollisionGroup==1 && mActors[j].mCollisionGroup==1) continue; if(isCollisionDisabled(i, j)) continue; } if(mBounds[i].intersects(mBounds[j])) { mBroadphasePairs.pushBack(IDS(i, j)); } #if WITH_PERSISTENCY else { //No collision detection performed at all so clear contact cache and friction data mPersistentPairs.erase(IDS(i, j)); } #endif } } } void ImmediateScene::narrowPhase() { class ContactRecorder : public PxContactRecorder { public: ContactRecorder(ImmediateScene* scene, PxU32 id0, PxU32 id1) : mScene(scene), mID0(id0), mID1(id1), mHasContacts(false) {} virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 /*index*/) { { ImmediateScene::ContactPair pair; pair.mID0 = mID0; pair.mID1 = mID1; pair.mNbContacts = nbContacts; pair.mStartContactIndex = mScene->mContactPoints.size(); mScene->mContactPairs.pushBack(pair); mHasContacts = true; } for(PxU32 i=0; i<nbContacts; i++) { // Fill in solver-specific data that our contact gen does not produce... PxContactPoint point = contactPoints[i]; point.maxImpulse = PX_MAX_F32; point.targetVel = PxVec3(0.0f); point.staticFriction = gStaticFriction; point.dynamicFriction = gDynamicFriction; point.restitution = gRestitution; point.materialFlags = PxMaterialFlag::eIMPROVED_PATCH_FRICTION; mScene->mContactPoints.pushBack(point); } return true; } ImmediateScene* mScene; PxU32 mID0; PxU32 mID1; bool mHasContacts; }; mCacheAllocator->reset(); mConstraintAllocator->release(); mContactPairs.resize(0); mContactPoints.resize(0); const PxU32 nbPairs = mBroadphasePairs.size(); for(PxU32 i=0;i<nbPairs;i++) { const IDS& pair = mBroadphasePairs[i]; const PxTransform& tr0 = mPoses[pair.mID0]; const PxTransform& tr1 = mPoses[pair.mID1]; const PxGeometry* pxGeom0 = &mGeoms[pair.mID0].any(); const PxGeometry* pxGeom1 = &mGeoms[pair.mID1].any(); ContactRecorder contactRecorder(this, pair.mID0, pair.mID1); #if WITH_PERSISTENCY PersistentContactPair& persistentData = mPersistentPairs[IDS(pair.mID0, pair.mID1)]; PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &persistentData.cache, 1, contactRecorder, gContactDistance, gMeshContactMargin, gToleranceLength, *mCacheAllocator); if(!contactRecorder.mHasContacts) { //Contact generation run but no touches found so clear cached friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; } #else PxCache cache; PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &cache, 1, contactRecorder, gContactDistance, gMeshContactMargin, gToleranceLength, *mCacheAllocator); #endif } if(1) { printf("Narrow-phase: %d contacts \r", mContactPoints.size()); } } void ImmediateScene::buildSolverBodyData(float dt) { const PxU32 nbActors = mActors.size(); for(PxU32 i=0;i<nbActors;i++) { if(mActors[i].mType==ImmediateActor::eSTATIC) { #if USE_TGS PxConstructStaticSolverBodyTGS(mPoses[i], mSolverBodies[i], mSolverBodyTxInertias[i], mSolverBodyData[i]); #else PxConstructStaticSolverBody(mPoses[i], mSolverBodyData[i]); #endif } else { PxRigidBodyData data; data.linearVelocity = mActors[i].mLinearVelocity; data.angularVelocity = mActors[i].mAngularVelocity; data.invMass = mActors[i].mMassProps.mInvMass; data.invInertia = mActors[i].mMassProps.mInvInertia; data.body2World = mPoses[i]; data.maxDepenetrationVelocity = gMaxDepenetrationVelocity; data.maxContactImpulse = gMaxContactImpulse; data.linearDamping = gLinearDamping; data.angularDamping = gAngularDamping; data.maxLinearVelocitySq = gMaxLinearVelocity*gMaxLinearVelocity; data.maxAngularVelocitySq = gMaxAngularVelocity*gMaxAngularVelocity; #if USE_TGS PxConstructSolverBodiesTGS(&data, &mSolverBodies[i], &mSolverBodyTxInertias[i], &mSolverBodyData[i], 1, gGravity, dt); #else PxConstructSolverBodies(&data, &mSolverBodyData[i], 1, gGravity, dt); #endif } } } #if USE_TGS static void setupDesc(PxSolverConstraintDesc& desc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyVel* solverBodies, PxU32 id, bool aorb) #else static void setupDesc(PxSolverConstraintDesc& desc, const ImmediateScene::ImmediateActor* actors, PxSolverBody* solverBodies, PxU32 id, bool aorb) #endif { if(!aorb) desc.bodyADataIndex = id; else desc.bodyBDataIndex = id; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { if(!aorb) { desc.articulationA = link.articulation; desc.linkIndexA = link.linkId; } else { desc.articulationB = link.articulation; desc.linkIndexB = link.linkId; } } else { if(!aorb) { #if USE_TGS desc.tgsBodyA = &solverBodies[id]; #else desc.bodyA = &solverBodies[id]; #endif desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; } else { #if USE_TGS desc.tgsBodyB = &solverBodies[id]; #else desc.bodyB = &solverBodies[id]; #endif desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; } } } void ImmediateScene::buildSolverConstraintDesc() { const PxU32 nbContactPairs = mContactPairs.size(); #ifdef TEST_IMMEDIATE_JOINTS const PxU32 nbJoints = mJointData.size(); mSolverConstraintDesc.resize(nbContactPairs+nbJoints); #else mSolverConstraintDesc.resize(nbContactPairs); #endif for(PxU32 i=0; i<nbContactPairs; i++) { const ContactPair& pair = mContactPairs[i]; PxSolverConstraintDesc& desc = mSolverConstraintDesc[i]; setupDesc(desc, mActors.begin(), mSolverBodies.begin(), pair.mID0, false); setupDesc(desc, mActors.begin(), mSolverBodies.begin(), pair.mID1, true); //Cache pointer to our contact data structure and identify which type of constraint this is. We'll need this later after batching. //If we choose not to perform batching and instead just create a single header per-pair, then this would not be necessary because //the constraintDescs would not have been reordered desc.constraint = reinterpret_cast<PxU8*>(const_cast<ContactPair*>(&pair)); desc.constraintLengthOver16 = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJoints; i++) { const MyJointData& jointData = mJointData[i]; PxSolverConstraintDesc& desc = mSolverConstraintDesc[nbContactPairs+i]; const PxU32 id0 = jointData.mActors[0]; const PxU32 id1 = jointData.mActors[1]; setupDesc(desc, mActors.begin(), mSolverBodies.begin(), id0, false); setupDesc(desc, mActors.begin(), mSolverBodies.begin(), id1, true); desc.constraint = reinterpret_cast<PxU8*>(const_cast<MyJointData*>(&jointData)); desc.constraintLengthOver16 = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif } #ifdef TEST_IMMEDIATE_JOINTS // PT: this is copied from PxExtensions, it's the solver prep function for spherical joints //TAG:solverprepshader static PxU32 SphericalJointSolverPrep(Px1DConstraint* constraints, PxVec3p& body0WorldOffset, PxU32 /*maxConstraints*/, PxConstraintInvMassScale& invMassScale, const void* constantBlock, const PxTransform& bA2w, const PxTransform& bB2w, bool /*useExtendedLimits*/, PxVec3p& cA2wOut, PxVec3p& cB2wOut) { const MyJointData& data = *reinterpret_cast<const MyJointData*>(constantBlock); PxTransform32 cA2w, cB2w; Ext::joint::ConstraintHelper ch(constraints, invMassScale, cA2w, cB2w, body0WorldOffset, data, bA2w, bB2w); Ext::joint::applyNeighborhoodOperator(cA2w, cB2w); /* if(data.jointFlags & PxSphericalJointFlag::eLIMIT_ENABLED) { PxQuat swing, twist; PxSeparateSwingTwist(cA2w.q.getConjugate() * cB2w.q, swing, twist); PX_ASSERT(PxAbs(swing.x)<1e-6f); // PT: TODO: refactor with D6 joint code PxVec3 axis; PxReal error; const PxReal pad = data.limit.isSoft() ? 0.0f : data.limit.contactDistance; const Cm::ConeLimitHelperTanLess coneHelper(data.limit.yAngle, data.limit.zAngle, pad); const bool active = coneHelper.getLimit(swing, axis, error); if(active) ch.angularLimit(cA2w.rotate(axis), error, data.limit); }*/ PxVec3 ra, rb; ch.prepareLockedAxes(cA2w.q, cB2w.q, cA2w.transformInv(cB2w.p), 7, 0, ra, rb); cA2wOut = ra + bA2w.p; cB2wOut = rb + bB2w.p; return ch.getCount(); } #endif #if USE_TGS static void setupDesc(PxTGSSolverContactDesc& contactDesc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyData, PxTransform* poses, const PxU32 id, const bool aorb) { PxTransform& bodyFrame = aorb ? contactDesc.bodyFrame1 : contactDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? contactDesc.bodyState1 : contactDesc.bodyState0; const PxTGSSolverBodyData*& data = aorb ? contactDesc.bodyData1 : contactDesc.bodyData0; const PxTGSSolverBodyTxInertia*& txI = aorb ? contactDesc.body1TxI : contactDesc.body0TxI; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(link, linkData); PX_ASSERT(status); PX_UNUSED(status); data = NULL; txI = NULL; bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { data = &solverBodyData[id]; txI = &txInertias[id]; bodyFrame = poses[id]; bodyState = actors[id].mType == ImmediateScene::ImmediateActor::eDYNAMIC ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; } } #else static void setupDesc(PxSolverContactDesc& contactDesc, const ImmediateScene::ImmediateActor* actors, PxSolverBodyData* solverBodyData, const PxU32 id, const bool aorb) { PxTransform& bodyFrame = aorb ? contactDesc.bodyFrame1 : contactDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? contactDesc.bodyState1 : contactDesc.bodyState0; const PxSolverBodyData*& data = aorb ? contactDesc.data1 : contactDesc.data0; const PxArticulationLinkHandle& link = actors[id].mLink; if(link.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(link, linkData); PX_ASSERT(status); PX_UNUSED(status); data = NULL; bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { data = &solverBodyData[id]; bodyFrame = solverBodyData[id].body2World; bodyState = actors[id].mType == ImmediateScene::ImmediateActor::eDYNAMIC ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; } } #endif #if USE_TGS static void setupJointDesc(PxTGSSolverConstraintPrepDesc& jointDesc, const ImmediateScene::ImmediateActor* actors, PxTGSSolverBodyTxInertia* txInertias, PxTGSSolverBodyData* solverBodyData, PxTransform* poses, const PxU32 bodyDataIndex, const bool aorb) { if(!aorb) { jointDesc.bodyData0 = &solverBodyData[bodyDataIndex]; jointDesc.body0TxI = &txInertias[bodyDataIndex]; } else { jointDesc.bodyData1 = &solverBodyData[bodyDataIndex]; jointDesc.body1TxI = &txInertias[bodyDataIndex]; } PxTransform& bodyFrame = aorb ? jointDesc.bodyFrame1 : jointDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? jointDesc.bodyState1 : jointDesc.bodyState0; if(actors[bodyDataIndex].mLink.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(actors[bodyDataIndex].mLink, linkData); PX_ASSERT(status); PX_UNUSED(status); bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. // PT: TODO: this is a bug in the immediate mode snippet if(actors[bodyDataIndex].mType == ImmediateScene::ImmediateActor::eSTATIC) { bodyFrame = PxTransform(PxIdentity); bodyState = PxSolverConstraintPrepDescBase::eSTATIC_BODY; } else { bodyFrame = poses[bodyDataIndex]; bodyState = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; } } } #else static void setupJointDesc(PxSolverConstraintPrepDesc& jointDesc, const ImmediateScene::ImmediateActor* actors, PxSolverBodyData* solverBodyData, const PxU32 bodyDataIndex, const bool aorb) { if(!aorb) jointDesc.data0 = &solverBodyData[bodyDataIndex]; else jointDesc.data1 = &solverBodyData[bodyDataIndex]; PxTransform& bodyFrame = aorb ? jointDesc.bodyFrame1 : jointDesc.bodyFrame0; PxSolverConstraintPrepDescBase::BodyState& bodyState = aorb ? jointDesc.bodyState1 : jointDesc.bodyState0; if(actors[bodyDataIndex].mLink.articulation) { PxArticulationLinkDerivedDataRC linkData; bool status = PxGetLinkData(actors[bodyDataIndex].mLink, linkData); PX_ASSERT(status); PX_UNUSED(status); bodyFrame = linkData.pose; bodyState = PxSolverConstraintPrepDescBase::eARTICULATION; } else { //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. // PT: TODO: this is a bug in the immediate mode snippet if(actors[bodyDataIndex].mType == ImmediateScene::ImmediateActor::eSTATIC) { bodyFrame = PxTransform(PxIdentity); bodyState = PxSolverConstraintPrepDescBase::eSTATIC_BODY; } else { bodyFrame = solverBodyData[bodyDataIndex].body2World; bodyState = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; } } } #endif void ImmediateScene::createContactConstraints(float dt, float invDt, float lengthScale, const PxU32 nbPosIterations) { //Only referenced if using TGS solver PX_UNUSED(lengthScale); PX_UNUSED(nbPosIterations); #if USE_TGS const float stepDt = dt/float(nbPosIterations); const float stepInvDt = invDt*float(nbPosIterations); #endif #if BATCH_CONTACTS mHeaders.resize(mSolverConstraintDesc.size()); const PxU32 nbBodies = mActors.size() - mNbStaticActors; mOrderedSolverConstraintDesc.resize(mSolverConstraintDesc.size()); PxArray<PxSolverConstraintDesc>& orderedDescs = mOrderedSolverConstraintDesc; #if USE_TGS const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraintsTGS( mSolverConstraintDesc.begin(), mContactPairs.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin(), orderedDescs.begin(), mArticulations.begin(), mArticulations.size()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraintsTGS( mSolverConstraintDesc.begin() + mContactPairs.size(), mJointData.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin() + nbContactHeaders, orderedDescs.begin() + mContactPairs.size(), mArticulations.begin(), mArticulations.size()); #else //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraints(mSolverConstraintDesc.begin(), mContactPairs.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin(), orderedDescs.begin(), mArticulations.begin(), mArticulations.size()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraints( mSolverConstraintDesc.begin() + mContactPairs.size(), mJointData.size(), mSolverBodies.begin(), nbBodies, mHeaders.begin() + nbContactHeaders, orderedDescs.begin() + mContactPairs.size(), mArticulations.begin(), mArticulations.size()); #endif const PxU32 totalHeaders = nbContactHeaders + nbJointHeaders; mHeaders.forceSize_Unsafe(totalHeaders); #else PxArray<PxSolverConstraintDesc>& orderedDescs = mSolverConstraintDesc; const PxU32 nbContactHeaders = mContactPairs.size(); #ifdef TEST_IMMEDIATE_JOINTS const PxU32 nbJointHeaders = mJointData.size(); PX_ASSERT(nbContactHeaders+nbJointHeaders==mSolverConstraintDesc.size()); mHeaders.resize(nbContactHeaders+nbJointHeaders); #else PX_ASSERT(nbContactHeaders==mSolverConstraintDesc.size()); PX_UNUSED(dt); mHeaders.resize(nbContactHeaders); #endif // We are bypassing the constraint batching so we create dummy PxConstraintBatchHeaders for(PxU32 i=0; i<nbContactHeaders; i++) { PxConstraintBatchHeader& hdr = mHeaders[i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJointHeaders; i++) { PxConstraintBatchHeader& hdr = mHeaders[nbContactHeaders+i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif #endif mContactForces.resize(mContactPoints.size()); for(PxU32 i=0; i<nbContactHeaders; i++) { PxConstraintBatchHeader& header = mHeaders[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eCONTACT_CONSTRAINT); #if USE_TGS PxTGSSolverContactDesc contactDescs[4]; #else PxSolverContactDesc contactDescs[4]; #endif #if WITH_PERSISTENCY PersistentContactPair* persistentPairs[4]; #endif for(PxU32 a=0; a<header.stride; a++) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. const ContactPair& pair = *reinterpret_cast<const ContactPair*>(constraintDesc.constraint); #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; PxMemZero(&contactDesc, sizeof(contactDesc)); setupDesc(contactDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), pair.mID0, false); setupDesc(contactDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), pair.mID1, true); contactDesc.body0 = constraintDesc.tgsBodyA; contactDesc.body1 = constraintDesc.tgsBodyB; contactDesc.torsionalPatchRadius = 0.0f; contactDesc.minTorsionalPatchRadius = 0.0f; #else PxSolverContactDesc& contactDesc = contactDescs[a]; PxMemZero(&contactDesc, sizeof(contactDesc)); setupDesc(contactDesc, mActors.begin(), mSolverBodyData.begin(), pair.mID0, false); setupDesc(contactDesc, mActors.begin(), mSolverBodyData.begin(), pair.mID1, true); contactDesc.body0 = constraintDesc.bodyA; contactDesc.body1 = constraintDesc.bodyB; #endif contactDesc.contactForces = &mContactForces[pair.mStartContactIndex]; contactDesc.contacts = &mContactPoints[pair.mStartContactIndex]; contactDesc.numContacts = pair.mNbContacts; #if WITH_PERSISTENCY const PxHashMap<IDS, PersistentContactPair>::Entry* e = mPersistentPairs.find(IDS(pair.mID0, pair.mID1)); PX_ASSERT(e); { PersistentContactPair& pcp = const_cast<PersistentContactPair&>(e->second); contactDesc.frictionPtr = pcp.frictions; contactDesc.frictionCount = PxU8(pcp.nbFrictions); persistentPairs[a] = &pcp; } #else contactDesc.frictionPtr = NULL; contactDesc.frictionCount = 0; #endif contactDesc.maxCCDSeparation = PX_MAX_F32; contactDesc.desc = &constraintDesc; contactDesc.invMassScales.angular0 = contactDesc.invMassScales.angular1 = contactDesc.invMassScales.linear0 = contactDesc.invMassScales.linear1 = 1.0f; } #if USE_TGS PxCreateContactConstraintsTGS(&header, 1, contactDescs, *mConstraintAllocator, stepInvDt, invDt, gBounceThreshold, gFrictionOffsetThreshold, gCorrelationDistance); #else PxCreateContactConstraints(&header, 1, contactDescs, *mConstraintAllocator, invDt, gBounceThreshold, gFrictionOffsetThreshold, gCorrelationDistance, mTempZ.begin()); #endif #if WITH_PERSISTENCY //Cache friction information... for (PxU32 a = 0; a < header.stride; ++a) { #if USE_TGS const PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else const PxSolverContactDesc& contactDesc = contactDescs[a]; #endif PersistentContactPair& pcp = *persistentPairs[a]; pcp.frictions = contactDesc.frictionPtr; pcp.nbFrictions = contactDesc.frictionCount; } #endif } #ifdef TEST_IMMEDIATE_JOINTS for(PxU32 i=0; i<nbJointHeaders; i++) { PxConstraintBatchHeader& header = mHeaders[nbContactHeaders+i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eJOINT_CONSTRAINT); { #if USE_TGS PxTGSSolverConstraintPrepDesc jointDescs[4]; #else PxSolverConstraintPrepDesc jointDescs[4]; #endif PxImmediateConstraint constraints[4]; header.startIndex += mContactPairs.size(); for(PxU32 a=0; a<header.stride; a++) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. const MyJointData& jd = *reinterpret_cast<const MyJointData*>(constraintDesc.constraint); constraints[a].prep = SphericalJointSolverPrep; constraints[a].constantBlock = &jd; #if USE_TGS PxTGSSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.tgsBodyA; jointDesc.body1 = constraintDesc.tgsBodyB; setupJointDesc(jointDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), constraintDesc.bodyADataIndex, false); setupJointDesc(jointDesc, mActors.begin(), mSolverBodyTxInertias.begin(), mSolverBodyData.begin(), mPoses.begin(), constraintDesc.bodyBDataIndex, true); #else PxSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.bodyA; jointDesc.body1 = constraintDesc.bodyB; setupJointDesc(jointDesc, mActors.begin(), mSolverBodyData.begin(), constraintDesc.bodyADataIndex, false); setupJointDesc(jointDesc, mActors.begin(), mSolverBodyData.begin(), constraintDesc.bodyBDataIndex, true); #endif jointDesc.desc = &constraintDesc; jointDesc.writeback = NULL; jointDesc.linBreakForce = PX_MAX_F32; jointDesc.angBreakForce = PX_MAX_F32; jointDesc.minResponseThreshold = 0; jointDesc.disablePreprocessing = false; jointDesc.improvedSlerp = false; jointDesc.driveLimitsAreForces = false; jointDesc.invMassScales.angular0 = jointDesc.invMassScales.angular1 = jointDesc.invMassScales.linear0 = jointDesc.invMassScales.linear1 = 1.0f; } #if USE_TGS immediate::PxCreateJointConstraintsWithImmediateShadersTGS(&header, 1, constraints, jointDescs, *mConstraintAllocator, stepDt, dt, stepInvDt, invDt, lengthScale); #else immediate::PxCreateJointConstraintsWithImmediateShaders(&header, 1, constraints, jointDescs, *mConstraintAllocator, dt, invDt, mTempZ.begin()); #endif } } #endif } void ImmediateScene::solveAndIntegrate(float dt) { #ifdef PRINT_TIMINGS unsigned long long time0 = __rdtsc(); #endif const PxU32 totalNbActors = mActors.size(); const PxU32 nbDynamicActors = totalNbActors - mNbStaticActors - mNbArticulationLinks; const PxU32 nbDynamic = nbDynamicActors + mNbArticulationLinks; mMotionLinearVelocity.resize(nbDynamic); mMotionAngularVelocity.resize(nbDynamic); const PxU32 nbArticulations = mArticulations.size(); PxArticulationHandle* articulations = mArticulations.begin(); #if USE_TGS const float stepDt = dt/float(gNbIterPos); immediate::PxSolveConstraintsTGS(mHeaders.begin(), mHeaders.size(), #if BATCH_CONTACTS mOrderedSolverConstraintDesc.begin(), #else mSolverConstraintDesc.begin(), #endif mSolverBodies.begin(), mSolverBodyTxInertias.begin(), nbDynamic, gNbIterPos, gNbIterVel, stepDt, 1.0f / stepDt, nbArticulations, articulations, mTempZ.begin(), mTempDeltaV.begin()); #else PxMemZero(mSolverBodies.begin(), mSolverBodies.size() * sizeof(PxSolverBody)); PxSolveConstraints( mHeaders.begin(), mHeaders.size(), #if BATCH_CONTACTS mOrderedSolverConstraintDesc.begin(), #else mSolverConstraintDesc.begin(), #endif mSolverBodies.begin(), mMotionLinearVelocity.begin(), mMotionAngularVelocity.begin(), nbDynamic, gNbIterPos, gNbIterVel, dt, 1.0f/dt, nbArticulations, articulations, mTempZ.begin(), mTempDeltaV.begin()); #endif #ifdef PRINT_TIMINGS unsigned long long time1 = __rdtsc(); #endif #if USE_TGS PxIntegrateSolverBodiesTGS(mSolverBodies.begin(), mSolverBodyTxInertias.begin(), mPoses.begin(), nbDynamicActors, dt); for (PxU32 i = 0; i<nbArticulations; i++) PxUpdateArticulationBodiesTGS(articulations[i], dt); for (PxU32 i = 0; i<nbDynamicActors; i++) { PX_ASSERT(mActors[i].mType == ImmediateActor::eDYNAMIC); const PxTGSSolverBodyVel& data = mSolverBodies[i]; mActors[i].mLinearVelocity = data.linearVelocity; mActors[i].mAngularVelocity = data.angularVelocity; } #else PxIntegrateSolverBodies(mSolverBodyData.begin(), mSolverBodies.begin(), mMotionLinearVelocity.begin(), mMotionAngularVelocity.begin(), nbDynamicActors, dt); for (PxU32 i = 0; i<nbArticulations; i++) PxUpdateArticulationBodies(articulations[i], dt); for (PxU32 i = 0; i<nbDynamicActors; i++) { PX_ASSERT(mActors[i].mType == ImmediateActor::eDYNAMIC); const PxSolverBodyData& data = mSolverBodyData[i]; mActors[i].mLinearVelocity = data.linearVelocity; mActors[i].mAngularVelocity = data.angularVelocity; mPoses[i] = data.body2World; } #endif for(PxU32 i=0;i<mNbArticulationLinks;i++) { const PxU32 j = nbDynamicActors + i; PX_ASSERT(mActors[j].mType==ImmediateActor::eLINK); PxArticulationLinkDerivedDataRC data; bool status = PxGetLinkData(mActors[j].mLink, data); PX_ASSERT(status); PX_UNUSED(status); mActors[j].mLinearVelocity = data.linearVelocity; mActors[j].mAngularVelocity = data.angularVelocity; mPoses[j] = data.pose; } #ifdef PRINT_TIMINGS unsigned long long time2 = __rdtsc(); printf("solve: %d \n", (time1-time0)/1024); printf("integrate: %d \n", (time2-time1)/1024); #endif } static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static ImmediateScene* gScene = NULL; /////////////////////////////////////////////////////////////////////////////// PxU32 getNbGeoms() { return gScene ? gScene->mGeoms.size() : 0; } const PxGeometryHolder* getGeoms() { if(!gScene || !gScene->mGeoms.size()) return NULL; return &gScene->mGeoms[0]; } const PxTransform* getGeomPoses() { if(!gScene || !gScene->mPoses.size()) return NULL; return &gScene->mPoses[0]; } PxU32 getNbArticulations() { return gScene ? gScene->mArticulations.size() : 0; } PxArticulationHandle* getArticulations() { if(!gScene || !gScene->mArticulations.size()) return NULL; return &gScene->mArticulations[0]; } PxU32 getNbBounds() { if(!gDrawBounds) return 0; return gScene ? gScene->mBounds.size() : 0; } const PxBounds3* getBounds() { if(!gDrawBounds) return NULL; if(!gScene || !gScene->mBounds.size()) return NULL; return &gScene->mBounds[0]; } PxU32 getNbContacts() { return gScene ? gScene->mContactPoints.size() : 0; } const PxContactPoint* getContacts() { if(!gScene || !gScene->mContactPoints.size()) return NULL; return &gScene->mContactPoints[0]; } /////////////////////////////////////////////////////////////////////////////// void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gScene = new ImmediateScene; gScene->createScene(); } void stepPhysics(bool /*interactive*/) { if(!gScene) return; if(gPause && !gOneFrame) return; gOneFrame = false; const float dt = 1.0f/60.0f; const float invDt = 60.0f; { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->updateArticulations(dt); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("updateArticulations: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->updateBounds(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("updateBounds: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->broadPhase(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("broadPhase: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->narrowPhase(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("narrowPhase: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->buildSolverBodyData(dt); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("buildSolverBodyData: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->buildSolverConstraintDesc(); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("buildSolverConstraintDesc: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS unsigned long long time = __rdtsc(); #endif gScene->createContactConstraints(dt, invDt, 1.f, gNbIterPos); #ifdef PRINT_TIMINGS time = __rdtsc() - time; printf("createContactConstraints: %d \n", time/1024); #endif } { #ifdef PRINT_TIMINGS // unsigned long long time = __rdtsc(); #endif gScene->solveAndIntegrate(dt); #ifdef PRINT_TIMINGS // time = __rdtsc() - time; // printf("solveAndIntegrate: %d \n", time/1024); #endif } if(gScene->mMotorLink.articulation) { gTime += 0.1f; const float target = sinf(gTime) * 4.0f; // printf("target: %f\n", target); PxArticulationJointDataRC data; bool status = PxGetJointData(gScene->mMotorLink, data); PX_ASSERT(status); data.targetVel[PxArticulationAxis::eTWIST] = target; const PxVec3 boxExtents(0.5f, 0.1f, 0.5f); const float s = boxExtents.x*1.1f + fabsf(sinf(gTime))*0.5f; data.parentPose = PxTransform(PxVec3(0.0f, 0.0f, s)); data.childPose = PxTransform(PxVec3(0.0f, 0.0f, -s)); status = PxSetJointData(gScene->mMotorLink, data); PX_ASSERT(status); PX_UNUSED(status); } } void cleanupPhysics(bool /*interactive*/) { PX_DELETE(gScene); PX_RELEASE(gFoundation); printf("SnippetImmediateArticulation done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='b' || key=='B') gDrawBounds = !gDrawBounds; if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } if(gScene) { if(key>=1 && key<=7) { gSceneIndex = key-1; gScene->reset(); gScene->createScene(); } if(key=='r' || key=='R') { gScene->reset(); gScene->createScene(); } } } void renderText() { #ifdef RENDER_SNIPPET Snippets::print("Press F1 to F7 to select a scene."); #endif } int snippetMain(int, const char*const*) { printf("Immediate articulation snippet. Use these keys:\n"); printf(" P - enable/disable pause\n"); printf(" O - step simulation for one frame\n"); printf(" R - reset scene\n"); printf(" F1 to F6 - select scene\n"); printf("\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
70,838
C++
30.610442
253
0.729608
NVIDIA-Omniverse/PhysX/physx/snippets/snippetpbdinflatable/SnippetPBDInflatable.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates inflatable simulation using position-based dynamics // particle simulation. It creates an inflatable body that drops to the ground. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "extensions/PxRemeshingExt.h" #include "extensions/PxParticleExt.h" #include "extensions/PxParticleClothCooker.h" using namespace physx; using namespace ExtGpu; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxPBDParticleSystem* gParticleSystem = NULL; static PxParticleClothBuffer* gUserClothBuffer = NULL; static bool gIsRunning = true; static void initObstacles() { PxShape* shape = gPhysics->createShape(PxCapsuleGeometry(0.5f, 4.f), *gMaterial); PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.f, 5.0f, 2.f))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); shape = gPhysics->createShape(PxCapsuleGeometry(0.5f, 4.f), *gMaterial); body = gPhysics->createRigidDynamic(PxTransform(PxVec3(0.f, 5.0f, -2.f))); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); } // ----------------------------------------------------------------------------------------------------------------- static void initScene() { PxCudaContextManager* cudaContextManager = NULL; if (PxGetSuggestedCudaDeviceOrdinal(gFoundation->getErrorCallback()) >= 0) { // initialize CUDA PxCudaContextManagerDesc cudaContextManagerDesc; cudaContextManager = PxCreateCudaContextManager(*gFoundation, cudaContextManagerDesc, PxGetProfilerCallback()); if (cudaContextManager && !cudaContextManager->contextIsValid()) { cudaContextManager->release(); cudaContextManager = NULL; } } if (cudaContextManager == NULL) { PxGetFoundation().error(PxErrorCode::eINVALID_OPERATION, PX_FL, "Failed to initialize CUDA!\n"); } PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; sceneDesc.cudaContextManager = cudaContextManager; sceneDesc.staticStructure = PxPruningStructureType::eDYNAMIC_AABB_TREE; sceneDesc.flags |= PxSceneFlag::eENABLE_PCM; sceneDesc.flags |= PxSceneFlag::eENABLE_GPU_DYNAMICS; sceneDesc.broadPhaseType = PxBroadPhaseType::eGPU; sceneDesc.solverType = PxSolverType::eTGS; gScene = gPhysics->createScene(sceneDesc); } // ----------------------------------------------------------------------------------------------------------------- PxVec3 cubeVertices[] = { PxVec3(0.5f, -0.5f, -0.5f), PxVec3(0.5f, -0.5f, 0.5f), PxVec3(-0.5f, -0.5f, 0.5f), PxVec3(-0.5f, -0.5f, -0.5f), PxVec3(0.5f, 0.5f, -0.5f), PxVec3(0.5f, 0.5f, 0.5f), PxVec3(-0.5f, 0.5f, 0.5f), PxVec3(-0.5f, 0.5f, -0.5f) }; PxU32 cubeIndices[] = { 1, 2, 3, 7, 6, 5, 4, 5, 1, 5, 6, 2, 2, 6, 7, 0, 3, 7, 0, 1, 3, 4, 7, 5, 0, 4, 1, 1, 5, 2, 3, 2, 7, 4, 0, 7 }; static void projectPointsOntoSphere(PxArray<PxVec3>& triVerts, const PxVec3& center, PxReal radius) { for (PxU32 i = 0; i < triVerts.size(); ++i) { PxVec3 dir = triVerts[i] - center; dir.normalize(); triVerts[i] = center + radius * dir; } } static void createSphere(PxArray<PxVec3>& triVerts, PxArray<PxU32>& triIndices, const PxVec3& center, PxReal radius, const PxReal maxEdgeLength) { for (PxU32 i = 0; i < 8; ++i) triVerts.pushBack(cubeVertices[i] * radius + center); for (PxU32 i = 0; i < 36; ++i) triIndices.pushBack(cubeIndices[i]); projectPointsOntoSphere(triVerts, center, radius); while (PxRemeshingExt::limitMaxEdgeLength(triIndices, triVerts, maxEdgeLength, 1)) projectPointsOntoSphere(triVerts, center, radius); } static void initInflatable(PxArray<PxVec3>& verts, PxArray<PxU32>& indices, const PxReal restOffset = 0.1f, const PxReal totalInflatableMass = 10.f) { PxCudaContextManager* cudaContextManager = gScene->getCudaContextManager(); if (cudaContextManager == NULL) return; PxArray<PxVec4> vertices; vertices.resize(verts.size()); PxReal invMass = 1.0f / (totalInflatableMass / verts.size()); for (PxU32 i = 0; i < verts.size(); ++i) vertices[i] = PxVec4(verts[i], invMass); const PxU32 numParticles = vertices.size(); const PxReal stretchStiffness = 100000.f; const PxReal shearStiffness = 1000.f; const PxReal bendStiffness = 1000.f; const PxReal pressure = 1.0f; //Pressure is used to compute the target volume of the inflatable by scaling its rest volume // Cook cloth PxParticleClothCooker* cooker = PxCreateParticleClothCooker(vertices.size(), vertices.begin(), indices.size(), indices.begin(), PxParticleClothConstraint::eTYPE_HORIZONTAL_CONSTRAINT | PxParticleClothConstraint::eTYPE_VERTICAL_CONSTRAINT | PxParticleClothConstraint::eTYPE_DIAGONAL_CONSTRAINT); cooker->cookConstraints(); cooker->calculateMeshVolume(); // Apply cooked constraints to particle springs PxU32 constraintCount = cooker->getConstraintCount(); PxParticleClothConstraint* constraintBuffer = cooker->getConstraints(); PxArray<PxParticleSpring> springs; springs.reserve(constraintCount); for (PxU32 i = 0; i < constraintCount; i++) { const PxParticleClothConstraint& c = constraintBuffer[i]; PxReal stiffness = 0.0f; switch (c.constraintType) { case PxParticleClothConstraint::eTYPE_INVALID_CONSTRAINT: continue; case PxParticleClothConstraint::eTYPE_HORIZONTAL_CONSTRAINT: case PxParticleClothConstraint::eTYPE_VERTICAL_CONSTRAINT: stiffness = stretchStiffness; break; case PxParticleClothConstraint::eTYPE_DIAGONAL_CONSTRAINT: stiffness = shearStiffness; break; case PxParticleClothConstraint::eTYPE_BENDING_CONSTRAINT: stiffness = bendStiffness; break; default: PX_ASSERT("Invalid cloth constraint generated by PxParticleClothCooker"); } PxParticleSpring spring; spring.ind0 = c.particleIndexA; spring.ind1 = c.particleIndexB; spring.stiffness = stiffness; spring.damping = 0.001f; spring.length = c.length; springs.pushBack(spring); } const PxU32 numSprings = springs.size(); // Read triangles from cooker const PxU32 numTriangles = cooker->getTriangleIndicesCount() / 3; const PxU32* triangles = cooker->getTriangleIndices(); // Material setup PxPBDMaterial* defaultMat = gPhysics->createPBDMaterial(0.8f, 0.05f, 1e+6f, 0.001f, 0.5f, 0.005f, 0.05f, 0.f, 0.f); PxPBDParticleSystem *particleSystem = gPhysics->createPBDParticleSystem(*cudaContextManager); gParticleSystem = particleSystem; // General particle system setting particleSystem->setRestOffset(restOffset); particleSystem->setContactOffset(restOffset + 0.02f); particleSystem->setParticleContactOffset(restOffset + 0.02f); particleSystem->setSolidRestOffset(restOffset); particleSystem->setFluidRestOffset(0.0f); gScene->addActor(*particleSystem); // Create particles and add them to the particle system const PxU32 particlePhase = particleSystem->createPhase(defaultMat, PxParticlePhaseFlags(PxParticlePhaseFlag::eParticlePhaseSelfCollideFilter | PxParticlePhaseFlag::eParticlePhaseSelfCollide)); PxU32* phases = cudaContextManager->allocPinnedHostBuffer<PxU32>(numParticles); PxVec4* positionInvMass = cudaContextManager->allocPinnedHostBuffer<PxVec4>(numParticles); PxVec4* velocity = cudaContextManager->allocPinnedHostBuffer<PxVec4>(numParticles); for (PxU32 v = 0; v < numParticles; v++) { positionInvMass[v] = vertices[v]; velocity[v] = PxVec4(0.0f, 0.0f, 0.0f, 0.0f); phases[v] = particlePhase; } PxParticleVolumeBufferHelper* volumeBuffers = PxCreateParticleVolumeBufferHelper(1, numTriangles, cudaContextManager); //Volumes are optional. They are used to accelerate scene queries, e. g. to support picking. PxParticleClothBufferHelper* clothBuffers = PxCreateParticleClothBufferHelper(1, numTriangles, numSprings, numParticles, cudaContextManager); clothBuffers->addCloth(0.0f, cooker->getMeshVolume(), pressure, triangles, numTriangles, springs.begin(), numSprings, positionInvMass, numParticles); volumeBuffers->addVolume(0, numParticles, triangles, numTriangles); cooker->release(); ExtGpu::PxParticleBufferDesc bufferDesc; bufferDesc.maxParticles = numParticles; bufferDesc.numActiveParticles = numParticles; bufferDesc.positions = positionInvMass; bufferDesc.velocities = velocity; bufferDesc.phases = phases; bufferDesc.maxVolumes = volumeBuffers->getMaxVolumes(); bufferDesc.numVolumes = volumeBuffers->getNumVolumes(); bufferDesc.volumes = volumeBuffers->getParticleVolumes(); PxParticleClothPreProcessor* clothPreProcessor = PxCreateParticleClothPreProcessor(cudaContextManager); PxPartitionedParticleCloth output; const PxParticleClothDesc& clothDesc = clothBuffers->getParticleClothDesc(); clothPreProcessor->partitionSprings(clothDesc, output); clothPreProcessor->release(); gUserClothBuffer = physx::ExtGpu::PxCreateAndPopulateParticleClothBuffer(bufferDesc, clothDesc, output, cudaContextManager); gParticleSystem->addParticleBuffer(gUserClothBuffer); clothBuffers->release(); volumeBuffers->release(); cudaContextManager->freePinnedHostBuffer(positionInvMass); cudaContextManager->freePinnedHostBuffer(velocity); cudaContextManager->freePinnedHostBuffer(phases); } PxPBDParticleSystem* getParticleSystem() { return gParticleSystem; } PxParticleClothBuffer* getUserClothBuffer() { return gUserClothBuffer; } // ----------------------------------------------------------------------------------------------------------------- void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); initScene(); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if (pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); // Setup Cloth const PxReal totalInflatableMass = 100.0f; PxReal particleSpacing = 0.05f; PxArray<PxVec3> vertices; PxArray<PxU32> indices; createSphere(vertices, indices, PxVec3(0, 10, 0), 3, 0.25f); initInflatable(vertices, indices, particleSpacing, totalInflatableMass); initObstacles(); gScene->addActor(*PxCreatePlane(*gPhysics, PxPlane(0.f, 1.f, 0.f, 0.0f), *gMaterial)); // Setup rigid bodies const PxReal boxSize = 0.75f; const PxReal boxMass = 0.25f; PxShape* shape = gPhysics->createShape(PxBoxGeometry(0.5f * boxSize, 0.5f * boxSize, 0.5f * boxSize), *gMaterial); for (int i = 0; i < 5; ++i) { PxRigidDynamic* body = gPhysics->createRigidDynamic(PxTransform(PxVec3(i - 2.0f, 10, 0.f))); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, boxMass); gScene->addActor(*body); } shape->release(); } // --------------------------------------------------- void stepPhysics(bool /*interactive*/) { if (gIsRunning) { const PxReal dt = 1.0f / 60.0f; gScene->simulate(dt); gScene->fetchResults(true); gScene->fetchResultsParticleSystem(); } } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetPBDInflatable done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { switch(toupper(key)) { case 'P': gIsRunning = !gIsRunning; break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
14,487
C++
36.926701
212
0.728377
NVIDIA-Omniverse/PhysX/physx/snippets/snippetstandalonebroadphase/SnippetStandaloneBroadphase.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates how to use a standalone broadphase. // It creates a small custom scene (no PxScene) and creates a broadphase for the // scene objects. These objects are then updated each frame and rendered in red // when they touch another object, or green if they don't. Use the P and O keys // to pause and step the simulation one frame, to visually check the results. // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "PxImmediateMode.h" #include "foundation/PxArray.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #ifdef RENDER_SNIPPET #include "../snippetrender/SnippetCamera.h" #include "../snippetrender/SnippetRender.h" #endif using namespace physx; using namespace immediate; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static const PxU32 gNbObjects = 100; static float gTime = 0.0f; static bool gPause = false; static bool gOneFrame = false; static PxVec3 computeObjectPosition(PxU32 i) { const float coeff = float(i)*0.2f; return PxVec3( sinf(gTime*coeff*0.567f)*cosf(gTime+coeff)*3.0f, cosf(gTime*coeff*0.0917f)*cosf(gTime*1.17f+coeff)*2.0f, sinf(gTime*coeff*0.533f)*cosf(gTime*0.33f+coeff)*3.0f); } namespace { class CustomScene { public: CustomScene(); ~CustomScene(); void release(); void addGeom(const PxGeometry& geom, const PxTransform& pose); void render(); void updateObjects(); void createBroadphase(); void runBroadphase(); struct Object { PxGeometryHolder mGeom; PxTransform mPose; PxU32 mNbCollisions; }; PxArray<Object> mObjects; PxBroadPhase* mBroadphase; PxAABBManager* mAABBManager; }; CustomScene::CustomScene() : mBroadphase(NULL), mAABBManager(NULL) { } CustomScene::~CustomScene() { } void CustomScene::release() { PX_RELEASE(mAABBManager); PX_RELEASE(mBroadphase); mObjects.reset(); PX_DELETE_THIS; } void CustomScene::addGeom(const PxGeometry& geom, const PxTransform& pose) { Object obj; obj.mGeom.storeAny(geom); obj.mPose = pose; mObjects.pushBack(obj); } void CustomScene::createBroadphase() { PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); mBroadphase = PxCreateBroadPhase(bpDesc); mAABBManager = PxCreateAABBManager(*mBroadphase); const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; obj.mPose.p = computeObjectPosition(i); obj.mNbCollisions = 0; PxBounds3 bounds; PxGeometryQuery::computeGeomBounds(bounds, obj.mGeom.any(), obj.mPose); mAABBManager->addObject(i, bounds, PxGetBroadPhaseDynamicFilterGroup(i)); } runBroadphase(); } void CustomScene::runBroadphase() { PxBroadPhaseResults results; mAABBManager->update(results); for(PxU32 i=0;i<results.mNbCreatedPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; mObjects[id0].mNbCollisions++; mObjects[id1].mNbCollisions++; } for(PxU32 i=0;i<results.mNbDeletedPairs;i++) { const PxU32 id0 = results.mDeletedPairs[i].mID0; const PxU32 id1 = results.mDeletedPairs[i].mID1; PX_ASSERT(mObjects[id0].mNbCollisions); PX_ASSERT(mObjects[id1].mNbCollisions); mObjects[id0].mNbCollisions--; mObjects[id1].mNbCollisions--; } } void CustomScene::updateObjects() { if(gPause && !gOneFrame) return; gOneFrame = false; gTime += 0.001f; const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { Object& obj = mObjects[i]; obj.mPose.p = computeObjectPosition(i); PxBounds3 newBounds; PxGeometryQuery::computeGeomBounds(newBounds, obj.mGeom.any(), obj.mPose); mAABBManager->updateObject(i, &newBounds); } runBroadphase(); } void CustomScene::render() { updateObjects(); #ifdef RENDER_SNIPPET const PxU32 nbObjects = mObjects.size(); for(PxU32 i=0;i<nbObjects;i++) { const Object& obj = mObjects[i]; const PxVec3 color = obj.mNbCollisions ? PxVec3(1.0f, 0.0f, 0.0f) : PxVec3(0.0f, 1.0f, 0.0f); Snippets::renderGeoms(1, &obj.mGeom, &obj.mPose, false, color); } #endif } } static void initScene() { } static void releaseScene() { } static CustomScene* gScene = NULL; void renderScene() { if(gScene) gScene->render(); } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gScene = new CustomScene; for(PxU32 i=0;i<gNbObjects;i++) gScene->addGeom(PxBoxGeometry(PxVec3(0.1f)), PxTransform(PxVec3(0.0f, 0.0f, 0.0f))); gScene->createBroadphase(); initScene(); } void stepPhysics(bool /*interactive*/) { } void cleanupPhysics(bool /*interactive*/) { releaseScene(); PX_RELEASE(gScene); PX_RELEASE(gFoundation); printf("SnippetStandaloneBroadphase done.\n"); } void keyPress(unsigned char key, const PxTransform& /*camera*/) { if(key=='p' || key=='P') gPause = !gPause; if(key=='o' || key=='O') { gPause = true; gOneFrame = true; } } int snippetMain(int, const char*const*) { printf("Standalone broadphase snippet.\n"); #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,206
C++
24.831541
95
0.712046
NVIDIA-Omniverse/PhysX/physx/snippets/snippetimmediatemode/SnippetImmediateMode.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // **************************************************************************** // This snippet illustrates the use of PhysX immediate mode. // // It creates a number of box stacks on a plane, and if rendering, allows the // user to create new stacks and fire a ball from the camera position // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetutils/SnippetImmUtils.h" #include "foundation/PxArray.h" #include "PxImmediateMode.h" #include "extensions/PxMassProperties.h" #include "../snippetcommon/SnippetPrint.h" #include "extensions/PxRigidActorExt.h" #define USE_TGS 1 //Enables whether we want persistent state caching (contact cache, friction caching) or not. Avoiding persistency results in one-shot collision detection and zero friction //correlation but simplifies code by not longer needing to cache persistent pairs. #define WITH_PERSISTENCY 1 //Toggles between using low-level inertia computation code or using the RigidBodyExt inertia computation code. The former can operate without the need for PxRigidDynamics being constructed. #define USE_LOWLEVEL_INERTIA_COMPUTATION 1 //Toggles whether we batch constraints or not. Constraint batching is an optional process which can improve performance by grouping together independent constraints. These independent constraints //can be solved in parallel by using multiple lanes of SIMD registers. #define BATCH_CONTACTS 1 // Toggles whether we use PhysX' "immediate broadphase", or not. If we don't, a simple O(n^2) broadphase is used. #define USE_IMMEDIATE_BROADPHASE 1 // Toggles profiling for the full step. Only for Windows. #define PROFILE_STEP 0 using namespace physx; using namespace immediate; using namespace SnippetImmUtils; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static physx::PxArray<PxConstraint*>* gConstraints = NULL; static PxReal gStackZ = 10.0f; //Enable to 1 to use centimeter units instead of meter units. //Instructive to demonstrate which values used in immediate mode are unit-dependent #define USE_CM_UNITS 0 #if !USE_CM_UNITS static const PxReal gUnitScale = 1.0f; //static float cameraSpeed = 1.0f; #else static const PxReal gUnitScale = 100.0f; //static float cameraSpeed = 100.0f; #endif #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY static PxU32 gFrameIndex = 0; #endif #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE static PxAABBManager* gAABBManager = NULL; struct PersistentPair { PersistentPair() {} PersistentPair(PxU32 id0, PxU32 id1) : mID0(id0), mID1(id1) {} PX_INLINE bool operator == (const PersistentPair& a) const { return a.mID0 == mID0 && a.mID1 == mID1; } PxU32 mID0; PxU32 mID1; }; struct PersistentPairData { PxRigidActor* actor0; PxRigidActor* actor1; PxCache cache; PxU8* frictions; PxU32 nbFrictions; }; static PX_INLINE uint32_t PxComputeHash(const PersistentPair& p) { return PxComputeHash(uint64_t(p.mID0)|(uint64_t(p.mID1)<<32)); } static PxHashMap<PersistentPair, PersistentPairData>* gPersistentPairs = NULL; #else namespace { struct PersistentContactPair { PxCache cache; PxU8* frictions; PxU32 nbFrictions; }; } static PxArray<PersistentContactPair>* allContactCache = NULL; #endif #endif static TestCacheAllocator* gCacheAllocator = NULL; static TestConstraintAllocator* gConstraintAllocator = NULL; namespace { struct ContactPair { PxRigidActor* actor0; PxRigidActor* actor1; PxU32 idx0, idx1; PxU32 startContactIndex; PxU32 nbContacts; }; class TestContactRecorder : public immediate::PxContactRecorder { PxArray<ContactPair>& mContactPairs; PxArray<PxContactPoint>& mContactPoints; PxRigidActor& mActor0; PxRigidActor& mActor1; PxU32 mIdx0, mIdx1; bool mHasContacts; public: TestContactRecorder(PxArray<ContactPair>& contactPairs, PxArray<PxContactPoint>& contactPoints, PxRigidActor& actor0, PxRigidActor& actor1, PxU32 idx0, PxU32 idx1) : mContactPairs(contactPairs), mContactPoints(contactPoints), mActor0(actor0), mActor1(actor1), mIdx0(idx0), mIdx1(idx1), mHasContacts(false) { } virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 index) { PX_UNUSED(index); { ContactPair pair; pair.actor0 = &mActor0; pair.actor1 = &mActor1; pair.nbContacts = nbContacts; pair.startContactIndex = mContactPoints.size(); pair.idx0 = mIdx0; pair.idx1 = mIdx1; mContactPairs.pushBack(pair); mHasContacts = true; } for (PxU32 c = 0; c < nbContacts; ++c) { //Fill in solver-specific data that our contact gen does not produce... PxContactPoint point = contactPoints[c]; point.maxImpulse = PX_MAX_F32; point.targetVel = PxVec3(0.0f); point.staticFriction = 0.5f; point.dynamicFriction = 0.5f; point.restitution = 0.0f; point.materialFlags = 0; mContactPoints.pushBack(point); } return true; } PX_FORCE_INLINE bool hasContacts() const { return mHasContacts; } private: PX_NOCOPY(TestContactRecorder) }; } static bool generateContacts( const PxGeometryHolder& geom0, const PxGeometryHolder& geom1, PxRigidActor& actor0, PxRigidActor& actor1, PxCacheAllocator& cacheAllocator, PxArray<PxContactPoint>& contactPoints, PxArray<ContactPair>& contactPairs, PxU32 idx0, PxU32 idx1, PxCache& cache) { const PxTransform tr0 = actor0.getGlobalPose(); const PxTransform tr1 = actor1.getGlobalPose(); TestContactRecorder recorder(contactPairs, contactPoints, actor0, actor1, idx0, idx1); const PxGeometry* pxGeom0 = &geom0.any(); const PxGeometry* pxGeom1 = &geom1.any(); physx::immediate::PxGenerateContacts(&pxGeom0, &pxGeom1, &tr0, &tr1, &cache, 1, recorder, gUnitScale*0.04f, gUnitScale*0.01f, gUnitScale, cacheAllocator); return recorder.hasContacts(); } static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0)) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void updateInertia(PxRigidBody* body, PxReal density) { #if !USE_LOWLEVEL_INERTIA_COMPUTATION PX_UNUSED(density); //Compute the inertia of the rigid body using the helper function in PxRigidBodyExt PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); #else //Compute the inertia/mass of the bodies using the more low-level PxMassProperties interface //This was written for readability rather than performance. Complexity can be avoided if you know that you are dealing with a single shape body PxU32 nbShapes = body->getNbShapes(); //Keep track of an array of inertia tensors and local poses. physx::PxArray<PxMassProperties> inertias; physx::PxArray<PxTransform> localPoses; for (PxU32 a = 0; a < nbShapes; ++a) { PxShape* shape; body->getShapes(&shape, 1, a); //(1) initialize an inertia tensor based on the shape's geometry PxMassProperties inertia(shape->getGeometry()); //(2) Scale the inertia tensor based on density. If you use a single density instead of a density per-shape, this could be performed just prior to //extracting the massSpaceInertiaTensor inertia = inertia * density; inertias.pushBack(inertia); localPoses.pushBack(shape->getLocalPose()); } //(3)Sum all the inertia tensors - can be skipped if the shape count is 1 PxMassProperties inertia = PxMassProperties::sum(inertias.begin(), localPoses.begin(), inertias.size()); //(4)Get the diagonalized inertia component and frame of the mass space orientation PxQuat orient; const PxVec3 diagInertia = PxMassProperties::getMassSpaceInertia(inertia.inertiaTensor, orient); //(4) Set properties on the rigid body body->setMass(inertia.mass); body->setCMassLocalPose(PxTransform(inertia.centerOfMass, orient)); body->setMassSpaceInertiaTensor(diagInertia); #endif } /*static*/ void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for (PxU32 i = 0; i<size; i++) { for (PxU32 j = 0; j<size - i; j++) { PxTransform localTm(PxVec3(PxReal(j * 2) - PxReal(size - i), PxReal(i * 2 + 1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); updateInertia(body, 10.f); gScene->addActor(*body); } } shape->release(); } struct Triangle { PxU32 ind0, ind1, ind2; }; static PxTriangleMesh* createMeshGround() { const PxU32 gridSize = 8; const PxReal gridStep = 512.f / (gridSize-1); PxVec3 verts[gridSize * gridSize]; const PxU32 nbTriangles = 2 * (gridSize - 1) * (gridSize-1); Triangle indices[nbTriangles]; for (PxU32 a = 0; a < gridSize; ++a) { for (PxU32 b = 0; b < gridSize; ++b) { verts[a * gridSize + b] = PxVec3(-400.f + b*gridStep, 0.f, -400.f + a*gridStep); } } for (PxU32 a = 0; a < (gridSize-1); ++a) { for (PxU32 b = 0; b < (gridSize-1); ++b) { Triangle& tri0 = indices[(a * (gridSize-1) + b) * 2]; Triangle& tri1 = indices[((a * (gridSize-1) + b) * 2) + 1]; tri0.ind0 = a * gridSize + b + 1; tri0.ind1 = a * gridSize + b; tri0.ind2 = (a + 1) * gridSize + b + 1; tri1.ind0 = (a + 1) * gridSize + b + 1; tri1.ind1 = a * gridSize + b; tri1.ind2 = (a + 1) * gridSize + b; } } PxTriangleMeshDesc meshDesc; meshDesc.points.data = verts; meshDesc.points.count = gridSize * gridSize; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = nbTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = sizeof(Triangle); PxCookingParams cookingParams(gPhysics->getTolerancesScale()); PxTriangleMesh* triMesh = PxCreateTriangleMesh(cookingParams, meshDesc, gPhysics->getPhysicsInsertionCallback()); return triMesh; } #if WITH_PERSISTENCY && USE_IMMEDIATE_BROADPHASE static void createBroadPhase() { PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); PxBroadPhase* bp = PxCreateBroadPhase(bpDesc); gAABBManager = PxCreateAABBManager(*bp); gPersistentPairs = new PxHashMap<PersistentPair, PersistentPairData>; } static void releaseBroadPhase() { PxBroadPhase* bp = &gAABBManager->getBroadPhase(); PX_RELEASE(gAABBManager); PX_RELEASE(bp); delete gPersistentPairs; } #endif static void updateContactPairs() { #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE // In this simple snippet we just recreate the broadphase structure here releaseBroadPhase(); createBroadPhase(); gFrameIndex = 0; #else allContactCache->clear(); const PxU32 nbDynamic = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); const PxU32 nbStatic = gScene->getNbActors(PxActorTypeFlag::eRIGID_STATIC); const PxU32 totalPairs = (nbDynamic * (nbDynamic - 1)) / 2 + nbDynamic * nbStatic; allContactCache->resize(totalPairs); for (PxU32 a = 0; a < totalPairs; ++a) { (*allContactCache)[a].frictions = NULL; (*allContactCache)[a].nbFrictions = 0; (*allContactCache)[a].cache.mCachedData = 0; (*allContactCache)[a].cache.mCachedSize = 0; (*allContactCache)[a].cache.mManifoldFlags = 0; (*allContactCache)[a].cache.mPairData = 0; } #endif #endif } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport, PxPvdInstrumentationFlag::ePROFILE); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f)*gUnitScale; gDispatcher = PxDefaultCpuDispatcherCreate(0); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.2f); gConstraints = new physx::PxArray<PxConstraint*>(); const bool useGroundMesh = true; // Use a triangle mesh or a plane for the ground if(useGroundMesh) { PxTriangleMesh* mesh = createMeshGround(); PxTriangleMeshGeometry geom(mesh); PxRigidStatic* groundMesh = gPhysics->createRigidStatic(PxTransform(PxVec3(0, 2, 0))); PxRigidActorExt::createExclusiveShape(*groundMesh, geom, *gMaterial); gScene->addActor(*groundMesh); } else { PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0,1,0,0), *gMaterial); gScene->addActor(*groundPlane); } for (PxU32 i = 0; i<4; i++) createStack(PxTransform(PxVec3(0, 2, gStackZ -= 10.0f*gUnitScale)), 20, gUnitScale); PxRigidDynamic* ball = createDynamic(PxTransform(PxVec3(0, 20, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); PxRigidDynamic* ball2 = createDynamic(PxTransform(PxVec3(0, 24, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); PxRigidDynamic* ball3 = createDynamic(PxTransform(PxVec3(0, 27, 100)*gUnitScale), PxSphereGeometry(2 * gUnitScale), PxVec3(0, -25, -100)*gUnitScale); updateInertia(ball, 1000.f); updateInertia(ball2, 1000.f); PxD6Joint* joint = PxD6JointCreate(*gPhysics, ball, PxTransform(PxVec3(0, 4, 0)*gUnitScale), ball2, PxTransform(PxVec3(0, -2, 0)*gUnitScale)); PxD6Joint* joint2 = PxD6JointCreate(*gPhysics, ball2, PxTransform(PxVec3(0, 4, 0)*gUnitScale), ball3, PxTransform(PxVec3(0, -2, 0)*gUnitScale)); gConstraints->pushBack(joint->getConstraint()); gConstraints->pushBack(joint2->getConstraint()); gCacheAllocator = new TestCacheAllocator; gConstraintAllocator = new TestConstraintAllocator; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE createBroadPhase(); #else allContactCache = new PxArray<PersistentContactPair>; #endif #endif updateContactPairs(); } void stepPhysics(bool /*interactive*/) { #if PROFILE_STEP PxU64 time = __rdtsc(); #endif gCacheAllocator->reset(); gConstraintAllocator->release(); const PxU32 nbStatics = gScene->getNbActors(PxActorTypeFlag::eRIGID_STATIC); const PxU32 nbDynamics = gScene->getNbActors(PxActorTypeFlag::eRIGID_DYNAMIC); const PxU32 totalActors = nbDynamics + nbStatics; PxArray<ContactPair> activeContactPairs; PxArray<PxContactPoint> contactPoints; activeContactPairs.reserve(4 * totalActors); PxArray<PxActor*> actors(totalActors); PxArray<PxBounds3> shapeBounds(totalActors+1); PxArray<PxGeometryHolder> mGeometries(totalActors); #if USE_TGS PxArray<PxTGSSolverBodyVel> bodies(totalActors); PxArray<PxTGSSolverBodyData> bodyData(totalActors); PxArray<PxTGSSolverBodyTxInertia> txInertia(totalActors); PxArray<PxTransform> globalPoses(totalActors); #else PxArray<PxSolverBody> bodies(totalActors); PxArray<PxSolverBodyData> bodyData(totalActors); #endif #if USE_IMMEDIATE_BROADPHASE && !WITH_PERSISTENCY PxArray<PxBpIndex> handles(totalActors); PxArray<PxBpFilterGroup> groups(totalActors); PxArray<float> distances(totalActors); #endif gScene->getActors(PxActorTypeFlag::eRIGID_DYNAMIC, actors.begin(), nbDynamics); gScene->getActors(PxActorTypeFlag::eRIGID_STATIC, actors.begin() + nbDynamics, nbStatics); #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY gFrameIndex++; #endif //Now do collision detection...Brute force every dynamic against every dynamic/static for (PxU32 a = 0; a < totalActors; ++a) { PxRigidActor* actor = actors[a]->is<PxRigidActor>(); PxShape* shape; actor->getShapes(&shape, 1); //Compute the AABBs. We inflate these by 2cm margins shapeBounds[a] = PxShapeExt::getWorldBounds(*shape, *actor, 1.f); shapeBounds[a].minimum -= PxVec3(0.02f)*gUnitScale; shapeBounds[a].maximum += PxVec3(0.02f)*gUnitScale; mGeometries[a].storeAny(shape->getGeometry()); #if USE_IMMEDIATE_BROADPHASE #if WITH_PERSISTENCY if(gFrameIndex==1) { const PxBpFilterGroup group = a < nbDynamics ? PxGetBroadPhaseDynamicFilterGroup(a) : PxGetBroadPhaseStaticFilterGroup(); gAABBManager->addObject(a, shapeBounds[a], group); } else if(a < nbDynamics) { gAABBManager->updateObject(a, &shapeBounds[a]); } #else handles[a] = a; distances[a]= 0.0f; if(a < nbDynamics) groups[a] = PxGetBroadPhaseDynamicFilterGroup(a); else groups[a] = PxGetBroadPhaseStaticFilterGroup(); #endif #endif } #if USE_IMMEDIATE_BROADPHASE { PxBroadPhaseResults results; #if WITH_PERSISTENCY gAABBManager->update(results); const PxU32 nbCreatedPairs = results.mNbCreatedPairs; for(PxU32 i=0;i<nbCreatedPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; const PersistentPair currentPair(id0, id1); PersistentPairData data; data.actor0 = actors[id0]->is<PxRigidActor>(); data.actor1 = actors[id1]->is<PxRigidActor>(); data.frictions = NULL; data.nbFrictions = 0; data.cache = PxCache(); bool b = gPersistentPairs->insert(currentPair, data); PX_ASSERT(b); PX_UNUSED(b); } const PxU32 nbDeletedPairs = results.mNbDeletedPairs; for(PxU32 i=0;i<nbDeletedPairs;i++) { const PxU32 id0 = results.mDeletedPairs[i].mID0; const PxU32 id1 = results.mDeletedPairs[i].mID1; const PersistentPair currentPair(id0, id1); PxHashMap<PersistentPair, PersistentPairData>::Entry removedEntry; bool b = gPersistentPairs->erase(currentPair, removedEntry); PX_ASSERT(b); PX_UNUSED(b); } #else PxBroadPhaseDesc bpDesc(PxBroadPhaseType::eABP); PxBroadPhase* bp = PxCreateBroadPhase(bpDesc); const PxBroadPhaseUpdateData updateData(handles.begin(), totalActors, NULL, 0, NULL, 0, shapeBounds.begin(), groups.begin(), distances.begin(), totalActors); bp->update(results, updateData); const PxU32 nbPairs = results.mNbCreatedPairs; for(PxU32 i=0;i<nbPairs;i++) { const PxU32 id0 = results.mCreatedPairs[i].mID0; const PxU32 id1 = results.mCreatedPairs[i].mID1; ContactPair pair; pair.actor0 = actors[id0]->is<PxRigidActor>(); pair.actor1 = actors[id1]->is<PxRigidActor>(); pair.idx0 = id0; pair.idx1 = id1; activeContactPairs.pushBack(pair); } PX_RELEASE(bp); #endif } #else { //Broad phase for active pairs... for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dyn0 = actors[a]->is<PxRigidDynamic>(); for (PxU32 b = a + 1; b < totalActors; ++b) { PxRigidActor* actor1 = actors[b]->is<PxRigidActor>(); if (shapeBounds[a].intersects(shapeBounds[b])) { ContactPair pair; pair.actor0 = dyn0; pair.actor1 = actor1; pair.idx0 = a; pair.idx1 = b; activeContactPairs.pushBack(pair); } #if WITH_PERSISTENCY else { const PxU32 startIndex = a == 0 ? 0 : (a * totalActors) - (a * (a + 1)) / 2; PersistentContactPair& persistentData = (*allContactCache)[startIndex + (b - a - 1)]; //No collision detection performed at all so clear contact cache and friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; persistentData.cache = PxCache(); } #endif } } } #endif #if USE_IMMEDIATE_BROADPHASE && WITH_PERSISTENCY const PxU32 nbActivePairs = gPersistentPairs->size(); activeContactPairs.forceSize_Unsafe(0); contactPoints.reserve(4 * nbActivePairs); for(PxHashMap<PersistentPair, PersistentPairData>::Iterator iter = gPersistentPairs->getIterator(); !iter.done(); ++iter) { const PxU32 id0 = iter->first.mID0; const PxU32 id1 = iter->first.mID1; PxRigidActor* dyn0 = iter->second.actor0; const PxGeometryHolder& holder0 = mGeometries[id0]; PxRigidActor* actor1 = iter->second.actor1; const PxGeometryHolder& holder1 = mGeometries[id1]; if (!generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, id0, id1, iter->second.cache)) { //Contact generation run but no touches found so clear cached friction data iter->second.frictions = NULL; iter->second.nbFrictions = 0; } } #else const PxU32 nbActivePairs = activeContactPairs.size(); ContactPair* activePairs = activeContactPairs.begin(); activeContactPairs.forceSize_Unsafe(0); contactPoints.reserve(4 * nbActivePairs); for (PxU32 a = 0; a < nbActivePairs; ++a) { const ContactPair& pair = activePairs[a]; PxRigidActor* dyn0 = pair.actor0; const PxGeometryHolder& holder0 = mGeometries[pair.idx0]; PxRigidActor* actor1 = pair.actor1; const PxGeometryHolder& holder1 = mGeometries[pair.idx1]; #if WITH_PERSISTENCY const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; PersistentContactPair& persistentData = (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)]; if (!generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, pair.idx0, pair.idx1, persistentData.cache)) { //Contact generation run but no touches found so clear cached friction data persistentData.frictions = NULL; persistentData.nbFrictions = 0; } #else PxCache cache; generateContacts(holder0, holder1, *dyn0, *actor1, *gCacheAllocator, contactPoints, activeContactPairs, pair.idx0, pair.idx1, cache); #endif } #endif const PxReal dt = 1.f / 60.f; const PxReal invDt = 60.f; const PxU32 nbPositionIterations = 4; const PxU32 nbVelocityIterations = 1; #if USE_TGS const PxReal stepDt = dt/PxReal(nbPositionIterations); const PxReal invStepDt = invDt * PxReal(nbPositionIterations); #endif const PxVec3 gravity(0.f, -9.8f* gUnitScale, 0.f); //Construct solver bodies for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dyn = actors[a]->is<PxRigidDynamic>(); immediate::PxRigidBodyData data; data.linearVelocity = dyn->getLinearVelocity(); data.angularVelocity = dyn->getAngularVelocity(); data.invMass = dyn->getInvMass(); data.invInertia = dyn->getMassSpaceInvInertiaTensor(); data.body2World = dyn->getGlobalPose(); data.maxDepenetrationVelocity = dyn->getMaxDepenetrationVelocity(); data.maxContactImpulse = dyn->getMaxContactImpulse(); data.linearDamping = dyn->getLinearDamping(); data.angularDamping = dyn->getAngularDamping(); data.maxLinearVelocitySq = 100.f*100.f*gUnitScale*gUnitScale; data.maxAngularVelocitySq = 7.f*7.f; #if USE_TGS physx::immediate::PxConstructSolverBodiesTGS(&data, &bodies[a], &txInertia[a], &bodyData[a], 1, gravity, dt); globalPoses[a] = data.body2World; #else physx::immediate::PxConstructSolverBodies(&data, &bodyData[a], 1, gravity, dt); #endif dyn->userData = reinterpret_cast<void*>(size_t(a)); } //Construct static bodies for (PxU32 a = nbDynamics; a < totalActors; ++a) { PxRigidStatic* sta = actors[a]->is<PxRigidStatic>(); #if USE_TGS physx::immediate::PxConstructStaticSolverBodyTGS(sta->getGlobalPose(), bodies[a], txInertia[a], bodyData[a]); globalPoses[a] = sta->getGlobalPose(); #else physx::immediate::PxConstructStaticSolverBody(sta->getGlobalPose(), bodyData[a]); #endif sta->userData = reinterpret_cast<void*>(size_t(a)); } PxArray<PxSolverConstraintDesc> descs(activeContactPairs.size() + gConstraints->size()); for (PxU32 a = 0; a < activeContactPairs.size(); ++a) { PxSolverConstraintDesc& desc = descs[a]; ContactPair& pair = activeContactPairs[a]; //Set body pointers and bodyData idxs #if USE_TGS desc.tgsBodyA = &bodies[pair.idx0]; desc.tgsBodyB = &bodies[pair.idx1]; #else desc.bodyA = &bodies[pair.idx0]; desc.bodyB = &bodies[pair.idx1]; #endif desc.bodyADataIndex = pair.idx0; desc.bodyBDataIndex = pair.idx1; desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; //Cache pointer to our contact data structure and identify which type of constraint this is. We'll need this later after batching. //If we choose not to perform batching and instead just create a single header per-pair, then this would not be necessary because //the constraintDescs would not have been reordered desc.constraint = reinterpret_cast<PxU8*>(&pair); desc.constraintLengthOver16 = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } for (PxU32 a = 0; a < gConstraints->size(); ++a) { PxConstraint* constraint = (*gConstraints)[a]; PxSolverConstraintDesc& desc = descs[activeContactPairs.size() + a]; PxRigidActor* actor0, *actor1; constraint->getActors(actor0, actor1); const PxU32 id0 = PxU32(size_t(actor0->userData)); const PxU32 id1 = PxU32(size_t(actor1->userData)); #if USE_TGS desc.tgsBodyA = &bodies[id0]; desc.tgsBodyB = &bodies[id1]; #else desc.bodyA = &bodies[id0]; desc.bodyB = &bodies[id1]; #endif desc.bodyADataIndex = PxU16(id0); desc.bodyBDataIndex = PxU16(id1); desc.linkIndexA = PxSolverConstraintDesc::RIGID_BODY; desc.linkIndexB = PxSolverConstraintDesc::RIGID_BODY; desc.constraint = reinterpret_cast<PxU8*>(constraint); desc.constraintLengthOver16 = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } PxArray<PxConstraintBatchHeader> headers(descs.size()); PxArray<PxReal> contactForces(contactPoints.size()); //Technically, you can batch the contacts and joints all at once using a single call but doing so mixes them in the orderedDescs array, which means that it is impossible to //batch all contact or all joint dispatches into a single call. While we don't do this in this snippet (we instead process a single header at a time), our approach could be extended to //dispatch all contact headers at once if that was necessary. #if BATCH_CONTACTS PxArray<PxSolverConstraintDesc> tempOrderedDescs(descs.size()); physx::PxArray<PxSolverConstraintDesc>& orderedDescs = tempOrderedDescs; #if USE_TGS //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraintsTGS(descs.begin(), activeContactPairs.size(), bodies.begin(), nbDynamics, headers.begin(), orderedDescs.begin()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraintsTGS(descs.begin() + activeContactPairs.size(), gConstraints->size(), bodies.begin(), nbDynamics, headers.begin() + nbContactHeaders, orderedDescs.begin() + activeContactPairs.size()); #else //1 batch the contacts const PxU32 nbContactHeaders = physx::immediate::PxBatchConstraints(descs.begin(), activeContactPairs.size(), bodies.begin(), nbDynamics, headers.begin(), orderedDescs.begin()); //2 batch the joints... const PxU32 nbJointHeaders = physx::immediate::PxBatchConstraints(descs.begin() + activeContactPairs.size(), gConstraints->size(), bodies.begin(), nbDynamics, headers.begin() + nbContactHeaders, orderedDescs.begin() + activeContactPairs.size()); #endif #else physx::PxArray<PxSolverConstraintDesc>& orderedDescs = descs; //We are bypassing the constraint batching so we create dummy PxConstraintBatchHeaders const PxU32 nbContactHeaders = activeContactPairs.size(); const PxU32 nbJointHeaders = gConstraints->size(); for (PxU32 i = 0; i < nbContactHeaders; ++i) { PxConstraintBatchHeader& hdr = headers[i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eCONTACT_CONSTRAINT; } for (PxU32 i = 0; i < nbJointHeaders; ++i) { PxConstraintBatchHeader& hdr = headers[nbContactHeaders+i]; hdr.startIndex = i; hdr.stride = 1; hdr.constraintType = PxSolverConstraintDesc::eJOINT_CONSTRAINT; } #endif const PxU32 totalHeaders = nbContactHeaders + nbJointHeaders; headers.forceSize_Unsafe(totalHeaders); //1 - Create all the contact constraints. We do this by looping over all the headers and, for each header, constructing the PxSolverContactDesc objects, then creating that contact constraint. //We could alternatively create all the PxSolverContactDesc objects in a single pass, then create batch create that constraint for (PxU32 i = 0; i < nbContactHeaders; ++i) { PxConstraintBatchHeader& header = headers[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eCONTACT_CONSTRAINT); #if USE_TGS PxTGSSolverContactDesc contactDescs[4]; #else PxSolverContactDesc contactDescs[4]; #endif #if WITH_PERSISTENCY const ContactPair* pairs[4]; #endif for (PxU32 a = 0; a < header.stride; ++a) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else PxSolverContactDesc& contactDesc = contactDescs[a]; #endif PxMemZero(&contactDesc, sizeof(contactDesc)); //Extract the contact pair that we saved in this structure earlier. const ContactPair& pair = *reinterpret_cast<const ContactPair*>(constraintDesc.constraint); #if WITH_PERSISTENCY pairs[a] = &pair; #endif #if USE_TGS contactDesc.body0 = constraintDesc.tgsBodyA; contactDesc.body1 = constraintDesc.tgsBodyB; contactDesc.bodyData0 = &bodyData[constraintDesc.bodyADataIndex]; contactDesc.bodyData1 = &bodyData[constraintDesc.bodyBDataIndex]; contactDesc.body0TxI = &txInertia[constraintDesc.bodyADataIndex]; contactDesc.body1TxI = &txInertia[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. contactDesc.bodyFrame0 = globalPoses[constraintDesc.bodyADataIndex]; contactDesc.bodyFrame1 = globalPoses[constraintDesc.bodyBDataIndex]; #else contactDesc.body0 = constraintDesc.bodyA; contactDesc.body1 = constraintDesc.bodyB; contactDesc.data0 = &bodyData[constraintDesc.bodyADataIndex]; contactDesc.data1 = &bodyData[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. contactDesc.bodyFrame0 = contactDesc.data0->body2World; contactDesc.bodyFrame1 = contactDesc.data1->body2World; #endif contactDesc.contactForces = &contactForces[pair.startContactIndex]; contactDesc.contacts = &contactPoints[pair.startContactIndex]; contactDesc.numContacts = pair.nbContacts; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE const PersistentPair currentPair(pair.idx0, pair.idx1); const PxHashMap<PersistentPair, PersistentPairData>::Entry* e = gPersistentPairs->find(currentPair); contactDesc.frictionPtr = e->second.frictions; contactDesc.frictionCount = PxU8(e->second.nbFrictions); #else const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; contactDesc.frictionPtr = (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].frictions; contactDesc.frictionCount = PxU8((*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].nbFrictions); #endif #else contactDesc.frictionPtr = NULL; contactDesc.frictionCount = 0; #endif contactDesc.shapeInteraction = NULL; contactDesc.maxCCDSeparation = PX_MAX_F32; contactDesc.bodyState0 = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; contactDesc.bodyState1 = pair.actor1->is<PxRigidDynamic>() ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; contactDesc.desc = &constraintDesc; contactDesc.invMassScales.angular0 = contactDesc.invMassScales.angular1 = contactDesc.invMassScales.linear0 = contactDesc.invMassScales.linear1 = 1.f; } #if USE_TGS immediate::PxCreateContactConstraintsTGS(&header, 1, contactDescs, *gConstraintAllocator, invStepDt, invDt, -2.f * gUnitScale, 0.04f * gUnitScale, 0.025f * gUnitScale); #else immediate::PxCreateContactConstraints(&header, 1, contactDescs, *gConstraintAllocator, invDt, -2.f * gUnitScale, 0.04f * gUnitScale, 0.025f * gUnitScale); #endif #if WITH_PERSISTENCY for (PxU32 a = 0; a < header.stride; ++a) { //Cache friction information... #if USE_TGS PxTGSSolverContactDesc& contactDesc = contactDescs[a]; #else PxSolverContactDesc& contactDesc = contactDescs[a]; #endif //PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; const ContactPair& pair = *pairs[a]; #if USE_IMMEDIATE_BROADPHASE const PersistentPair currentPair(pair.idx0, pair.idx1); PxHashMap<PersistentPair, PersistentPairData>::Entry* e = const_cast<PxHashMap<PersistentPair, PersistentPairData>::Entry*>(gPersistentPairs->find(currentPair)); e->second.frictions = contactDesc.frictionPtr; e->second.nbFrictions = contactDesc.frictionCount; #else const PxU32 startIndex = pair.idx0 == 0 ? 0 : (pair.idx0 * totalActors) - (pair.idx0 * (pair.idx0 + 1)) / 2; (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].frictions = contactDesc.frictionPtr; (*allContactCache)[startIndex + (pair.idx1 - pair.idx0 - 1)].nbFrictions = contactDesc.frictionCount; #endif } #endif } for (PxU32 i = nbContactHeaders; i < totalHeaders; ++i) { PxConstraintBatchHeader& header = headers[i]; PX_ASSERT(header.constraintType == PxSolverConstraintDesc::eJOINT_CONSTRAINT); { #if USE_TGS PxTGSSolverConstraintPrepDesc jointDescs[4]; #else PxSolverConstraintPrepDesc jointDescs[4]; #endif PxConstraint* constraints[4]; header.startIndex += activeContactPairs.size(); for (PxU32 a = 0; a < header.stride; ++a) { PxSolverConstraintDesc& constraintDesc = orderedDescs[header.startIndex + a]; //Extract the contact pair that we saved in this structure earlier. PxConstraint& constraint = *reinterpret_cast<PxConstraint*>(constraintDesc.constraint); constraints[a] = &constraint; #if USE_TGS PxTGSSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.tgsBodyA; jointDesc.body1 = constraintDesc.tgsBodyB; jointDesc.bodyData0 = &bodyData[constraintDesc.bodyADataIndex]; jointDesc.bodyData1 = &bodyData[constraintDesc.bodyBDataIndex]; jointDesc.body0TxI = &txInertia[constraintDesc.bodyADataIndex]; jointDesc.body1TxI = &txInertia[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. jointDesc.bodyFrame0 = globalPoses[constraintDesc.bodyADataIndex]; jointDesc.bodyFrame1 = globalPoses[constraintDesc.bodyBDataIndex]; #else PxSolverConstraintPrepDesc& jointDesc = jointDescs[a]; jointDesc.body0 = constraintDesc.bodyA; jointDesc.body1 = constraintDesc.bodyB; jointDesc.data0 = &bodyData[constraintDesc.bodyADataIndex]; jointDesc.data1 = &bodyData[constraintDesc.bodyBDataIndex]; //This may seem redundant but the bodyFrame is not defined by the bodyData object when using articulations. This //example does not use articulations. jointDesc.bodyFrame0 = jointDesc.data0->body2World; jointDesc.bodyFrame1 = jointDesc.data1->body2World; #endif PxRigidActor* actor0, *actor1; constraint.getActors(actor0, actor1); jointDesc.bodyState0 = PxSolverConstraintPrepDescBase::eDYNAMIC_BODY; jointDesc.bodyState1 = actor1 == NULL ? PxSolverConstraintPrepDescBase::eSTATIC_BODY : actor1->is<PxRigidDynamic>() ? PxSolverConstraintPrepDescBase::eDYNAMIC_BODY : PxSolverConstraintPrepDescBase::eSTATIC_BODY; jointDesc.desc = &constraintDesc; jointDesc.invMassScales.angular0 = jointDesc.invMassScales.angular1 = jointDesc.invMassScales.linear0 = jointDesc.invMassScales.linear1 = 1.f; jointDesc.writeback = NULL; constraint.getBreakForce(jointDesc.linBreakForce, jointDesc.angBreakForce); jointDesc.minResponseThreshold = constraint.getMinResponseThreshold(); jointDesc.disablePreprocessing = !!(constraint.getFlags() & PxConstraintFlag::eDISABLE_PREPROCESSING); jointDesc.improvedSlerp = !!(constraint.getFlags() & PxConstraintFlag::eIMPROVED_SLERP); jointDesc.driveLimitsAreForces = !!(constraint.getFlags() & PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES); } #if USE_TGS immediate::PxCreateJointConstraintsWithShadersTGS(&header, 1, constraints, jointDescs, *gConstraintAllocator, stepDt, dt, invStepDt, invDt, 1.f); #else immediate::PxCreateJointConstraintsWithShaders(&header, 1, constraints, jointDescs, *gConstraintAllocator, dt, invDt); #endif } } #if USE_TGS immediate::PxSolveConstraintsTGS(headers.begin(), headers.size(), orderedDescs.begin(), bodies.begin(), txInertia.begin(), nbDynamics, nbPositionIterations, nbVelocityIterations, stepDt, invStepDt); immediate::PxIntegrateSolverBodiesTGS(bodies.begin(), txInertia.begin(), globalPoses.begin(), nbDynamics, dt); for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dynamic = actors[a]->is<PxRigidDynamic>(); const PxTGSSolverBodyVel& body = bodies[a]; dynamic->setLinearVelocity(body.linearVelocity); dynamic->setAngularVelocity(body.angularVelocity); dynamic->setGlobalPose(globalPoses[a]); } #else //Solve all the constraints produced earlier. Intermediate motion linear/angular velocity buffers are filled in. These contain intermediate delta velocity information that is used //the PxIntegrateSolverBody PxArray<PxVec3> motionLinearVelocity(nbDynamics); PxArray<PxVec3> motionAngularVelocity(nbDynamics); //Zero the bodies array. This buffer contains the delta velocities and are accumulated during the simulation. For correct behavior, it is vital //that this buffer is zeroed. PxMemZero(bodies.begin(), bodies.size() * sizeof(PxSolverBody)); immediate::PxSolveConstraints(headers.begin(), headers.size(), orderedDescs.begin(), bodies.begin(), motionLinearVelocity.begin(), motionAngularVelocity.begin(), nbDynamics, nbPositionIterations, nbVelocityIterations); immediate::PxIntegrateSolverBodies(bodyData.begin(), bodies.begin(), motionLinearVelocity.begin(), motionAngularVelocity.begin(), nbDynamics, dt); for (PxU32 a = 0; a < nbDynamics; ++a) { PxRigidDynamic* dynamic = actors[a]->is<PxRigidDynamic>(); const PxSolverBodyData& data = bodyData[a]; dynamic->setLinearVelocity(data.linearVelocity); dynamic->setAngularVelocity(data.angularVelocity); dynamic->setGlobalPose(data.body2World); } #endif #if PROFILE_STEP time = __rdtsc() - time; printf("Time: %d\n", PxU32(time/1024)); #endif } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } delete gCacheAllocator; delete gConstraintAllocator; #if WITH_PERSISTENCY #if USE_IMMEDIATE_BROADPHASE releaseBroadPhase(); #else delete allContactCache; #endif #endif PX_RELEASE(gFoundation); printf("SnippetImmediateMode done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f*gUnitScale), camera.rotate(PxVec3(0, 0, -1)) * 200*gUnitScale); updateContactPairs(); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
41,062
C++
34.399138
249
0.741245
NVIDIA-Omniverse/PhysX/physx/snippets/snippetdeformablemesh/SnippetDeformableMesh.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet shows how to use deformable meshes in PhysX. // **************************************************************************** #include <ctype.h> #include <vector> #include "PxPhysicsAPI.h" // temporary disable this snippet, cannot work without rendering we cannot include GL directly #ifdef RENDER_SNIPPET #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" #include "../snippetrender/SnippetRender.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxTriangleMesh* gMesh = NULL; static PxRigidStatic* gActor = NULL; static const PxU32 gGridSize = 8; static const PxReal gGridStep = 512.0f / PxReal(gGridSize-1); static float gTime = 0.0f; static PxRigidDynamic* createDynamic(const PxTransform& t, const PxGeometry& geometry, const PxVec3& velocity=PxVec3(0), PxReal density=1.0f) { PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, t, geometry, *gMaterial, density); dynamic->setLinearVelocity(velocity); gScene->addActor(*dynamic); return dynamic; } static void createStack(const PxTransform& t, PxU32 size, PxReal halfExtent) { PxShape* shape = gPhysics->createShape(PxBoxGeometry(halfExtent, halfExtent, halfExtent), *gMaterial); for(PxU32 i=0; i<size;i++) { for(PxU32 j=0;j<size-i;j++) { PxTransform localTm(PxVec3(PxReal(j*2) - PxReal(size-i), PxReal(i*2+1), 0) * halfExtent); PxRigidDynamic* body = gPhysics->createRigidDynamic(t.transform(localTm)); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); } } shape->release(); } struct Triangle { PxU32 ind0, ind1, ind2; }; static void updateVertices(PxVec3* verts, float amplitude=0.0f) { const PxU32 gridSize = gGridSize; const PxReal gridStep = gGridStep; for(PxU32 a=0; a<gridSize; a++) { const float coeffA = float(a)/float(gridSize); for(PxU32 b=0; b<gridSize; b++) { const float coeffB = float(b)/float(gridSize); const float y = 20.0f + sinf(coeffA*PxTwoPi)*cosf(coeffB*PxTwoPi)*amplitude; verts[a * gridSize + b] = PxVec3(-400.0f + b*gridStep, y, -400.0f + a*gridStep); } } } static PxTriangleMesh* createMeshGround(const PxCookingParams& params) { const PxU32 gridSize = gGridSize; PxVec3 verts[gridSize * gridSize]; const PxU32 nbTriangles = 2 * (gridSize - 1) * (gridSize-1); Triangle indices[nbTriangles]; updateVertices(verts); for (PxU32 a = 0; a < (gridSize-1); ++a) { for (PxU32 b = 0; b < (gridSize-1); ++b) { Triangle& tri0 = indices[(a * (gridSize-1) + b) * 2]; Triangle& tri1 = indices[((a * (gridSize-1) + b) * 2) + 1]; tri0.ind0 = a * gridSize + b + 1; tri0.ind1 = a * gridSize + b; tri0.ind2 = (a + 1) * gridSize + b + 1; tri1.ind0 = (a + 1) * gridSize + b + 1; tri1.ind1 = a * gridSize + b; tri1.ind2 = (a + 1) * gridSize + b; } } PxTriangleMeshDesc meshDesc; meshDesc.points.data = verts; meshDesc.points.count = gridSize * gridSize; meshDesc.points.stride = sizeof(PxVec3); meshDesc.triangles.count = nbTriangles; meshDesc.triangles.data = indices; meshDesc.triangles.stride = sizeof(Triangle); PxTriangleMesh* triMesh = PxCreateTriangleMesh(params, meshDesc, gPhysics->getPhysicsInsertionCallback()); return triMesh; } void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(), true, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); PxCookingParams cookingParams(gPhysics->getTolerancesScale()); if(0) { cookingParams.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH33); } else { cookingParams.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34); cookingParams.midphaseDesc.mBVH34Desc.quantized = false; } // We need to disable the mesh cleaning part so that the vertex mapping remains untouched. cookingParams.meshPreprocessParams = PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH; PxTriangleMesh* mesh = createMeshGround(cookingParams); gMesh = mesh; PxTriangleMeshGeometry geom(mesh); PxRigidStatic* groundMesh = gPhysics->createRigidStatic(PxTransform(PxVec3(0, 2, 0))); gActor = groundMesh; PxShape* shape = gPhysics->createShape(geom, *gMaterial); { shape->setContactOffset(0.02f); // A negative rest offset helps to avoid jittering when the deformed mesh moves away from objects resting on it. shape->setRestOffset(-0.5f); } groundMesh->attachShape(*shape); gScene->addActor(*groundMesh); createStack(PxTransform(PxVec3(0,22,0)), 10, 2.0f); } PxBounds3 gBounds; void debugRender() { const PxVec3 c = gBounds.getCenter(); const PxVec3 e = gBounds.getExtents(); PxVec3 pts[8]; pts[0] = c + PxVec3(-e.x, -e.y, e.z); pts[1] = c + PxVec3(-e.x, e.y, e.z); pts[2] = c + PxVec3( e.x, e.y, e.z); pts[3] = c + PxVec3( e.x, -e.y, e.z); pts[4] = c + PxVec3(-e.x, -e.y, -e.z); pts[5] = c + PxVec3(-e.x, e.y, -e.z); pts[6] = c + PxVec3( e.x, e.y, -e.z); pts[7] = c + PxVec3( e.x, -e.y, -e.z); std::vector<PxVec3> gContactVertices; struct AddQuad { static void func(std::vector<PxVec3>& v, const PxVec3* pts_, PxU32 index0, PxU32 index1, PxU32 index2, PxU32 index3) { v.push_back(pts_[index0]); v.push_back(pts_[index1]); v.push_back(pts_[index1]); v.push_back(pts_[index2]); v.push_back(pts_[index2]); v.push_back(pts_[index3]); v.push_back(pts_[index3]); v.push_back(pts_[index0]); } }; AddQuad::func(gContactVertices, pts, 0, 1, 2, 3); AddQuad::func(gContactVertices, pts, 4, 5, 6, 7); AddQuad::func(gContactVertices, pts, 0, 1, 5, 4); AddQuad::func(gContactVertices, pts, 2, 3, 7, 6); glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glDisable(GL_LIGHTING); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &gContactVertices[0]); glDrawArrays(GL_LINES, 0, GLint(gContactVertices.size())); glDisableClientState(GL_VERTEX_ARRAY); glEnable(GL_LIGHTING); } void stepPhysics(bool /*interactive*/) { { PxVec3* verts = gMesh->getVerticesForModification(); gTime += 0.01f; updateVertices(verts, sinf(gTime)*20.0f); { // unsigned long long time = __rdtsc(); gBounds = gMesh->refitBVH(); // time = __rdtsc() - time; // printf("Time: %d\n", int(time)); } // Reset filtering to tell the broadphase about the new mesh bounds. gScene->resetFiltering(*gActor); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetDeformableMesh done.\n"); } void keyPress(unsigned char key, const PxTransform& camera) { switch(toupper(key)) { case ' ': createDynamic(camera, PxSphereGeometry(3.0f), camera.rotate(PxVec3(0,0,-1))*200, 3.0f); break; } } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; } #else int snippetMain(int, const char*const*) { return 0; } #endif
10,192
C++
29.426866
141
0.705455
NVIDIA-Omniverse/PhysX/physx/snippets/snippetrackjoint/SnippetRackJoint.cpp
// Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. // **************************************************************************** // This snippet illustrates simple use of rack & pinion joints // **************************************************************************** #include <ctype.h> #include "PxPhysicsAPI.h" #include "../snippetcommon/SnippetPrint.h" #include "../snippetcommon/SnippetPVD.h" #include "../snippetutils/SnippetUtils.h" using namespace physx; static PxDefaultAllocator gAllocator; static PxDefaultErrorCallback gErrorCallback; static PxFoundation* gFoundation = NULL; static PxPhysics* gPhysics = NULL; static PxDefaultCpuDispatcher* gDispatcher = NULL; static PxScene* gScene = NULL; static PxMaterial* gMaterial = NULL; static PxPvd* gPvd = NULL; static PxRigidDynamic* createGearWithBoxes(PxPhysics& sdk, const PxBoxGeometry& boxGeom, const PxTransform& transform, PxMaterial& material, int nbShapes) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); PxMat33 m(PxIdentity); for(int i=0;i<nbShapes;i++) { const float coeff = float(i)/float(nbShapes); const float angle = PxPi * 0.5f * coeff; PxShape* shape = sdk.createShape(boxGeom, material, true); const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); shape->setLocalPose(localPose); actor->attachShape(*shape); } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRigidDynamic* createRackWithBoxes(PxPhysics& sdk, const PxTransform& transform, PxMaterial& material, int nbTeeth, float rackLength) { PxRigidDynamic* actor = sdk.createRigidDynamic(transform); { const PxBoxGeometry boxGeom(rackLength*0.5f, 0.25f, 0.25f); PxShape* shape = sdk.createShape(boxGeom, material, true); actor->attachShape(*shape); } PxMat33 m(PxIdentity); const float angle = PxPi * 0.25f; const PxReal cos = cosf(angle); const PxReal sin = sinf(angle); m[0][0] = m[1][1] = cos; m[0][1] = sin; m[1][0] = -sin; PxTransform localPose; localPose.p = PxVec3(0.0f); localPose.q = PxQuat(m); const float offset = rackLength / float(nbTeeth); localPose.p.x = (offset - rackLength)*0.5f; for(int i=0;i<nbTeeth;i++) { const PxBoxGeometry boxGeom(0.75f, 0.75f, 0.25f); PxShape* shape = sdk.createShape(boxGeom, material, true); shape->setLocalPose(localPose); actor->attachShape(*shape); localPose.p.x += offset; } PxRigidBodyExt::updateMassAndInertia(*actor, 1.0f); return actor; } static PxRevoluteJoint* gHinge0 = NULL; void initPhysics(bool /*interactive*/) { gFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate(PVD_HOST, 5425, 10); gPvd->connect(*transport,PxPvdInstrumentationFlag::eALL); gPhysics = PxCreatePhysics(PX_PHYSICS_VERSION, *gFoundation, PxTolerancesScale(),true, gPvd); PxInitExtensions(*gPhysics, gPvd); PxSceneDesc sceneDesc(gPhysics->getTolerancesScale()); sceneDesc.gravity = PxVec3(0.0f, -9.81f, 0.0f); gDispatcher = PxDefaultCpuDispatcherCreate(2); sceneDesc.cpuDispatcher = gDispatcher; sceneDesc.filterShader = PxDefaultSimulationFilterShader; gScene = gPhysics->createScene(sceneDesc); PxPvdSceneClient* pvdClient = gScene->getScenePvdClient(); if(pvdClient) { pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONSTRAINTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_CONTACTS, true); pvdClient->setScenePvdFlag(PxPvdSceneFlag::eTRANSMIT_SCENEQUERIES, true); } gMaterial = gPhysics->createMaterial(0.5f, 0.5f, 0.6f); const float velocityTarget = 0.5f; const float radius = 3.0f; const float rackLength = 3.0f*10.0f; const int nbPinionTeeth = int(radius)*4; // 'radius' teeth for PI/2 const int nbRackTeeth = 5*3; const PxBoxGeometry boxGeom0(radius, radius, 0.5f); const PxVec3 boxPos0(0.0f, 10.0f, 0.0f); const PxVec3 boxPos1(0.0f, 10.0f+radius+1.5f, 0.0f); PxRigidDynamic* actor0 = createGearWithBoxes(*gPhysics, boxGeom0, PxTransform(boxPos0), *gMaterial, int(radius)); gScene->addActor(*actor0); PxRigidDynamic* actor1 = createRackWithBoxes(*gPhysics, PxTransform(boxPos1), *gMaterial, nbRackTeeth, rackLength); gScene->addActor(*actor1); const PxQuat x2z = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), PxVec3(0.0f, 0.0f, 1.0f)); PxRevoluteJoint* hinge = PxRevoluteJointCreate(*gPhysics, NULL, PxTransform(boxPos0, x2z), actor0, PxTransform(PxVec3(0.0f), x2z)); PxPrismaticJoint* prismatic = PxPrismaticJointCreate(*gPhysics, NULL, PxTransform(boxPos1), actor1, PxTransform(PxVec3(0.0f))); if(1) { hinge->setDriveVelocity(velocityTarget); hinge->setRevoluteJointFlag(PxRevoluteJointFlag::eDRIVE_ENABLED, true); gHinge0 = hinge; } PxRackAndPinionJoint* rackJoint = PxRackAndPinionJointCreate(*gPhysics, actor0, PxTransform(PxVec3(0.0f), x2z), actor1, PxTransform(PxVec3(0.0f))); rackJoint->setJoints(hinge, prismatic); rackJoint->setData(nbRackTeeth, nbPinionTeeth, rackLength); } void stepPhysics(bool /*interactive*/) { if(gHinge0) { static float globalTime = 0.0f; globalTime += 1.0f/60.0f; const float velocityTarget = cosf(globalTime)*3.0f; gHinge0->setDriveVelocity(velocityTarget); } gScene->simulate(1.0f/60.0f); gScene->fetchResults(true); } void cleanupPhysics(bool /*interactive*/) { PX_RELEASE(gScene); PX_RELEASE(gDispatcher); PxCloseExtensions(); PX_RELEASE(gPhysics); if(gPvd) { PxPvdTransport* transport = gPvd->getTransport(); gPvd->release(); gPvd = NULL; PX_RELEASE(transport); } PX_RELEASE(gFoundation); printf("SnippetRackJoint done.\n"); } int snippetMain(int, const char*const*) { #ifdef RENDER_SNIPPET extern void renderLoop(); renderLoop(); #else static const PxU32 frameCount = 100; initPhysics(false); for(PxU32 i=0; i<frameCount; i++) stepPhysics(false); cleanupPhysics(false); #endif return 0; }
7,702
C++
31.918803
154
0.726954
NVIDIA-Omniverse/PhysX/physx/snippets/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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