This commit is contained in:
2025-11-28 23:13:44 +05:30
commit a3a8e79709
7360 changed files with 1156074 additions and 0 deletions

View File

@ -0,0 +1,151 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 "Planet.h"
#include "RendererMemoryMacros.h"
#include "foundation/PxPlane.h"
#include "foundation/PxAssert.h"
#include "PxTkRandom.h"
PlanetMesh::PlanetMesh() :
mNbVerts (0),
mNbTris (0),
mVerts (NULL),
mIndices (NULL)
{
}
PlanetMesh::~PlanetMesh()
{
DELETEARRAY(mIndices);
DELETEARRAY(mVerts);
}
PxU8 PlanetMesh::checkCulling(const PxVec3& center, PxU32 index0, PxU32 index1, PxU32 index2) const
{
const PxPlane tmp(mVerts[index0], mVerts[index1], mVerts[index2]);
return tmp.distance(center)>0.0f;
}
void PlanetMesh::generate(const PxVec3& center, PxF32 radius, PxU32 nbX, PxU32 nbY)
{
DELETEARRAY(mIndices);
DELETEARRAY(mVerts);
mNbVerts = 6*nbX*nbY;
mVerts = new PxVec3[mNbVerts];
PxU32 index=0;
for(PxU32 i=0;i<6;i++)
{
for(PxU32 y=0;y<nbY;y++)
{
const PxF32 coeffY = float(y)/float(nbY-1);
for(PxU32 x=0;x<nbX;x++)
{
const PxF32 coeffX = float(x)/float(nbX-1);
const PxF32 xr = coeffX-0.5f;
const PxF32 yr = coeffY-0.5f;
PxVec3 offset;
if(i==0)
{
offset = PxVec3(xr, yr, 0.5f);
}
else if(i==1)
{
offset = PxVec3(xr, yr, -0.5f);
}
else if(i==2)
{
offset = PxVec3(xr, 0.5f, yr);
}
else if(i==3)
{
offset = PxVec3(xr, -0.5f, yr);
}
else if(i==4)
{
offset = PxVec3(0.5f, xr, yr);
}
else
{
offset = PxVec3(-0.5f, xr, yr);
}
offset.normalize();
const float h = sinf(offset.z*10.0f)*sinf(offset.x*10.0f)*sinf(offset.y*10.0f)*2.0f;
offset *= (radius + h);
mVerts[index++] = center + offset;
}
}
}
PX_ASSERT(index==mNbVerts);
mNbTris = 6*(nbX-1)*(nbY-1)*2;
mIndices = new PxU32[mNbTris*3];
PxU32 offset = 0;
PxU32 baseOffset = 0;
for(PxU32 i=0;i<6;i++)
{
for(PxU32 y=0;y<nbY-1;y++)
{
for(PxU32 x=0;x<nbX-1;x++)
{
const PxU32 index0a = baseOffset + x;
const PxU32 index1a = baseOffset + x + nbX;
const PxU32 index2a = baseOffset + x + nbX + 1;
const PxU32 index0b = index0a;
const PxU32 index1b = index2a;
const PxU32 index2b = baseOffset + x + 1;
{
const PxU8 c = checkCulling(center, index0a, index1a, index2a);
mIndices[offset] = index0a;
mIndices[offset+1+c] = index1a;
mIndices[offset+2-c] = index2a;
offset+=3;
}
{
const PxU8 c = checkCulling(center, index0b, index1b, index2b);
mIndices[offset] = index0b;
mIndices[offset+1+c] = index1b;
mIndices[offset+2-c] = index2b;
offset+=3;
}
}
baseOffset += nbX;
}
baseOffset += nbX;
}
PX_ASSERT(offset==mNbTris*3);
}

View File

@ -0,0 +1,58 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 PLANET_H
#define PLANET_H
#include "SampleAllocator.h"
#include "foundation/PxVec3.h"
class PlanetMesh
{
public:
PlanetMesh();
~PlanetMesh();
void generate(const PxVec3& center, PxF32 radius, PxU32 nbX, PxU32 nbY);
PX_FORCE_INLINE PxU32 getNbVerts() const { return mNbVerts; }
PX_FORCE_INLINE PxU32 getNbTris() const { return mNbTris; }
PX_FORCE_INLINE const PxVec3* getVerts() const { return mVerts; }
PX_FORCE_INLINE const PxU32* getIndices() const { return mIndices; }
protected:
PxU32 mNbVerts;
PxU32 mNbTris;
PxVec3* mVerts;
PxU32* mIndices;
PxU8 checkCulling(const PxVec3& center, PxU32 index0, PxU32 index1, PxU32 index2) const;
};
#endif

View File

@ -0,0 +1,463 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 "characterkinematic/PxControllerManager.h"
#include "PxPhysicsAPI.h"
#include "SampleCustomGravity.h"
#include "SampleCustomGravityCameraController.h"
#include "SampleCustomGravityInputEventIds.h"
#include "SampleUtils.h"
#include "SampleCommandLine.h"
#include "SampleConsole.h"
#include "SampleAllocatorSDKClasses.h"
#include "RendererMemoryMacros.h"
#include "RenderMaterial.h"
#include "RenderBaseActor.h"
#include "RenderPhysX3Debug.h"
#include "characterkinematic/PxBoxController.h"
#include "characterkinematic/PxCapsuleController.h"
REGISTER_SAMPLE(SampleCustomGravity, "SampleCustomGravity")
#define PLANET_RADIUS 20.0f
//#define PLANET_RADIUS 100.0f
//#define PLANET_RADIUS 10.0f
using namespace SampleFramework;
using namespace SampleRenderer;
///////////////////////////////////////////////////////////////////////////////
SampleCustomGravity::SampleCustomGravity(PhysXSampleApplication& app) :
PhysXSample (app),
mCCTCamera (NULL),
#ifdef USE_BOX_CONTROLLER
mBoxController (NULL),
#else
mCapsuleController (NULL),
#endif
mControllerManager (NULL),
mSnowMaterial (NULL),
mPlatformMaterial (NULL),
mDrawInvisibleWalls (false),
mEnableCCTDebugRender (false)
{
mValidTouchedTriangle = false;
mCreateGroundPlane = false;
//mStepperType = FIXED_STEPPER;
mControllerRadius = 0.5f;
mControllerInitialPosition = PxExtendedVec3(0.0, PLANET_RADIUS + 4.0f, 0.0);
// mUseDebugStepper = true;
mRenderActor = NULL;
mPlanet.mPos = PxVec3(0.0f, 0.0f, 0.0f);
mPlanet.mRadius = PLANET_RADIUS;
}
SampleCustomGravity::~SampleCustomGravity()
{
}
///////////////////////////////////////////////////////////////////////////////
void SampleCustomGravity::customizeSample(SampleSetup& setup)
{
setup.mName = "SampleCustomGravity";
}
///////////////////////////////////////////////////////////////////////////////
extern PxF32 gJumpForce;
static void gJump(Console* console, const char* text, void* userData)
{
if(!text)
{
console->out("Usage: jump <float>");
return;
}
const float val = (float)::atof(text);
// shdfnd::printFormatted("value: %f\n", val);
gJumpForce = val;
}
// PT: TODO: use PhysXSampleApplication helper for this
static PxRigidActor* createRigidActor( PxScene& scene, PxPhysics& physics,
const PxTransform& pose, const PxGeometry& geometry, PxMaterial& material,
const PxFilterData* fd, const PxReal* density, const PxReal* mass, PxU32 flags)
{
const bool isDynamic = (density && *density) || (mass && *mass);
PxRigidActor* actor = isDynamic ? static_cast<PxRigidActor*>(physics.createRigidDynamic(pose))
: static_cast<PxRigidActor*>(physics.createRigidStatic(pose));
if(!actor)
return NULL;
PxShape* shape = PxRigidActorExt::createExclusiveShape(*actor, geometry, material);
if(!shape)
{
actor->release();
return NULL;
}
if(fd)
shape->setSimulationFilterData(*fd);
if(isDynamic)
{
PxRigidDynamic* body = static_cast<PxRigidDynamic*>(actor);
{
if(density)
PxRigidBodyExt::updateMassAndInertia(*body, *density);
else
PxRigidBodyExt::setMassAndUpdateInertia(*body, *mass);
}
}
scene.addActor(*actor);
return actor;
}
static PxRigidActor* createBox( PxScene& scene, PxPhysics& physics,
const PxTransform& pose, const PxVec3& dimensions, const PxReal density, PxMaterial& m, const PxFilterData* fd, PxU32 flags)
{
return createRigidActor(scene, physics, pose, PxBoxGeometry(dimensions), m, fd, &density, NULL, flags);
}
KinematicPlatform* SampleCustomGravity::createPlatform(PxU32 nbPts, const PxVec3* pts, const PxQuat& localRot, const PxVec3& extents, PxF32 platformSpeed, PxF32 rotationSpeed)
{
const PxTransform idt = PxTransform(PxIdentity);
PxRigidDynamic* platformActor = (PxRigidDynamic*)::createBox(getActiveScene(), getPhysics(), idt, extents, 1.0f, getDefaultMaterial(), NULL, 0);
/*#ifdef CCT_ON_BRIDGES
platformActor->setName(gPlatformName);
#endif*/
platformActor->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true);
PxShape* platformShape = NULL;
platformActor->getShapes(&platformShape, 1);
PX_ASSERT(platformShape);
createRenderObjectFromShape(platformActor, platformShape, mPlatformMaterial);
/*#ifdef PLATFORMS_AS_OBSTACLES
// platformShape->userData = NULL;
renderActor->setPhysicsShape(NULL);
#endif*/
return mPlatformManager.createPlatform(nbPts, pts, idt, localRot, platformActor, platformSpeed, rotationSpeed, LOOP_WRAP);
}
#include "RendererDirectionalLightDesc.h"
void SampleCustomGravity::onInit()
{
if(getConsole())
getConsole()->addCmd("jump", gJump);
mCreateCudaCtxManager = true;
PhysXSample::onInit();
PxSceneWriteLock scopedLock(*mScene);
mApplication.setMouseCursorHiding(true);
mApplication.setMouseCursorRecentering(true);
// getRenderer()->setAmbientColor(RendererColor(100, 100, 100));
// getRenderer()->setAmbientColor(RendererColor(255, 255, 255));
getRenderer()->setAmbientColor(RendererColor(160, 160, 160));
if(0)
{
RendererDirectionalLightDesc lightdesc;
lightdesc.intensity = 1;
lightdesc.color = RendererColor(250, 125, 64, 255);
lightdesc.direction = PxVec3(4.0f, 5.0f, 3.0f);
lightdesc.direction.normalizeFast();
RendererLight* newLight = getRenderer()->createLight(lightdesc);
mApplication.registerLight(newLight);
}
// some colors for the rendering
mSnowMaterial = SAMPLE_NEW(RenderMaterial)(*getRenderer(), PxVec3(0.90f, 0.90f, 1.00f), 1.0f, false, 0, NULL);
mRenderMaterials.push_back(mSnowMaterial);
{
RAWTexture data;
data.mName = "divingBoardFloor_diffuse.dds";
RenderTexture* platformTexture = createRenderTextureFromRawTexture(data);
mPlatformMaterial = SAMPLE_NEW(RenderMaterial)(*getRenderer(), PxVec3(1.0f, 1.0f, 1.0f), 1.0f, false, 0xffffffff, platformTexture);
mRenderMaterials.push_back(mPlatformMaterial);
}
buildScene();
// PhysX
mControllerManager = PxCreateControllerManager(getActiveScene());
#ifdef USE_BOX_CONTROLLER
mBoxController = createCharacter(mControllerInitialPosition);
#else
mCapsuleController = createCharacter(mControllerInitialPosition);
#endif
#ifdef USE_BOX_CONTROLLER
mCCTCamera = SAMPLE_NEW(SampleCustomGravityCameraController)(*mBoxController, *this);
#else
mCCTCamera = SAMPLE_NEW(SampleCustomGravityCameraController)(*mCapsuleController, *this);
#endif
setCameraController(mCCTCamera);
mCCTCamera->setView(0,0);
}
void SampleCustomGravity::onShutdown()
{
{
PxSceneWriteLock scopedLock(*mScene);
DELETESINGLE(mCCTCamera);
mControllerManager->release();
mPlatformManager.release();
}
PhysXSample::onShutdown();
}
void SampleCustomGravity::helpRender(PxU32 x, PxU32 y, PxU8 textAlpha)
{
SampleRenderer::Renderer* renderer = getRenderer();
const PxU32 yInc = 18;
const PxReal scale = 0.5f;
const PxReal shadowOffset = 6.0f;
const RendererColor textColor(255, 255, 255, textAlpha);
const bool isMouseSupported = getApplication().getPlatform()->getSampleUserInput()->mouseSupported();
const bool isPadSupported = getApplication().getPlatform()->getSampleUserInput()->gamepadSupported();
const char* msg;
if (isMouseSupported && isPadSupported)
renderer->print(x, y += yInc, "Use mouse or right stick to rotate the camera", scale, shadowOffset, textColor);
else if (isMouseSupported)
renderer->print(x, y += yInc, "Use mouse to rotate the camera", scale, shadowOffset, textColor);
else if (isPadSupported)
renderer->print(x, y += yInc, "Use right stick to rotate the camera", scale, shadowOffset, textColor);
if (isPadSupported)
renderer->print(x, y += yInc, "Use left stick to move",scale, shadowOffset, textColor);
msg = mApplication.inputMoveInfoMsg("Press "," to move", CAMERA_MOVE_FORWARD,CAMERA_MOVE_BACKWARD, CAMERA_MOVE_LEFT, CAMERA_MOVE_RIGHT);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to move fast", CAMERA_SHIFT_SPEED, -1);
if(msg)
renderer->print(x, y += yInc, msg, scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to jump", CAMERA_JUMP,-1);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
msg = mApplication.inputInfoMsg("Press "," to throw an object", SPAWN_DEBUG_OBJECT, -1);
if(msg)
renderer->print(x, y += yInc, msg,scale, shadowOffset, textColor);
}
void SampleCustomGravity::descriptionRender(PxU32 x, PxU32 y, PxU8 textAlpha)
{
bool print=(textAlpha!=0.0f);
if(print)
{
Renderer* renderer = getRenderer();
const PxU32 yInc = 24;
const PxReal scale = 0.5f;
const PxReal shadowOffset = 6.0f;
const RendererColor textColor(255, 255, 255, textAlpha);
char line0[256]="This sample demonstrates the application of custom gravity to each object";
char line1[256]="in the scene, rather than relying on a global gravity value. In this scene";
char line2[256]="gravity is applied as a force directed along the unit vector connecting the";
char line3[256]="object position to the center of the planet. The setup and run-time control";
char line4[256]="of the PhysX kinematic character controller is also presented.";
renderer->print(x, y+=yInc, line0, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line1, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line2, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line3, scale, shadowOffset, textColor);
renderer->print(x, y+=yInc, line4, scale, shadowOffset, textColor);
}
}
void SampleCustomGravity::onTickPreRender(PxReal dtime)
{
mValidTouchedTriangle = false;
PhysXSample::onTickPreRender(dtime);
if(!mPause)
{
#ifdef USE_BOX_CONTROLLER
const PxExtendedVec3& newPos = mBoxController->getPosition();
#else
const PxExtendedVec3& newPos = mCapsuleController->getPosition();
#endif
PxTransform tr = PxTransform(PxIdentity);
tr.p.x = float(newPos.x);
tr.p.y = float(newPos.y);
tr.p.z = float(newPos.z);
tr.q = PxQuat(mCCTCamera->mTest);
mRenderActor->setTransform(tr);
}
// PhysXSample::onTickPreRender(dtime);
}
void SampleCustomGravity::onTickPostRender(PxF32 dtime)
{
PhysXSample::onTickPostRender(dtime);
RenderPhysX3Debug* renderer = getDebugRenderer();
// PT: add CCT's internal debug rendering
if(mEnableCCTDebugRender)
{
mControllerManager->setDebugRenderingFlags(PxControllerDebugRenderFlag::eALL);
PxRenderBuffer& renderBuffer = mControllerManager->getRenderBuffer();
renderer->update(renderBuffer);
renderBuffer.clear();
}
else
{
mControllerManager->setDebugRenderingFlags(PxControllerDebugRenderFlag::eNONE);
}
if(mValidTouchedTriangle)
{
PxVec3 normal = (mTouchedTriangle[0] - mTouchedTriangle[1]).cross(mTouchedTriangle[0] - mTouchedTriangle[2]);
normal.normalize();
normal *= 0.01f;
renderer->addTriangle(mTouchedTriangle[0]+normal, mTouchedTriangle[1]+normal, mTouchedTriangle[2]+normal, 0x00ff00ff);
}
if(1)
{
PxU32 size = mCCTCamera->mNbRecords;
if(size>1)
{
const PxVec3* pos = mCCTCamera->mHistory;
for(PxU32 i=0;i<size-1;i++)
renderer->addLine(pos[i], pos[i+1], RendererColor(255,0,255));
}
}
PxController* ctrl;
#ifdef USE_BOX_CONTROLLER
ctrl = mBoxController;
#else
ctrl = mCapsuleController;
#endif
if(1 && ctrl)
{
const PxVec3 currentPos = toVec3(ctrl->getPosition());
PxVec3 up;
mPlanet.getUpVector(up, currentPos);
const float length = 2.0f;
const PxMat33& rot = mCCTCamera->mTest;
renderer->addLine(currentPos, currentPos + rot.column0 * length, RendererColor(255,0,0));
renderer->addLine(currentPos, currentPos + rot.column1 * length, RendererColor(0,255,0));
renderer->addLine(currentPos, currentPos + rot.column2 * length, RendererColor(0,0,255));
const PxVec3 groundPos = toVec3(ctrl->getFootPosition());
renderer->addLine(groundPos, groundPos + rot.column0 * length, RendererColor(255,0,0));
renderer->addLine(groundPos, groundPos + rot.column1 * length, RendererColor(0,255,0));
renderer->addLine(groundPos, groundPos + rot.column2 * length, RendererColor(0,0,255));
}
}
void SampleCustomGravity::onSubstep(float dtime)
{
mPlatformManager.updatePhysicsPlatforms(dtime);
PxSceneWriteLock scopedLock(*mScene);
PxU32 nb = (PxU32)mDebugActors.size();
for(PxU32 i=0;i<nb;i++)
{
PxRigidDynamic* dyna = mDebugActors[i];
// Don't accumulate forces in sleeping objects, else they explode when waking up
if(dyna->isSleeping())
continue;
PxTransform pose = dyna->getGlobalPose();
PxVec3 up;
mPlanet.getUpVector(up, pose.p);
// const PxVec3 force = -up * 9.81f;
// const PxVec3 force = -up * 9.81f * 0.25f;
const PxVec3 force = -up * 9.81f * 4.0f;
// const PxVec3 force = -up * 9.81f * 10.0f;
dyna->addForce(force, PxForceMode::eACCELERATION, false);
// dyna->addForce(force, PxForceMode::eIMPULSE);
}
}
void SampleCustomGravity::onPointerInputEvent(const SampleFramework::InputEvent& ie, physx::PxU32 x, physx::PxU32 y, physx::PxReal dx, physx::PxReal dy, bool val)
{
if((ie.m_Id == RAYCAST_HIT) && val)
{
PxRaycastBuffer hit;
getActiveScene().raycast(getCamera().getPos()+getCamera().getViewDir(),getCamera().getViewDir(),1,hit);
shdfnd::printFormatted("hits: %p\n",hit.block.shape);
}
}
void SampleCustomGravity::onDebugObjectCreation(PxRigidDynamic* actor)
{
PxTransform pose;
pose.p = mCCTCamera->mTarget;
pose.q = PxQuat(PxIdentity);
actor->setGlobalPose(pose);
mDebugActors.push_back(actor);
}
PxU32 SampleCustomGravity::getDebugObjectTypes() const
{
return DEBUG_OBJECT_BOX | DEBUG_OBJECT_SPHERE | DEBUG_OBJECT_CAPSULE | DEBUG_OBJECT_CONVEX;
}

View File

@ -0,0 +1,157 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 SAMPLE_CUSTOM_GRAVITY_H
#define SAMPLE_CUSTOM_GRAVITY_H
#include "PhysXSample.h"
#include "characterkinematic/PxController.h" // for PxUserControllerHitReport
#include "PxShape.h"
#include "KinematicPlatform.h"
namespace physx
{
class PxBoxController;
class PxCapsuleController;
class PxControllerManager;
}
class SampleCustomGravityCameraController;
//#define CONTACT_OFFSET 0.01f
#define CONTACT_OFFSET 0.1f
#define STEP_OFFSET 0.1f
#define SLOPE_LIMIT 0.0f
#define INVISIBLE_WALLS_HEIGHT 0.0f
#define MAX_JUMP_HEIGHT 0.0f
//#define USE_BOX_CONTROLLER
struct Planet
{
PxVec3 mPos;
float mRadius;
PX_FORCE_INLINE void getUpVector(PxVec3& up, const PxVec3& pos) const
{
up = pos - mPos;
up.normalize();
}
};
PxMat33 fromTo(const PxVec3& from, const PxVec3& to);
class SampleCustomGravity : public PhysXSample, public PxUserControllerHitReport
{
public:
SampleCustomGravity(PhysXSampleApplication& app);
virtual ~SampleCustomGravity();
///////////////////////////////////////////////////////////////////////////////
// Implements SampleApplication
virtual void onInit();
virtual void onInit(bool restart) { onInit(); }
virtual void onShutdown();
virtual void onTickPreRender(PxReal dtime);
virtual void onTickPostRender(PxF32 dtime);
virtual void onDigitalInputEvent(const SampleFramework::InputEvent& , bool val);
virtual void onPointerInputEvent(const SampleFramework::InputEvent& ie, physx::PxU32 x, physx::PxU32 y, physx::PxReal dx, physx::PxReal dy, bool val);
virtual void collectInputEvents(std::vector<const SampleFramework::InputEvent*>& inputEvents);
///////////////////////////////////////////////////////////////////////////////
// Implements PhysXSampleApplication
virtual void helpRender(PxU32 x, PxU32 y, PxU8 textAlpha);
virtual void descriptionRender(PxU32 x, PxU32 y, PxU8 textAlpha);
virtual void customizeSample(SampleSetup&);
virtual void customizeSceneDesc(PxSceneDesc&);
virtual void onSubstep(float dtime);
virtual void onDebugObjectCreation(PxRigidDynamic* actor);
virtual PxU32 getDebugObjectTypes() const;
// virtual PxReal getDebugObjectsVelocity() const { return 0;}
///////////////////////////////////////////////////////////////////////////////
// Implements PxUserControllerHitReport
virtual void onShapeHit(const PxControllerShapeHit& hit);
virtual void onControllerHit(const PxControllersHit& hit) {}
virtual void onObstacleHit(const PxControllerObstacleHit& hit) {}
///////////////////////////////////////////////////////////////////////////////
// dynamics
void resetScene();
///////////////////////////////////////////////////////////////////////////////
void buildScene();
///////////////////////////////////////////////////////////////////////////////
PxVec3 mTouchedTriangle[3];
bool mValidTouchedTriangle;
///////////////////////////////////////////////////////////////////////////////
std::vector<PxRigidDynamic*> mDebugActors;
KinematicPlatformManager mPlatformManager;
Planet mPlanet;
// Camera and Controller
SampleCustomGravityCameraController* mCCTCamera;
#ifdef USE_BOX_CONTROLLER
PxBoxController* mBoxController;
#else
PxCapsuleController* mCapsuleController;
#endif
PxControllerManager* mControllerManager;
RenderBaseActor* mRenderActor;
PxExtendedVec3 mControllerInitialPosition;
PxReal mControllerRadius;
#ifdef USE_BOX_CONTROLLER
PxBoxController* createCharacter(const PxExtendedVec3& position);
#else
PxCapsuleController* createCharacter(const PxExtendedVec3& position);
#endif
///////////////////////////////////////////////////////////////////////////////
// rendering
RenderMaterial* mSnowMaterial;
RenderMaterial* mPlatformMaterial;
bool mDrawInvisibleWalls;
bool mEnableCCTDebugRender;
// Platforms
KinematicPlatform* createPlatform(PxU32 nbPts, const PxVec3* pts, const PxQuat& localRot, const PxVec3& extents, PxF32 platformSpeed, PxF32 rotationSpeed);
};
#endif

View File

@ -0,0 +1,124 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxPhysicsAPI.h"
#include "SampleCustomGravity.h"
#include "Planet.h"
#include "PsMathUtils.h"
using namespace PxToolkit;
static const PxReal gPlatformSpeed = 4.0f;
static const PxReal gGlobalScale = 1.0f;
void SampleCustomGravity::buildScene()
{
if(1)
{
importRAWFile("planet.raw", 2.0f);
}
if(0)
{
// const PxU32 tesselationLevel = 10;
const PxU32 tesselationLevel = 32;
PlanetMesh planet;
planet.generate(mPlanet.mPos, mPlanet.mRadius, tesselationLevel, tesselationLevel);
RAWMesh data;
data.mName = "planet";
data.mTransform = PxTransform(PxIdentity);
data.mNbVerts = planet.getNbVerts();
data.mVerts = planet.getVerts();
data.mUVs = 0;
data.mMaterialID = 0;
data.mNbFaces = planet.getNbTris();
data.mIndices = planet.getIndices();
char buffer[256];
sprintf(buffer, "PlanetMesh%.2f", mPlanet.mRadius);
// char srcMetaFile[512]; srcMetaFile[0]=0;
// GetOutputFileManager().getFilePath(buffer, srcMetaFile);
// setFilename(srcMetaFile);
setFilename(getSampleMediaFilename(buffer));
newMesh(data);
}
if(0)
{
const PxF32 rotationSpeed = 1.0f;
BasicRandom random(42);
const PxU32 nbPlatforms = 20;
for(PxU32 i=0;i<nbPlatforms;i++)
{
PxVec3 up;
random.unitRandomPt(up);
up.normalize();
const PxQuat q = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), up);
PxVec3 pts[2];
pts[0] = up * mPlanet.mRadius;
pts[1] = up * (mPlanet.mRadius + 5.0f);
KinematicPlatform* platform = createPlatform(2, pts, q, gGlobalScale * PxVec3(0.1f, 4.0f, 1.0f), gPlatformSpeed, rotationSpeed);
platform->setT(PxF32(i)/PxF32(nbPlatforms-1));
}
}
if(0)
{
const PxF32 radius = 25.0f;
const PxF32 platformSpeed = 4.0f;
// const PxF32 platformSpeed = 10.0f;
const PxU32 nbPts = 100;
PxVec3 pts[100];
for(PxU32 i=0;i<nbPts;i++)
{
const float angle = 6.283185f * float(i)/float(nbPts-1);
const float s = sinf(angle);
const float c = cosf(angle);
pts[i] = radius * PxVec3(s, c, 0.0f);
}
const PxReal rotationSpeed = 0.0f;
const PxVec3 up(0.0f, 0.0f, 1.0f);
const PxQuat q = PxShortestRotation(PxVec3(1.0f, 0.0f, 0.0f), up);
KinematicPlatform* platform = createPlatform(nbPts, pts, q, gGlobalScale * PxVec3(1.0f, 1.0f, 1.0f), platformSpeed, rotationSpeed);
const PxF32 travelTime = platform->getTravelTime();
platform->setRotationSpeed(-6.283185f/travelTime);
}
}

View File

@ -0,0 +1,388 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 "SampleCustomGravity.h"
#include "SampleCustomGravityCameraController.h"
#include "SampleCCTJump.h"
#include "PxRigidDynamic.h"
#include "geometry/PxCapsuleGeometry.h"
#include "PxShape.h"
#include <SampleBaseInputEventIds.h>
#include <SampleUserInputIds.h>
#include <SampleUserInputDefines.h>
#include <SamplePlatform.h>
using namespace SampleRenderer;
using namespace SampleFramework;
/*static*/ PxF32 gJumpForce = 30.0f;
static Jump gJump;
SampleCustomGravityCameraController::SampleCustomGravityCameraController(PxController& controlled, SampleCustomGravity& base) :
mCCT (controlled),
mBase (base),
mTargetYaw (0.0f-PxPi/2),
mTargetPitch (0.0f),
mPitchMin (-PxHalfPi),
mPitchMax (PxHalfPi),
mGamepadPitchInc (0.0f),
mGamepadYawInc (0.0f),
mGamepadForwardInc (0.0f),
mGamepadLateralInc (0.0f),
mSensibility (0.001f),
mFwd (false),
mBwd (false),
mLeft (false),
mRight (false),
mKeyShiftDown (false),
mRunningSpeed (25.0f),
mWalkingSpeed (2.5f)
{
mForward = PxVec3(0);
mRightV = PxVec3(0);
mTarget = PxVec3(0);
mNbRecords = 0;
mTest = PxMat33(PxIdentity);
}
void SampleCustomGravityCameraController::collectInputEvents(std::vector<const SampleFramework::InputEvent*>& inputEvents)
{
//digital keyboard events
DIGITAL_INPUT_EVENT_DEF(CAMERA_MOVE_FORWARD, SCAN_CODE_FORWARD, SCAN_CODE_FORWARD, SCAN_CODE_FORWARD );
DIGITAL_INPUT_EVENT_DEF(CAMERA_MOVE_BACKWARD, SCAN_CODE_BACKWARD, SCAN_CODE_BACKWARD, SCAN_CODE_BACKWARD );
DIGITAL_INPUT_EVENT_DEF(CAMERA_MOVE_LEFT, SCAN_CODE_LEFT, SCAN_CODE_LEFT, SCAN_CODE_LEFT );
DIGITAL_INPUT_EVENT_DEF(CAMERA_MOVE_RIGHT, SCAN_CODE_RIGHT, SCAN_CODE_RIGHT, SCAN_CODE_RIGHT );
DIGITAL_INPUT_EVENT_DEF(CAMERA_SHIFT_SPEED, SCAN_CODE_LEFT_SHIFT, OSXKEY_SHIFT, LINUXKEY_SHIFT );
DIGITAL_INPUT_EVENT_DEF(CAMERA_JUMP, SCAN_CODE_SPACE, OSXKEY_SPACE, LINUXKEY_SPACE );
//analog mouse events
ANALOG_INPUT_EVENT_DEF(CAMERA_GAMEPAD_ROTATE_LEFT_RIGHT, GAMEPAD_ROTATE_SENSITIVITY, GAMEPAD_RIGHT_STICK_X, GAMEPAD_RIGHT_STICK_X, LINUXKEY_UNKNOWN );
ANALOG_INPUT_EVENT_DEF(CAMERA_GAMEPAD_ROTATE_UP_DOWN, GAMEPAD_ROTATE_SENSITIVITY, GAMEPAD_RIGHT_STICK_Y, GAMEPAD_RIGHT_STICK_Y, LINUXKEY_UNKNOWN );
ANALOG_INPUT_EVENT_DEF(CAMERA_GAMEPAD_MOVE_LEFT_RIGHT, GAMEPAD_DEFAULT_SENSITIVITY, GAMEPAD_LEFT_STICK_X, GAMEPAD_LEFT_STICK_X, LINUXKEY_UNKNOWN );
ANALOG_INPUT_EVENT_DEF(CAMERA_GAMEPAD_MOVE_FORWARD_BACK, GAMEPAD_DEFAULT_SENSITIVITY, GAMEPAD_LEFT_STICK_Y, GAMEPAD_LEFT_STICK_Y, LINUXKEY_UNKNOWN );
//digital gamepad events
DIGITAL_INPUT_EVENT_DEF(CAMERA_JUMP, GAMEPAD_SOUTH, GAMEPAD_SOUTH, LINUXKEY_UNKNOWN );
}
void SampleCustomGravityCameraController::onDigitalInputEvent(const SampleFramework::InputEvent& ie, bool val)
{
if(val)
{
if(ie.m_Id == CAMERA_MOVE_FORWARD) mFwd = true;
else if(ie.m_Id == CAMERA_MOVE_BACKWARD) mBwd = true;
else if(ie.m_Id == CAMERA_MOVE_LEFT) mLeft = true;
else if(ie.m_Id == CAMERA_MOVE_RIGHT) mRight = true;
else if(ie.m_Id == CAMERA_SHIFT_SPEED) mKeyShiftDown = true;
else if(ie.m_Id == CAMERA_JUMP) gJump.startJump(gJumpForce);
}
else
{
if(ie.m_Id == CAMERA_MOVE_FORWARD) mFwd = false;
else if(ie.m_Id == CAMERA_MOVE_BACKWARD) mBwd = false;
else if(ie.m_Id == CAMERA_MOVE_LEFT) mLeft = false;
else if(ie.m_Id == CAMERA_MOVE_RIGHT) mRight = false;
else if(ie.m_Id == CAMERA_SHIFT_SPEED) mKeyShiftDown = false;
}
}
static PX_FORCE_INLINE PxReal remapAxisValue(PxReal absolutePosition)
{
return absolutePosition * absolutePosition * absolutePosition * 5.0f;
}
void SampleCustomGravityCameraController::onAnalogInputEvent(const SampleFramework::InputEvent& ie, float val)
{
if(ie.m_Id == CAMERA_GAMEPAD_ROTATE_LEFT_RIGHT)
{
mGamepadYawInc = - remapAxisValue(val);
}
else if(ie.m_Id == CAMERA_GAMEPAD_ROTATE_UP_DOWN)
{
// PT: ideally we'd need an option to "invert Y axis" here
// mGamepadPitchInc = - remapAxisValue(val);
mGamepadPitchInc = remapAxisValue(val);
}
else if(ie.m_Id == CAMERA_GAMEPAD_MOVE_LEFT_RIGHT)
{
mGamepadLateralInc = val;
}
else if(ie.m_Id == CAMERA_GAMEPAD_MOVE_FORWARD_BACK)
{
mGamepadForwardInc = val;
}
}
void SampleCustomGravityCameraController::onPointerInputEvent(const SampleFramework::InputEvent &ie, physx::PxU32, physx::PxU32, physx::PxReal dx, physx::PxReal dy, bool val)
{
if (ie.m_Id == CAMERA_MOUSE_LOOK)
{
mTargetYaw -= dx * mSensibility;
mTargetPitch += dy * mSensibility;
}
}
void SampleCustomGravityCameraController::setView(PxReal pitch, PxReal yaw)
{
mTargetPitch = pitch;
mTargetYaw = yaw;
}
static PxQuat rotationArc(const PxVec3& v0, const PxVec3& v1, bool& res)
{
PxVec3 _v0 = v0;
PxVec3 _v1 = v1;
_v0.normalize();
_v1.normalize();
float s = sqrtf((1.0f + (v0.dot(v1))) * 2.0f);
if(s<0.001f)
{
res = false;
return PxQuat(PxIdentity);
}
PxVec3 p = (_v0.cross(_v1)) / s;
float w = s * 0.5f;
PxQuat q(p.x, p.y, p.z, w);
q.normalize();
res = true;
return q;
}
void SampleCustomGravityCameraController::update(Camera& camera, PxReal dtime)
{
PxSceneReadLock scopedLock(mBase.getActiveScene());
const PxExtendedVec3& currentPos = mCCT.getPosition();
const PxVec3 curPos = toVec3(currentPos);
// Compute up vector for current CCT position
PxVec3 upVector;
mBase.mPlanet.getUpVector(upVector, curPos);
PX_ASSERT(upVector.isFinite());
// Update CCT
if(!mBase.isPaused())
{
if(1)
{
bool recordPos = true;
const PxU32 currentSize = mNbRecords;
if(currentSize)
{
const PxVec3 lastPos = mHistory[currentSize-1];
// const float limit = 0.1f;
const float limit = 0.5f;
if((curPos - lastPos).magnitude()<limit)
recordPos = false;
}
if(recordPos)
{
if(mNbRecords==POS_HISTORY_LIMIT)
{
for(PxU32 i=1;i<mNbRecords;i++)
mHistory[i-1] = mHistory[i];
mNbRecords--;
}
mHistory[mNbRecords++] = curPos;
}
}
// Subtract off the 'up' component of the view direction to get our forward motion vector.
PxVec3 viewDir = camera.getViewDir();
PxVec3 forward = (viewDir - upVector * upVector.dot(viewDir)).getNormalized();
// PxVec3 forward = mForward;
// Compute "right" vector
PxVec3 right = forward.cross(upVector);
right.normalize();
// PxVec3 right = mRightV;
PxVec3 targetKeyDisplacement(0);
if(mFwd) targetKeyDisplacement += forward;
if(mBwd) targetKeyDisplacement -= forward;
if(mRight) targetKeyDisplacement += right;
if(mLeft) targetKeyDisplacement -= right;
targetKeyDisplacement *= mKeyShiftDown ? mRunningSpeed : mWalkingSpeed;
// targetKeyDisplacement += PxVec3(0,-9.81,0);
targetKeyDisplacement *= dtime;
PxVec3 targetPadDisplacement(0);
targetPadDisplacement += forward * mGamepadForwardInc * mRunningSpeed;
targetPadDisplacement += right * mGamepadLateralInc * mRunningSpeed;
// targetPadDisplacement += PxVec3(0,-9.81,0);
targetPadDisplacement *= dtime;
const PxF32 heightDelta = gJump.getHeight(dtime);
// shdfnd::printFormatted("%f\n", heightDelta);
PxVec3 upDisp = upVector;
if(heightDelta!=0.0f)
upDisp *= heightDelta;
else
upDisp *= -9.81f * dtime;
const PxVec3 disp = targetKeyDisplacement + targetPadDisplacement + upDisp;
//upDisp.normalize();
//shdfnd::printFormatted("%f | %f | %f\n", upDisp.x, upDisp.y, upDisp.z);
// shdfnd::printFormatted("%f | %f | %f\n", targetKeyDisplacement.x, targetKeyDisplacement.y, targetKeyDisplacement.z);
// shdfnd::printFormatted("%f | %f | %f\n\n", targetPadDisplacement.x, targetPadDisplacement.y, targetPadDisplacement.z);
mCCT.setUpDirection(upVector);
// const PxU32 flags = mCCT.move(disp, 0.001f, dtime, PxControllerFilters());
const PxU32 flags = mCCT.move(disp, 0.0f, dtime, PxControllerFilters());
if(flags & PxControllerCollisionFlag::eCOLLISION_DOWN)
{
gJump.stopJump();
// shdfnd::printFormatted("Stop jump\n");
}
}
// Update camera
if(1)
{
mTargetYaw += mGamepadYawInc * dtime;
mTargetPitch += mGamepadPitchInc * dtime;
// Clamp pitch
// if(mTargetPitch<mPitchMin) mTargetPitch = mPitchMin;
// if(mTargetPitch>mPitchMax) mTargetPitch = mPitchMax;
}
if(1)
{
PxVec3 up = upVector;
PxQuat localPitchQ(mTargetPitch, PxVec3(1.0f, 0.0f, 0.0f));
PX_ASSERT(localPitchQ.isSane());
PxMat33 localPitchM(localPitchQ);
const PxVec3 upRef(0.0f, 1.0f, 0.0f);
PxQuat localYawQ(mTargetYaw, upRef);
PX_ASSERT(localYawQ.isSane());
PxMat33 localYawM(localYawQ);
bool res;
PxQuat localToWorldQ = rotationArc(upRef, up, res);
static PxQuat memory(0,0,0,1);
if(!res)
{
localToWorldQ = memory;
}
else
{
memory = localToWorldQ;
}
PX_ASSERT(localToWorldQ.isSane());
PxMat33 localToWorld(localToWorldQ);
static PxVec3 previousUp(0.0f, 1.0f, 0.0f);
static PxQuat incLocalToWorldQ(0.0f, 0.0f, 0.0f, 1.0f);
PxQuat incQ = rotationArc(previousUp, up, res);
PX_ASSERT(incQ.isSane());
// incLocalToWorldQ = incLocalToWorldQ * incQ;
incLocalToWorldQ = incQ * incLocalToWorldQ;
PX_ASSERT(incLocalToWorldQ.isSane());
incLocalToWorldQ.normalize();
PxMat33 incLocalToWorldM(incLocalToWorldQ);
localToWorld = incLocalToWorldM;
previousUp = up;
mTest = localToWorld;
//mTest = localToWorld * localYawM;
// PxMat33 rot = localYawM * localToWorld;
PxMat33 rot = localToWorld * localYawM * localPitchM;
// PxMat33 rot = localToWorld * localYawM;
PX_ASSERT(rot.column0.isFinite());
PX_ASSERT(rot.column1.isFinite());
PX_ASSERT(rot.column2.isFinite());
////
PxMat44 view(rot.column0, rot.column1, rot.column2, PxVec3(0));
mForward = -rot.column2;
mRightV = rot.column0;
camera.setView(PxTransform(view));
PX_ASSERT(camera.getViewDir().isFinite());
////
PxRigidActor* characterActor = mCCT.getActor();
PxShape* shape;
characterActor->getShapes(&shape,1);
PxCapsuleGeometry geom;
shape->getCapsuleGeometry(geom);
up *= geom.halfHeight+geom.radius;
const PxVec3 headPos = curPos + up;
const float distanceToTarget = 10.0f;
// const float distanceToTarget = 20.0f;
// const float distanceToTarget = 5.0f;
// const PxVec3 camPos = headPos - viewDir*distanceToTarget;
const PxVec3 camPos = headPos - mForward*distanceToTarget;// + up * 20.0f;
// view.t = camPos;
view.column3 = PxVec4(camPos,0);
// camera.setView(view);
camera.setView(PxTransform(view));
mTarget = headPos;
}
if(0)
{
PxControllerState cctState;
mCCT.getState(cctState);
shdfnd::printFormatted("\nCCT state:\n");
shdfnd::printFormatted("delta: %.02f | %.02f | %.02f\n", cctState.deltaXP.x, cctState.deltaXP.y, cctState.deltaXP.z);
shdfnd::printFormatted("touchedShape: %p\n", cctState.touchedShape);
shdfnd::printFormatted("touchedObstacleHandle: %d\n", cctState.touchedObstacleHandle);
shdfnd::printFormatted("standOnAnotherCCT: %d\n", cctState.standOnAnotherCCT);
shdfnd::printFormatted("standOnObstacle: %d\n", cctState.standOnObstacle);
shdfnd::printFormatted("isMovingUp: %d\n", cctState.isMovingUp);
shdfnd::printFormatted("collisionFlags: %d\n", cctState.collisionFlags);
}
}

View File

@ -0,0 +1,75 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 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 "PhysXSampleApplication.h"
#include "SampleCameraController.h"
#include "characterkinematic/PxController.h"
#define POS_HISTORY_LIMIT 1024
class SampleCustomGravityCameraController : public CameraController
{
public:
SampleCustomGravityCameraController(PxController& controlled, SampleCustomGravity& base);
virtual void onDigitalInputEvent(const SampleFramework::InputEvent& , bool val);
virtual void onAnalogInputEvent(const SampleFramework::InputEvent& , float val);
virtual void onPointerInputEvent(const SampleFramework::InputEvent&, physx::PxU32, physx::PxU32, physx::PxReal dx, physx::PxReal dy, bool val);
virtual void collectInputEvents(std::vector<const SampleFramework::InputEvent*>& inputEvents);
virtual void update(Camera& camera, PxReal dtime);
void setView(PxReal pitch, PxReal yaw);
// private:
PxController& mCCT;
SampleCustomGravity& mBase;
PxVec3 mTarget;
PxMat33 mTest;
PxVec3 mForward, mRightV;
PxU32 mNbRecords;
PxVec3 mHistory[POS_HISTORY_LIMIT];
PxReal mTargetYaw, mTargetPitch;
PxReal mPitchMin, mPitchMax;
PxReal mGamepadPitchInc, mGamepadYawInc;
PxReal mGamepadForwardInc, mGamepadLateralInc;
PxReal mSensibility;
bool mFwd,mBwd,mLeft,mRight,mKeyShiftDown;
PxReal mRunningSpeed;
PxReal mWalkingSpeed;
private:
SampleCustomGravityCameraController& operator=(const SampleCustomGravityCameraController&);
};

View File

@ -0,0 +1,47 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxPhysicsAPI.h"
#include "SampleCustomGravity.h"
static PxFilterFlags filter(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1,
PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
{
pairFlags = PxPairFlag::eCONTACT_DEFAULT;
return PxFilterFlags();
}
void SampleCustomGravity::customizeSceneDesc(PxSceneDesc& sceneDesc)
{
sceneDesc.gravity = PxVec3(0);
sceneDesc.filterShader = filter;
sceneDesc.flags |= PxSceneFlag::eREQUIRE_RW_LOCK;
}

View File

@ -0,0 +1,46 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
#ifndef _SAMPLE_CUSTOM_GRAVITY_INPUT_EVENT_IDS_H
#define _SAMPLE_CUSTOM_GRAVITY_INPUT_EVENT_IDS_H
#include <SampleBaseInputEventIds.h>
// InputEvents used by SampleCharacterController
enum SampleCustomGravityInputEventIds
{
SAMPLE_CUSTOM_GRAVITY_FIRST = NUM_SAMPLE_BASE_INPUT_EVENT_IDS,
RESET_SCENE,
DRAW_WALLS,
DEBUG_RENDER,
RELEASE_TOUCH_SHAPE,
RAYCAST_HIT,
NUM_SAMPLE_CUSTOM_GRAVITY_INPUT_EVENT_IDS,
};
#endif

View File

@ -0,0 +1,233 @@
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxPhysicsAPI.h"
#include "characterkinematic/PxControllerManager.h"
#include "characterkinematic/PxBoxController.h"
#include "characterkinematic/PxCapsuleController.h"
#include "geometry/PxMeshQuery.h"
#include "geometry/PxTriangle.h"
#include "SampleCustomGravity.h"
#include "SampleCustomGravityCameraController.h"
#include "SampleCCTActor.h"
#include "SampleCustomGravityInputEventIds.h"
#include <SampleUserInputDefines.h>
#include <SamplePlatform.h>
#include <SampleUserInputIds.h>
#include "RenderBaseActor.h"
#include "RenderBoxActor.h"
#include "RenderCapsuleActor.h"
using namespace SampleRenderer;
using namespace SampleFramework;
#ifdef USE_BOX_CONTROLLER
PxBoxController* SampleCustomGravity::createCharacter(const PxExtendedVec3& position)
#else
PxCapsuleController* SampleCustomGravity::createCharacter(const PxExtendedVec3& position)
#endif
{
const float height = 2.0f;
// const float height = 1e-6f; // PT: TODO: make it work with 0?
#ifdef USE_BOX_CONTROLLER
PxBoxControllerDesc cDesc;
cDesc.halfHeight = height;
cDesc.halfSideExtent = mControllerRadius;
cDesc.halfForwardExtent = mControllerRadius;
#else
PxCapsuleControllerDesc cDesc;
cDesc.height = height;
cDesc.radius = mControllerRadius;
#endif
cDesc.material = &getDefaultMaterial();
cDesc.position = position;
cDesc.slopeLimit = SLOPE_LIMIT;
cDesc.contactOffset = CONTACT_OFFSET;
cDesc.stepOffset = STEP_OFFSET;
cDesc.invisibleWallHeight = INVISIBLE_WALLS_HEIGHT;
cDesc.maxJumpHeight = MAX_JUMP_HEIGHT;
cDesc.reportCallback = this;
mControllerInitialPosition = cDesc.position;
#ifdef USE_BOX_CONTROLLER
PxBoxController* ctrl = static_cast<PxBoxController*>(mControllerManager->createController(cDesc));
#else
PxCapsuleController* ctrl = static_cast<PxCapsuleController*>(mControllerManager->createController(cDesc));
#endif
// remove controller shape from scene query for standup overlap test
PxRigidDynamic* actor = ctrl->getActor();
if(actor)
{
if(actor->getNbShapes())
{
PxShape* ctrlShape;
actor->getShapes(&ctrlShape,1);
ctrlShape->setFlag(PxShapeFlag::eSCENE_QUERY_SHAPE, false);
#ifdef USE_BOX_CONTROLLER
const PxVec3 standingExtents(mControllerRadius, height, mControllerRadius);
mRenderActor = SAMPLE_NEW(RenderBoxActor)(*getRenderer(), standingExtents);
#else
mRenderActor = SAMPLE_NEW(RenderCapsuleActor)(*getRenderer(), mControllerRadius, height*0.5f);
#endif
if(mRenderActor)
mRenderActors.push_back(mRenderActor);
}
else
fatalError("character actor has no shape");
}
else
fatalError("character could not create actor");
// uncomment the next line to render the character
//createRenderObjectsFromActor(ctrl->getActor());
return ctrl;
}
void SampleCustomGravity::onShapeHit(const PxControllerShapeHit& hit)
{
PX_ASSERT(hit.shape);
// PT: TODO: rewrite this
if(hit.triangleIndex!=PxU32(-1))
{
PxTriangleMeshGeometry meshGeom;
PxHeightFieldGeometry hfGeom;
if(hit.shape->getTriangleMeshGeometry(meshGeom))
{
PxTriangle touchedTriangle;
PxMeshQuery::getTriangle(meshGeom, PxShapeExt::getGlobalPose(*hit.shape, *hit.shape->getActor()), hit.triangleIndex, touchedTriangle, NULL/*, NULL, NULL*/);
mValidTouchedTriangle = true;
mTouchedTriangle[0] = touchedTriangle.verts[0];
mTouchedTriangle[1] = touchedTriangle.verts[1];
mTouchedTriangle[2] = touchedTriangle.verts[2];
}
else if(hit.shape->getHeightFieldGeometry(hfGeom))
{
PxTriangle touchedTriangle;
PxMeshQuery::getTriangle(hfGeom, PxShapeExt::getGlobalPose(*hit.shape, *hit.shape->getActor()), hit.triangleIndex, touchedTriangle, NULL/*, NULL, NULL*/);
mValidTouchedTriangle = true;
mTouchedTriangle[0] = touchedTriangle.verts[0];
mTouchedTriangle[1] = touchedTriangle.verts[1];
mTouchedTriangle[2] = touchedTriangle.verts[2];
}
}
defaultCCTInteraction(hit);
}
void SampleCustomGravity::resetScene()
{
#ifdef USE_BOX_CONTROLLER
mBoxController->setPosition(mControllerInitialPosition);
#else
mCapsuleController->setPosition(mControllerInitialPosition);
#endif
mCCTCamera->setView(0,0);
/* while(mPhysicsActors.size())
{
PxRigidActor* actor = mPhysicsActors.back();
removeActor(actor);
}*/
}
void SampleCustomGravity::collectInputEvents(std::vector<const SampleFramework::InputEvent*>& inputEvents)
{
PhysXSample::collectInputEvents(inputEvents);
//digital keyboard events
DIGITAL_INPUT_EVENT_DEF(DRAW_WALLS, WKEY_B, OSXKEY_B, LINUXKEY_B );
DIGITAL_INPUT_EVENT_DEF(DEBUG_RENDER, WKEY_J, OSXKEY_J, LINUXKEY_J );
DIGITAL_INPUT_EVENT_DEF(RELEASE_TOUCH_SHAPE, WKEY_T, OSXKEY_T, LINUXKEY_T );
//digital mouse events
DIGITAL_INPUT_EVENT_DEF(RAYCAST_HIT, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_RIGHT, MOUSE_BUTTON_RIGHT );
}
void SampleCustomGravity::onDigitalInputEvent(const SampleFramework::InputEvent& ie, bool val)
{
if(val)
{
switch(ie.m_Id)
{
case RESET_SCENE:
{
resetScene();
}
break;
case DRAW_WALLS:
{
mDrawInvisibleWalls = !mDrawInvisibleWalls;
}
break;
case DEBUG_RENDER:
{
mEnableCCTDebugRender = !mEnableCCTDebugRender;
}
break;
case RELEASE_TOUCH_SHAPE:
{
#ifndef USE_BOX_CONTROLLER
PxControllerState state;
mCapsuleController->getState(state);
if (state.touchedShape && (!state.touchedShape->getActor()->is<PxRigidStatic>()))
{
PxRigidActor* actor = state.touchedShape->getActor();
std::vector<PxRigidDynamic*>::iterator i;
for(i=mDebugActors.begin(); i != mDebugActors.end(); i++)
{
if ((*i) == actor)
{
mDebugActors.erase(i);
break;
}
}
removeActor(actor);
}
#endif
}
break;
default:
break;
};
}
PhysXSample::onDigitalInputEvent(ie,val);
}