| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569 |
- #include "BsPhysX.h"
- #include "PxPhysicsAPI.h"
- #include "BsPhysXMaterial.h"
- #include "BsPhysXMesh.h"
- #include "BsPhysXRigidbody.h"
- #include "BsPhysXBoxCollider.h"
- #include "BsPhysXSphereCollider.h"
- #include "BsPhysXPlaneCollider.h"
- #include "BsPhysXCapsuleCollider.h"
- #include "BsPhysXMeshCollider.h"
- #include "BsPhysXFixedJoint.h"
- #include "BsPhysXDistanceJoint.h"
- #include "BsPhysXHingeJoint.h"
- #include "BsPhysXSphericalJoint.h"
- #include "BsPhysXSliderJoint.h"
- #include "BsPhysXD6Joint.h"
- #include "BsTaskScheduler.h"
- #include "BsTime.h"
- #include "Bsvector3.h"
- using namespace physx;
- namespace BansheeEngine
- {
- struct PHYSICS_INIT_DESC
- {
- float typicalLength = 1.0f;
- float typicalSpeed = 9.81f;
- Vector3 gravity = Vector3(0.0f, -9.81f, 0.0f);
- bool initCooking = true; // TODO: Disable this for Game build
- float timeStep = 1.0f / 60.0f;
- };
- class PhysXAllocator : public PxAllocatorCallback
- {
- public:
- void* allocate(size_t size, const char*, const char*, int) override
- {
- void* ptr = bs_alloc_aligned16((UINT32)size);
- PX_ASSERT((reinterpret_cast<size_t>(ptr) & 15) == 0);
- return ptr;
- }
- void deallocate(void* ptr) override
- {
- bs_free_aligned16(ptr);
- }
- };
- class PhysXErrorCallback : public PxErrorCallback
- {
- public:
- void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) override
- {
- {
- const char* errorCode = nullptr;
- UINT32 severity = 0;
- switch (code)
- {
- case PxErrorCode::eNO_ERROR:
- errorCode = "No error";
- break;
- case PxErrorCode::eINVALID_PARAMETER:
- errorCode = "Invalid parameter";
- severity = 2;
- break;
- case PxErrorCode::eINVALID_OPERATION:
- errorCode = "Invalid operation";
- severity = 2;
- break;
- case PxErrorCode::eOUT_OF_MEMORY:
- errorCode = "Out of memory";
- severity = 2;
- break;
- case PxErrorCode::eDEBUG_INFO:
- errorCode = "Info";
- break;
- case PxErrorCode::eDEBUG_WARNING:
- errorCode = "Warning";
- severity = 1;
- break;
- case PxErrorCode::ePERF_WARNING:
- errorCode = "Performance warning";
- severity = 1;
- break;
- case PxErrorCode::eABORT:
- errorCode = "Abort";
- severity = 2;
- break;
- case PxErrorCode::eINTERNAL_ERROR:
- errorCode = "Internal error";
- severity = 2;
- break;
- case PxErrorCode::eMASK_ALL:
- default:
- errorCode = "Unknown error";
- severity = 2;
- break;
- }
- StringStream ss;
- switch(severity)
- {
- case 0:
- ss << "PhysX info (" << errorCode << "): " << message << " at " << file << ":" << line;
- LOGDBG(ss.str());
- break;
- case 1:
- ss << "PhysX warning (" << errorCode << "): " << message << " at " << file << ":" << line;
- LOGWRN(ss.str());
- break;
- case 2:
- ss << "PhysX error (" << errorCode << "): " << message << " at " << file << ":" << line;
- LOGERR(ss.str());
- BS_ASSERT(false); // Halt execution on debug builds when error occurrs
- break;
- }
- }
- }
- };
- class PhysXEventCallback : public PxSimulationEventCallback
- {
- void onWake(PxActor** actors, PxU32 count) override { /* Do nothing */ }
- void onSleep(PxActor** actors, PxU32 count) override { /* Do nothing */ }
- void onTrigger(PxTriggerPair* pairs, PxU32 count) override
- {
- for (PxU32 i = 0; i < count; i++)
- {
- const PxTriggerPair& pair = pairs[i];
- PhysX::ContactEventType type;
- bool ignoreContact = false;
- switch ((UINT32)pair.status)
- {
- case PxPairFlag::eNOTIFY_TOUCH_FOUND:
- type = PhysX::ContactEventType::ContactBegin;
- break;
- case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
- type = PhysX::ContactEventType::ContactStay;
- break;
- case PxPairFlag::eNOTIFY_TOUCH_LOST:
- type = PhysX::ContactEventType::ContactEnd;
- break;
- default:
- ignoreContact = true;
- break;
- }
- if (ignoreContact)
- continue;
- PhysX::TriggerEvent event;
- event.trigger = (Collider*)pair.triggerShape->userData;
- event.other = (Collider*)pair.otherShape->userData;
- event.type = type;
- gPhysX()._reportTriggerEvent(event);
- }
- }
- void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 count) override
- {
- for (PxU32 i = 0; i < count; i++)
- {
- const PxContactPair& pair = pairs[i];
- PhysX::ContactEventType type;
- bool ignoreContact = false;
- switch((UINT32)pair.events)
- {
- case PxPairFlag::eNOTIFY_TOUCH_FOUND:
- type = PhysX::ContactEventType::ContactBegin;
- break;
- case PxPairFlag::eNOTIFY_TOUCH_PERSISTS:
- type = PhysX::ContactEventType::ContactStay;
- break;
- case PxPairFlag::eNOTIFY_TOUCH_LOST:
- type = PhysX::ContactEventType::ContactEnd;
- break;
- default:
- ignoreContact = true;
- break;
- }
- if (ignoreContact)
- continue;
- PhysX::ContactEvent event;
- event.colliderA = (Collider*)pair.shapes[0]->userData;
- event.colliderB = (Collider*)pair.shapes[1]->userData;
- event.type = type;
- PxU32 contactCount = pair.contactCount;
- const PxU8* stream = pair.contactStream;
- PxU16 streamSize = pair.contactStreamSize;
- if (contactCount > 0 && streamSize > 0)
- {
- PxU32 contactIdx = 0;
- PxContactStreamIterator iter((PxU8*)stream, streamSize);
- stream += ((streamSize + 15) & ~15);
- const PxReal* impulses = reinterpret_cast<const PxReal*>(stream);
- PxU32 hasImpulses = (pair.flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
- while (iter.hasNextPatch())
- {
- iter.nextPatch();
- while (iter.hasNextContact())
- {
- iter.nextContact();
- ContactPoint point;
- point.position = fromPxVector(iter.getContactPoint());
- point.separation = iter.getSeparation();
- point.normal = fromPxVector(iter.getContactNormal());
- if (hasImpulses)
- point.impulse = impulses[contactIdx];
- else
- point.impulse = 0.0f;
- event.points.push_back(point);
- contactIdx++;
- }
- }
- }
- gPhysX()._reportContactEvent(event);
- }
- }
- void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) override
- {
- for (UINT32 i = 0; i < count; i++)
- {
- PxConstraintInfo& constraintInfo = constraints[i];
- if (constraintInfo.type != PxConstraintExtIDs::eJOINT)
- continue;
- PxJoint* pxJoint = (PxJoint*)constraintInfo.externalReference;
- Joint* joint = (Joint*)pxJoint->userData;
-
- }
- }
- };
- class PhysXCPUDispatcher : public PxCpuDispatcher
- {
- public:
- void submitTask(PxBaseTask& physxTask) override
- {
- // Note: Banshee's task scheduler is pretty low granularity. Consider a better task manager in case PhysX ends
- // up submitting many tasks.
- // - PhysX's task manager doesn't seem much lighter either. But perhaps I can at least create a task pool to
- // avoid allocating them constantly.
- auto runTask = [&]() { physxTask.run(); physxTask.release(); };
- TaskPtr task = Task::create("PhysX", runTask);
- TaskScheduler::instance().addTask(task);
- }
- PxU32 getWorkerCount() const override
- {
- return (PxU32)TaskScheduler::instance().getNumWorkers();
- }
- };
- PxFilterFlags PhysXFilterShader(PxFilterObjectAttributes attr0, PxFilterData data0, PxFilterObjectAttributes attr1,
- PxFilterData data1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize)
- {
- if (PxFilterObjectIsTrigger(attr0) || PxFilterObjectIsTrigger(attr1))
- {
- pairFlags = PxPairFlag::eTRIGGER_DEFAULT;
- return PxFilterFlags();
- }
- UINT64 groupA = *(UINT64*)&data0.word0;
- UINT64 groupB = *(UINT64*)&data1.word0;
- bool canCollide = gPhysics().isCollisionEnabled(groupA, groupB);
- if (!canCollide)
- return PxFilterFlag::eSUPPRESS;
- pairFlags = PxPairFlag::eCONTACT_DEFAULT;
- return PxFilterFlags();
- }
- static PhysXAllocator gPhysXAllocator;
- static PhysXErrorCallback gPhysXErrorHandler;
- static PhysXCPUDispatcher gPhysXCPUDispatcher;
- static PhysXEventCallback gPhysXEventCallback;
- PhysX::PhysX()
- {
- PHYSICS_INIT_DESC input; // TODO - Make this an input parameter.
- mScale.length = input.typicalLength;
- mScale.speed = input.typicalSpeed;
- mFoundation = PxCreateFoundation(PX_PHYSICS_VERSION, gPhysXAllocator, gPhysXErrorHandler);
- mPhysics = PxCreateBasePhysics(PX_PHYSICS_VERSION, *mFoundation, mScale);
- PxRegisterArticulations(*mPhysics);
- if (input.initCooking)
- {
- // Note: PhysX supports cooking for specific platforms to make the generated results better. Consider
- // allowing the meshes to be re-cooked when target platform is changed. Right now we just use the default value.
- PxCookingParams cookingParams(mScale);
- mCooking = PxCreateCooking(PX_PHYSICS_VERSION, *mFoundation, cookingParams);
- }
- PxSceneDesc sceneDesc(mScale); // TODO - Test out various other parameters provided by scene desc
- sceneDesc.gravity = toPxVector(input.gravity);
- sceneDesc.cpuDispatcher = &gPhysXCPUDispatcher;
- sceneDesc.filterShader = PhysXFilterShader;
- sceneDesc.simulationEventCallback = &gPhysXEventCallback;
- sceneDesc.flags = PxSceneFlag::eENABLE_ACTIVETRANSFORMS;
- mScene = mPhysics->createScene(sceneDesc);
- mSimulationStep = input.timeStep;
- mDefaultMaterial = mPhysics->createMaterial(0.0f, 0.0f, 0.0f);
- }
- PhysX::~PhysX()
- {
- mScene->release();
- if (mCooking != nullptr)
- mCooking->release();
- mPhysics->release();
- mFoundation->release();
- }
- void PhysX::update()
- {
- mUpdateInProgress = true;
- float nextFrameTime = mLastSimulationTime + mSimulationStep;
- float curFrameTime = gTime().getTime();
- if(curFrameTime < nextFrameTime)
- {
- // TODO - Interpolate rigidbodies but perform no actual simulation
- return;
- }
- float simulationAmount = curFrameTime - mLastSimulationTime;
- while (simulationAmount >= mSimulationStep) // In case we're running really slow multiple updates might be needed
- {
- // Note: Consider delaying fetchResults one frame. This could improve performance because Physics update would be
- // able to run parallel to the simulation thread, but at a cost to input latency.
- // TODO - Provide a scratch buffer for the simulation (use the frame allocator, but I must extend it so it allocates
- // on a 16 byte boundary).
- mScene->simulate(mSimulationStep);
- mScene->fetchResults(true);
- // Update rigidbodies with new transforms
- PxU32 numActiveTransforms;
- const PxActiveTransform* activeTransforms = mScene->getActiveTransforms(numActiveTransforms);
- for (PxU32 i = 0; i < numActiveTransforms; i++)
- {
- Rigidbody* rigidbody = static_cast<Rigidbody*>(activeTransforms[i].userData);
- const PxTransform& transform = activeTransforms[i].actor2World;
- // Note: Make this faster, avoid dereferencing Rigidbody and attempt to access pos/rot destination directly,
- // use non-temporal writes
- rigidbody->_setTransform(fromPxVector(transform.p), fromPxQuaternion(transform.q));
- }
- simulationAmount -= mSimulationStep;
- }
- // TODO - Consider extrapolating for the remaining "simulationAmount" value
- mLastSimulationTime = curFrameTime;
- mUpdateInProgress = false;
- triggerEvents();
- }
- void PhysX::_reportContactEvent(const ContactEvent& event)
- {
- mContactEvents.push_back(event);
- }
- void PhysX::_reportTriggerEvent(const TriggerEvent& event)
- {
- mTriggerEvents.push_back(event);
- }
- void PhysX::_reportJointBreakEvent(const JointBreakEvent& event)
- {
- mJointBreakEvents.push_back(event);
- }
- void PhysX::triggerEvents()
- {
- CollisionData data;
- for(auto& entry : mTriggerEvents)
- {
- data.collider = entry.other;
- switch (entry.type)
- {
- case ContactEventType::ContactBegin:
- entry.trigger->onCollisionBegin(data);
- break;
- case ContactEventType::ContactStay:
- entry.trigger->onCollisionStay(data);
- break;
- case ContactEventType::ContactEnd:
- entry.trigger->onCollisionEnd(data);
- break;
- }
- }
- auto notifyContact = [&](Collider* obj, Collider* other, ContactEventType type,
- const Vector<ContactPoint>& points, bool flipNormals = false)
- {
- data.collider = other;
- data.contactPoints = points;
- if(flipNormals)
- {
- for (auto& point : data.contactPoints)
- point.normal = -point.normal;
- }
- SPtr<Rigidbody> rigidbody = obj->getRigidbody();
- if(rigidbody != nullptr)
- {
- switch (type)
- {
- case ContactEventType::ContactBegin:
- rigidbody->onCollisionBegin(data);
- break;
- case ContactEventType::ContactStay:
- rigidbody->onCollisionStay(data);
- break;
- case ContactEventType::ContactEnd:
- rigidbody->onCollisionEnd(data);
- break;
- }
- }
- else
- {
- switch (type)
- {
- case ContactEventType::ContactBegin:
- obj->onCollisionBegin(data);
- break;
- case ContactEventType::ContactStay:
- obj->onCollisionStay(data);
- break;
- case ContactEventType::ContactEnd:
- obj->onCollisionEnd(data);
- break;
- }
- }
- };
- for (auto& entry : mContactEvents)
- {
- notifyContact(entry.colliderA, entry.colliderB, entry.type, entry.points, true);
- notifyContact(entry.colliderB, entry.colliderA, entry.type, entry.points, false);
- }
- for(auto& entry : mJointBreakEvents)
- {
- entry.joint->onJointBreak();
- }
- mTriggerEvents.clear();
- mContactEvents.clear();
- mJointBreakEvents.clear();
- }
- SPtr<PhysicsMaterial> PhysX::createMaterial(float staticFriction, float dynamicFriction, float restitution)
- {
- return bs_shared_ptr_new<PhysXMaterial>(mPhysics, staticFriction, dynamicFriction, restitution);
- }
- SPtr<PhysicsMesh> PhysX::createMesh(const MeshDataPtr& meshData, PhysicsMeshType type)
- {
- return bs_shared_ptr_new<PhysXMesh>(meshData, type);
- }
- SPtr<Rigidbody> PhysX::createRigidbody(const HSceneObject& linkedSO)
- {
- return bs_shared_ptr_new<PhysXRigidbody>(mPhysics, mScene, linkedSO);
- }
- SPtr<BoxCollider> PhysX::createBoxCollider(const Vector3& extents, const Vector3& position,
- const Quaternion& rotation)
- {
- return bs_shared_ptr_new<PhysXBoxCollider>(mPhysics, position, rotation, extents);
- }
- SPtr<SphereCollider> PhysX::createSphereCollider(float radius, const Vector3& position, const Quaternion& rotation)
- {
- return bs_shared_ptr_new<PhysXSphereCollider>(mPhysics, position, rotation, radius);
- }
- SPtr<PlaneCollider> PhysX::createPlaneCollider(const Vector3& position, const Quaternion& rotation)
- {
- return bs_shared_ptr_new<PhysXPlaneCollider>(mPhysics, position, rotation);
- }
- SPtr<CapsuleCollider> PhysX::createCapsuleCollider(float radius, float halfHeight, const Vector3& position,
- const Quaternion& rotation)
- {
- return bs_shared_ptr_new<PhysXCapsuleCollider>(mPhysics, position, rotation, radius, halfHeight);
- }
- SPtr<MeshCollider> PhysX::createMeshCollider(const Vector3& position, const Quaternion& rotation)
- {
- return bs_shared_ptr_new<PhysXMeshCollider>(mPhysics, position, rotation);
- }
- SPtr<FixedJoint> PhysX::createFixedJoint()
- {
- return bs_shared_ptr_new<PhysXFixedJoint>(mPhysics);
- }
- SPtr<DistanceJoint> PhysX::createDistanceJoint()
- {
- return bs_shared_ptr_new<PhysXDistanceJoint>(mPhysics);
- }
- SPtr<HingeJoint> PhysX::createHingeJoint()
- {
- return bs_shared_ptr_new<PhysXHingeJoint>(mPhysics);
- }
- SPtr<SphericalJoint> PhysX::createSphericalJoint()
- {
- return bs_shared_ptr_new<PhysXSphericalJoint>(mPhysics);
- }
- SPtr<SliderJoint> PhysX::createSliderJoint()
- {
- return bs_shared_ptr_new<PhysXSliderJoint>(mPhysics);
- }
- SPtr<D6Joint> PhysX::createD6Joint()
- {
- return bs_shared_ptr_new<PhysXD6Joint>(mPhysics);
- }
- PhysX& gPhysX()
- {
- return static_cast<PhysX&>(PhysX::instance());
- }
- }
|