void Lux::Physics::CapsuleCollider::SetOrientation(CapsuleOrientation a_Orientation) { m_Orientation = a_Orientation; if (m_Shape) { PxTransform relativePose; switch (m_Orientation) { case X_AXIS: relativePose = PxTransform(PxQuat(PxHalfPi, PxVec3(0, 1, 0))); break; case Y_AXIS: relativePose = PxTransform(PxQuat(PxHalfPi, PxVec3(0, 0, 1))); break; case Z_AXIS: relativePose = PxTransform(PxQuat(PxHalfPi, PxVec3(1, 0, 0))); break; default: Utility::ThrowError("Error Setting Capsule Orientation. Unsupported Enumerator."); break; } m_Shape->setLocalPose(relativePose); } }
void TutorialScene::Initialize(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); // Create PhysX ground plane auto physX = PhysxManager::GetInstance()->GetPhysics(); GetPhysxProxy()->EnablePhysxDebugRendering(true); auto bouncyMaterial = physX->createMaterial(0, 0, 1); auto ground = new GameObject(); ground->AddComponent(new RigidBodyComponent(true)); std::shared_ptr<PxGeometry> geom(new PxPlaneGeometry()); ground->AddComponent(new ColliderComponent(geom,*bouncyMaterial,PxTransform(PxQuat(XM_PIDIV2,PxVec3(0,0,1))))); AddChild(ground); // ADD SPHERE m_pSphere = new SpherePrefab(); m_pSphere->GetTransform()->Translate(0,5,0); // Sphere PhysX auto rigidbody = new RigidBodyComponent(); m_pSphere->AddComponent(rigidbody); std::shared_ptr<PxGeometry> spheregeom(new PxSphereGeometry(1)); m_pSphere->AddComponent(new ColliderComponent(spheregeom,*bouncyMaterial, PxTransform(PxQuat(XM_PIDIV2,PxVec3(0,0,1))))); AddChild(m_pSphere); auto inputAction = InputAction(0, InputTriggerState::Down, 'M'); gameContext.pInput->AddInputAction(inputAction); }
physx::PxTransform Camera::GetTransform() const { PxVec3 viewY = m_dir.cross(PxVec3(0, 1, 0)); if (viewY.normalize() < 1e-6f) return PxTransform(m_eye); PxMat33 m(m_dir.cross(viewY), viewY, -m_dir); return PxTransform(m_eye, PxQuat(m)); }
PxRigidDynamic* Vehicle::createVehicleActor(const PxVehicleChassisData& chassisData, PxMaterial** wheelMaterials, PxConvexMesh** wheelConvexMeshes, const PxU32 numWheels, PxMaterial** chassisMaterials, PxConvexMesh** chassisConvexMeshes, const PxU32 numChassisMeshes, PxPhysics& physics, PxVec3 initPos) { //We need a rigid body actor for the vehicle. //Don't forget to add the actor to the scene after setting up the associated vehicle. PxRigidDynamic* vehActor = physics.createRigidDynamic(PxTransform(initPos)); vehActor->setRigidBodyFlag(PxRigidBodyFlag::eENABLE_CCD, true); //Wheel and chassis simulation filter data. PxFilterData wheelSimFilterData; wheelSimFilterData.word0 = COLLISION_FLAG_WHEEL; wheelSimFilterData.word1 = COLLISION_FLAG_WHEEL_AGAINST; PxFilterData chassisSimFilterData; chassisSimFilterData.word0 = COLLISION_FLAG_CHASSIS; chassisSimFilterData.word1 = COLLISION_FLAG_CHASSIS_AGAINST; //Wheel and chassis query filter data. //Optional: cars don't drive on other cars. PxFilterData wheelQryFilterData; wheelQryFilterData.word0 = FilterGroup::eWHEEL; setupNonDrivableSurface(wheelQryFilterData); PxFilterData chassisQryFilterData; chassisQryFilterData.word0 = FilterGroup::eVEHICLE; setupNonDrivableSurface(chassisQryFilterData); //Add all the wheel shapes to the actor. for (PxU32 i = 0; i < numWheels; i++) { PxConvexMeshGeometry geom(wheelConvexMeshes[i]); PxShape* wheelShape = vehActor->createShape(geom, *wheelMaterials[i]); wheelShape->setQueryFilterData(wheelQryFilterData); wheelShape->setSimulationFilterData(wheelSimFilterData); wheelShape->setLocalPose(PxTransform(PxIdentity)); } //Add the chassis shapes to the actor. for (PxU32 i = 0; i < numChassisMeshes; i++) { PxShape* chassisShape = vehActor->createShape (PxConvexMeshGeometry(chassisConvexMeshes[i]), *chassisMaterials[i]); chassisShape->setQueryFilterData(chassisQryFilterData); chassisShape->setSimulationFilterData(chassisSimFilterData); chassisShape->setLocalPose(PxTransform(PxIdentity)); } vehActor->setMass(chassisData.mMass); vehActor->setMassSpaceInertiaTensor(chassisData.mMOI); vehActor->setCMassLocalPose(PxTransform(chassisData.mCMOffset, PxQuat(PxIdentity))); return vehActor; }
bool UGripMotionControllerComponent::TeleportMoveGrippedActor(AActor * GrippedActorToMove) { if (!GrippedActorToMove || !GrippedActors.Num()) return false; FTransform WorldTransform; FTransform InverseTransform = this->GetComponentTransform().Inverse(); for (int i = GrippedActors.Num() - 1; i >= 0; --i) { if (GrippedActors[i].Actor == GrippedActorToMove) { // GetRelativeTransformReverse had some serious f*****g floating point errors associated with it that was f*****g everything up // Not sure whats wrong with the function but I might want to push a patch out eventually WorldTransform = GrippedActors[i].RelativeTransform.GetRelativeTransform(InverseTransform); // Need to use WITH teleport for this function so that the velocity isn't updated and without sweep so that they don't collide GrippedActors[i].Actor->SetActorTransform(WorldTransform, false, NULL, ETeleportType::TeleportPhysics); FBPActorPhysicsHandleInformation * Handle = GetPhysicsGrip(GrippedActors[i]); if (Handle && Handle->KinActorData) { { PxScene* PScene = GetPhysXSceneFromIndex(Handle->SceneIndex); if (PScene) { SCOPED_SCENE_WRITE_LOCK(PScene); Handle->KinActorData->setKinematicTarget(PxTransform(U2PVector(WorldTransform.GetLocation()), Handle->KinActorData->getGlobalPose().q)); Handle->KinActorData->setGlobalPose(PxTransform(U2PVector(WorldTransform.GetLocation()), Handle->KinActorData->getGlobalPose().q)); } } //Handle->KinActorData->setGlobalPose(PxTransform(U2PVector(WorldTransform.GetLocation()), Handle->KinActorData->getGlobalPose().q)); UPrimitiveComponent *root = Cast<UPrimitiveComponent>(GrippedActors[i].Actor->GetRootComponent()); if (root) { FBodyInstance * body = root->GetBodyInstance(); if (body) { body->SetBodyTransform(WorldTransform, ETeleportType::TeleportPhysics); } } } return true; } } return false; }
void createChain(const PxTransform& t, PxU32 length, const PxGeometry& g, PxReal separation, JointCreateFunction createJoint) { PxVec3 offset(separation / 2, 0, 0); PxTransform localTm(offset); PxRigidDynamic* prev = NULL; for (PxU32 i = 0; i<length; i++) { PxRigidDynamic* current = PxCreateDynamic(*gPhysics, t*localTm, g, *gMaterial, 1.0f); (*createJoint)(prev, prev ? PxTransform(offset) : t, current, PxTransform(-offset)); gScene->addActor(*current); prev = current; localTm.p.x += separation; } }
void Enemy::Move(D3DXVECTOR3 dir, float dT) { PxRaycastHit* hit = physics->RaycastMultiple(actor->getGlobalPose().p,PxVec3(0,-1,0).getNormalized(),colCapsuleHeight+0.1f,NULL,PxQueryFlag::eSTATIC); if(hit[0].actor == NULL) { dir.y = -9.8f*dT*2.5f; if(obj->position.y-colCapsuleHeight < -13.6f) { obj->position.y = -13.6f+colCapsuleHeight; } } else if(hit[1].actor == NULL && hit[0].actor == actor) { dir.y = -9.8f*dT*2.5f; if(obj->position.y-colCapsuleHeight < -13.6f) { obj->position.y = -13.6f+colCapsuleHeight; } } obj->position += dir*dT; D3DXQUATERNION rotQuat; D3DXQuaternionRotationYawPitchRoll(&rotQuat,0,0,90*ToRadian); if(actor->isRigidDynamic() != NULL) actor->isRigidDynamic()->setKinematicTarget(PxTransform(PxVec3(obj->position.x,obj->position.y,obj->position.z),PxQuat(rotQuat.x,rotQuat.y,rotQuat.z,rotQuat.w))); }
void Physics::setupPCTutorial() { //add a plane to the scene PxTransform transform = PxTransform(PxVec3(0, 0, 0), PxQuat((float)PxHalfPi, PxVec3(0, 0, 1))); PxRigidStatic* plane = PxCreateStatic(*m_physics, transform, PxPlaneGeometry(), *m_physics_material); m_physics_scene->addActor(*plane); my_hit_report = new MyControllerHitReport(); m_controller_manager = PxCreateControllerManager(*m_physics_scene); PxCapsuleControllerDesc desc; desc.height = 1.6f; desc.radius = 0.4f; desc.position.set(0, 0, 0); desc.material = m_physics_material; desc.reportCallback = my_hit_report; desc.density = 10; player_controller = m_controller_manager->createController(desc); player_controller->setPosition(desc.position); my_hit_report->player_contact_normal = PxVec3(0, 0, 0); }
void Apex::LoadDynamicTriangleMesh(int numVerts, PxVec3* verts, ObjectInfo info) { PxRigidDynamic* meshActor = mPhysics->createRigidDynamic(PxTransform::createIdentity()); PxShape* meshShape, *convexShape; if(meshActor) { //meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true); PxTriangleMeshDesc meshDesc; meshDesc.points.count = numVerts; meshDesc.points.stride = sizeof(PxVec3); meshDesc.points.data = verts; //meshDesc.triangles.count = numInds/3.; //meshDesc.triangles.stride = 3*sizeof(int); //meshDesc.triangles.data = inds; PxToolkit::MemoryOutputStream writeBuffer; bool status = mCooking->cookTriangleMesh(meshDesc, writeBuffer); if(!status) return; PxToolkit::MemoryInputData readBuffer(writeBuffer.getData(), writeBuffer.getSize()); PxTriangleMeshGeometry triGeom; triGeom.triangleMesh = mPhysics->createTriangleMesh(readBuffer); //triGeom.scale = PxMeshScale(PxVec3(info.sx,info.sy,info.sz),physx::PxQuat::createIdentity()); meshShape = meshActor->createShape(triGeom, *defaultMaterial); //meshShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z))); meshShape->setFlag(PxShapeFlag::eUSE_SWEPT_BOUNDS, true); PxConvexMeshDesc convexDesc; convexDesc.points.count = numVerts; convexDesc.points.stride = sizeof(PxVec3); convexDesc.points.data = verts; convexDesc.flags = PxConvexFlag::eCOMPUTE_CONVEX; if(!convexDesc.isValid()) return; PxToolkit::MemoryOutputStream buf; if(!mCooking->cookConvexMesh(convexDesc, buf)) return; PxToolkit::MemoryInputData input(buf.getData(), buf.getSize()); PxConvexMesh* convexMesh = mPhysics->createConvexMesh(input); PxConvexMeshGeometry convexGeom = PxConvexMeshGeometry(convexMesh); convexShape = meshActor->createShape(convexGeom, *defaultMaterial); //convexShape->setLocalPose(PxTransform(PxVec3(info.x,info.y,info.z))); //convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); convexShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true); meshShape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); meshActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false); meshActor->setGlobalPose(PxTransform(PxVec3(info.x,info.y,info.z), PxQuat(info.ry, PxVec3(0.0f,1.0f,0.0f)))); mScene[mCurrentScene]->addActor(*meshActor); dynamicActors.push_back(meshActor); } }
void GOCCharacterController::Create(Ogre::Vector3 dimensions) { QuitAllNewsgroups(); JoinNewsgroup(GlobalMessageIDs::PHYSICS_SUBSTEP); JoinNewsgroup(GlobalMessageIDs::PHYSICS_END); if (dimensions.x == 0 || dimensions.y == 0 || dimensions.z == 0) dimensions = Ogre::Vector3(1,1,1); mFreezed = false; mSpeedFactor = 1; mDirection = Ogre::Vector3(0,0,0); mDimensions = dimensions; PxMaterial *mat = &OgrePhysX::World::getSingleton().getDefaultMaterial(); mActor = Main::Instance().GetPhysXScene()->createRigidDynamic( PxBoxGeometry(mDimensions.x*0.5f, mDimensions.y*0.5f, mDimensions.z*0.5f), mDensity, *mat, PxTransform(PxVec3(0, mDimensions.y*0.5f, 0))); mActor.getFirstShape()->setSimulationFilterData(PhysXFilterData::Instance().Character); mActor.getFirstShape()->setQueryFilterData(PhysXFilterData::Instance().Character); mActor.getPxActor()->userData = mOwnerGO.lock().get(); mActor.getPxActor()->setMassSpaceInertiaTensor(PxVec3(0,1,0)); mActor.getPxActor()->setSolverIterationCounts(8); }
// Each frame, we do a shape query for static and dynamic objects // If this is the first time the synchronize has been called, then we create // a trigger actor with two spheres in the primary scene. This trigger // actor is used to detect when objects move in and outside of the static and dynamic // mirror range specified. void MirrorScene::synchronizePrimaryScene(const physx::PxVec3 &cameraPos) { PxVec3 diff = cameraPos - mLastCameraLocation; PxF32 dist = diff.magnitudeSquared(); if ( dist > mMirrorDistanceThreshold ) { mLastCameraLocation = cameraPos; if ( mTriggerActor == NULL ) { createTriggerActor(cameraPos); // Create the scene mirroring trigger actor } if ( mTriggerActor ) { mPrimaryScene.lockWrite(__FILE__,__LINE__); mTriggerActor->setKinematicTarget( PxTransform(cameraPos) ); // Update the position of the trigger actor to be the current camera location mPrimaryScene.unlockWrite(); } } // Now, iterate on all of the current actors which are being mirrored // Only the primary scene after modifies this hash, so it is safe to do this // without any concerns of thread locking. // The mirrored scene thread does access the contents of this hash (MirrorActor) { mPrimaryScene.lockRead(__FILE__,__LINE__); for (ActorHash::Iterator i=mActors.getIterator(); !i.done(); ++i) { MirrorActor *ma = i->second; ma->synchronizePose(); // check to see if the position of this object in the primary // scene has changed. If it has, then we create a command for the mirror scene to update // it's mirror actor to that new position. } mPrimaryScene.unlockRead(); } }
/** * Method is used to add heightfield actor to physics scene. * @param entity is actor logic object. * @param heightData is terrain height map data. * @param params is terrain parameters: heightmap size, row/column scale, max. height. * @param filterGroup is actor own id. * @param filterMask is mask to filter pairs that trigger a contact callback. */ void PhysicsManager::addHeightFieldActor(SceneEntity* entity, unsigned char* heightData, const Vector4D& params, PxU32 filterGroup, PxU32 filterMask) { int terrainSize = static_cast<int>(params.x()); PxHeightFieldSample* samples = new PxHeightFieldSample[terrainSize*terrainSize]; PxHeightFieldDesc descriptor; descriptor.nbColumns = static_cast<int>(terrainSize); descriptor.nbRows = static_cast<int>(terrainSize); for(int i = 0; i < terrainSize*terrainSize; ++i) samples[i].height = static_cast<PxI16>(heightData[i]); descriptor.samples.data = samples; descriptor.samples.stride = sizeof(PxHeightFieldSample); PxHeightField* heightField = physicsSDK->createHeightField(descriptor); PxHeightFieldGeometry geometry(heightField, PxMeshGeometryFlags(),params.w()*0.00390625f,params.y(),params.z()); PxTransform transformation = PxTransform(PxVec3(-terrainSize*0.5f*params.y(),0.0f,-terrainSize*0.5f*params.z()),PxQuat::createIdentity()); PxRigidStatic* heightFieldActor = physicsSDK->createRigidStatic(transformation); PxShape* aHeightFieldShape = heightFieldActor->createShape(geometry,*materials[0].second); heightFieldActor->setName(entity->entityName.c_str()); setupFiltering(heightFieldActor,filterGroup,filterMask); scene->addActor(*heightFieldActor); StaticActor* s = new StaticActor(); s->entityLogic = entity; s->entityPhysics = heightFieldActor; staticActors.push_back(s); }
void setupActor (PxRigidDynamic* vehActor, const PxFilterData& vehQryFilterData, const PxGeometry** wheelGeometries, const PxTransform* wheelLocalPoses, const PxU32 numWheelGeometries, const PxMaterial* wheelMaterial, const PxFilterData& wheelCollFilterData, const PxGeometry** chassisGeometries, const PxTransform* chassisLocalPoses, const PxU32 numChassisGeometries, const PxMaterial* chassisMaterial, const PxFilterData& chassisCollFilterData, const PxVehicleChassisData& chassisData, PxPhysics* physics) { //Add all the wheel shapes to the actor. for(PxU32 i=0;i<numWheelGeometries;i++) { PxShape* wheelShape=vehActor->createShape(*wheelGeometries[i],*wheelMaterial); wheelShape->setQueryFilterData(vehQryFilterData); wheelShape->setSimulationFilterData(wheelCollFilterData); wheelShape->setLocalPose(wheelLocalPoses[i]); } //Add the chassis shapes to the actor. for(PxU32 i=0;i<numChassisGeometries;i++) { PxShape* chassisShape=vehActor->createShape(*chassisGeometries[i],*chassisMaterial); chassisShape->setQueryFilterData(vehQryFilterData); chassisShape->setSimulationFilterData(chassisCollFilterData); chassisShape->setLocalPose(chassisLocalPoses[i]); } vehActor->setMass(chassisData.mMass); vehActor->setMassSpaceInertiaTensor(chassisData.mMOI); vehActor->setCMassLocalPose(PxTransform(chassisData.mCMOffset,PxQuat::createIdentity())); }
bool Collider::Init(bool isDynamic) { bool ret = false; const Transform& transform = mOwner.GetTransform(); mTransform.position = transform.position; mTransform.rotation = transform.rotation; PxVec3 pos = ConvertPxVec3(transform.position); PxQuat rot = ConvertPxQuat(transform.rotation); PxScene* scene = mOwner.GetScene().GetPxScene(); CHECK(scene); if (isDynamic) { PxRigidDynamic* dyn = gPhysics->createRigidDynamic(PxTransform(pos, rot)); dyn->setLinearDamping(0.25); dyn->setAngularDamping(0.25); mActor = dyn; mRigidBody = new RigidBody(*dyn); } else { mActor = gPhysics->createRigidStatic(PxTransform(pos, rot)); } CHECK(mActor); mActor->userData = &mOwner; OnInitShape(); CHECK(mGizmo); mOwner.GetScene().AddGizmo(mGizmo); mGizmo->SetColor(Color(0, 1, 0, 1)); scene->addActor(*mActor); SetLocalPose(Vector3(), Quat()); ret = true; Exit0: return ret; }
int RayCastManagerImpl::CastSweep(const XMFLOAT3& p_origin, XMFLOAT3& p_direction, float p_width, const float& p_range, int& o_flag) { if(p_range <= 0.0f) { cout << "Physcs. Raytracer. Sweep. Range of sweep was zero or below" << endl; return -1; } // Cast directx things to physx PxVec3 origin = PxVec3(p_origin.x, p_origin.y, p_origin.z); PxVec3 direction = PxVec3(p_direction.x, p_direction.y, p_direction.z); direction.normalize(); PxSweepBuffer hit; // Used to save the hit /// Paramters for the sweep // PxGeometry* geometry bool status = m_utils.m_worldScene->sweep(PxSphereGeometry(p_width), PxTransform(origin), direction, p_range, hit, PxHitFlag::eMESH_BOTH_SIDES); // hit.block.position; if(!status && !hit.hasBlock) { // No hit detected, return -1 TODOKO Maybee i should return something better? return -1; } // Start with checking static and dynamic rigid bodies unordered_map<PxRigidActor*, int> idsByRigidBody = m_utils.m_rigidBodyManager->GetIDsByBodies(); if(idsByRigidBody.find(hit.block.actor) != idsByRigidBody.end()) { PxRigidActor* actorAsRigic = (PxRigidActor*)hit.block.actor; if(actorAsRigic->isRigidDynamic()) { PxRigidDynamic* actorsAsDynamic = (PxRigidDynamic*)hit.block.actor; if(actorsAsDynamic->getRigidBodyFlags() & PxRigidBodyFlag::eKINEMATIC) { o_flag = 0; } } else if(actorAsRigic->isRigidStatic()) { o_flag = 3; } return idsByRigidBody.find(hit.block.actor)->second; } else { // Nothing } // Now comes the difficult task of checking vs character controllers unordered_map<PxController*, int> idsByCharacterController = m_utils.m_characterControlManager->GetIdsByControllers(); for(auto pairs : idsByCharacterController) // Loop through every pair in the list { if(pairs.first->getActor() == hit.block.actor) // The first part contains the actor pointer { o_flag = 1; return pairs.second; // If this is true we found a hit vs character controller, second contains ID } } return -1; }
/** Component tick override. Updates the PhysX scene with the Actor transform @param [in] deltaSeconds last frame duration */ void RigidStatic::tick(float deltaSeconds) { shared_ptr<Actor> actor = getActor(); // physxRigidStatic->setGlobalPose(transformToPhysXTransform(actor->transform)); physxRigidStatic->setGlobalPose(PxTransform(glmMat4ToPhysxMat4(actor->transform->getPosRotMatrix()))); }
void Item::SetPosition(OPvec3 pos) { physics.entity.transform.position = pos; physics.physX->setGlobalPose(PxTransform( PxVec3( physics.entity.transform.position.x, physics.entity.transform.position.y, physics.entity.transform.position.z))); //OPphysXGetTransform((OPphysXRigidActor*)physics.physX, &physics.entity.rendererEntity->world); }
void Physx1::setUpTutorial() { //add a plane PxTransform pose = PxTransform(PxVec3(0, 0, 0), PxQuat(PxHalfPi * 1.0f, PxVec3(0, 0, 1))); PxRigidStatic* plane = PxCreateStatic(*m_Physics, pose, PxPlaneGeometry(), *m_PhysicsMaterial); //add it to the physx scene m_PhysicsScene->addActor(*plane); }
/** * Method is used to add new static actor to physics scene. Now only plane shape can be used. * @param entity is pointer to scene entity which will be added to physics simulation. * @param type is enumeration of shape type. * @param filterGroup is actor own id. * @param filterMask is mask to filter pairs that trigger a contact callback. */ void PhysicsManager::addStaticActor(SceneEntity* entity, ShapeType type, PxU32 filterGroup, PxU32 filterMask) { PxVec3 position; PxQuat orientation; PxTransform transformation; if(entity == nullptr) { transformation = PxTransform(PxVec3(0.0f,1.0f,0.0f),PxQuat(PxHalfPi,PxVec3(0.0f, 0.0f, 1.0f))); } else { position = PxVec3(entity->entityState.position[0],entity->entityState.position[1],entity->entityState.position[2]); orientation = PxQuat(entity->entityState.orientation[0],entity->entityState.orientation[1],entity->entityState.orientation[2],entity->entityState.orientation[3]); transformation = PxTransform(position,orientation); } PxRigidStatic* actor = nullptr; actor = physicsSDK->createRigidStatic(transformation); if(!actor) Logger::getInstance()->saveLog(Log<string>("Static Actor creation error occurred!")); PxShape* shape = nullptr; if(type == PLANE) shape = actor->createShape(PxPlaneGeometry(),*materials[0].second); else return; if(!shape) Logger::getInstance()->saveLog(Log<string>("Static Actor shape creation error occurred!")); actor->setName("World Plane"); setupFiltering(actor,filterGroup,filterMask); scene->addActor(*actor); StaticActor* s = new StaticActor(); s->entityLogic = entity; s->entityPhysics = actor; staticActors.push_back(s); }
// Set up PhysX void InitializePhysX() { gFoundation = PxCreateFoundation(PX_FOUNDATION_VERSION, gAllocator, gErrorCallback); gPvd = PxCreatePvd(*gFoundation); PxPvdTransport* transport = PxDefaultPvdSocketTransportCreate("127.0.0.1", 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 = contactReportFilterShader/*PxDefaultSimulationFilterShader*/; sceneDesc.simulationEventCallback = &gContactReportCallback; // contact callback sceneDesc.contactModifyCallback = &gModContactReportCallback; // modification contact callback 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); // add some physics objects AddPhyObjects(); createChain(PxTransform(PxVec3(10.0f, 30.0f, -30.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createLimitedSpherical); createChain(PxTransform(PxVec3(0.0f, 30.0f, -30.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createBreakableFixed); createChain(PxTransform(PxVec3(-10.0f, 30.0f, -30.0f)), 5, PxBoxGeometry(2.0f, 0.5f, 0.5f), 4.0f, createDampedD6); gScene->setVisualizationParameter(PxVisualizationParameter::eSCALE, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eACTOR_AXES, 1.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eCOLLISION_SHAPES, 2.0f); gScene->setVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL, 2.0f); }
bool ParticleChain::checkPenetration(const Ogre::Vector3 &position, Ogre::Vector3 &closestSurfacePos, Ogre::Vector3 &collisionNormal) { PxShape *hit = nullptr; PxVec3 pxPos = Convert::toPx(position); if (mPhysXScene->getPxScene()->overlapAny(PxSphereGeometry(0.05f), PxTransform(pxPos), hit)) { PxVec3 actorCenter = hit->getActor().getWorldBounds().getCenter(); PxVec3 rayDir = actorCenter - pxPos; rayDir.normalize(); PxVec3 rayOrigin = pxPos - rayDir.multiply(PxVec3(0.2f, 0.2f, 0.2f)); if (mPhysXScene->getPxScene()->overlapAny(PxSphereGeometry(0.05f), PxTransform(rayOrigin), hit)) return false; PxRaycastHit rayHit; if (mPhysXScene->getPxScene()->raycastSingle(rayOrigin, rayDir, 0.2f, PxSceneQueryFlag::eIMPACT|PxSceneQueryFlag::eNORMAL|PxSceneQueryFlag::eDISTANCE, rayHit)) { closestSurfacePos = Convert::toOgre(rayHit.impact); collisionNormal = Convert::toOgre(rayHit.normal); return true; } } return false; }
void FConstraintInstance::UpdateDriveTarget() { #if WITH_PHYSX ExecuteOnUnbrokenJointReadWrite([&] (PxD6Joint* Joint) { FQuat OrientationTargetQuat(AngularOrientationTarget); Joint->setDrivePosition(PxTransform(U2PVector(LinearPositionTarget), U2PQuat(OrientationTargetQuat))); Joint->setDriveVelocity(U2PVector(LinearVelocityTarget), U2PVector(RevolutionsToRads(AngularVelocityTarget))); }); #endif }
void FConstraintInstance::UpdateDriveTarget() { #if WITH_PHYSX if (PxD6Joint* PJoint = GetUnbrokenJoint()) { FQuat OrientationTargetQuat(AngularOrientationTarget); PJoint->setDrivePosition(PxTransform(U2PVector(LinearPositionTarget), U2PQuat(OrientationTargetQuat))); PJoint->setDriveVelocity(U2PVector(LinearVelocityTarget), U2PVector(RevolutionsToRads(AngularVelocityTarget))); } #endif }
void labscale::CreateRegolithContainer() { // Geometry variables PxReal box_d = labscale::reg_box.diameter; PxReal box_h = labscale::reg_box.fillHeight*2; PxReal wall_dh = box_d/20; // We'll make the regolith container with a kinematic actor PxRigidDynamic* theBox = gPhysX.mPhysics->createRigidDynamic(PxTransform(PxVec3(0,0.05*wall_dh,0))); if (!theBox) ncc__error("Actor creation failed!"); theBox->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, true); // Define sides PxBoxGeometry box_bottom(box_d/2,wall_dh/2,box_d/2); PxBoxGeometry box_side(wall_dh/2,box_h/2,box_d/2); PxMaterial* defmat=gPhysX.mDefaultMaterial; // Attach the sides, making front wall invisible theBox->createShape(box_bottom,*defmat,PxTransform(PxVec3(0,wall_dh/2,0))); // the bottom theBox->createShape(box_side,*defmat,PxTransform(PxVec3(-box_d/2,box_h/2,0),PxQuat(0,PxVec3(0,1,0)))); // left wall theBox->createShape(box_side,*defmat,PxTransform(PxVec3( box_d/2,box_h/2,0),PxQuat(0,PxVec3(0,1,0)))); // right wall theBox->createShape(box_side,*defmat,PxTransform(PxVec3(0,box_h/2,-box_d/2),PxQuat(PxPi/2,PxVec3(0,1,0)))); // back wall PxShape* fwall = theBox->createShape(box_side,*defmat,PxTransform(PxVec3(0,box_h/2, box_d/2),PxQuat(PxPi/2,PxVec3(0,1,0)))); // front wall fwall->setName("~fwall"); // Name, color, and register the container theBox->setName("the_box"); ColorActor(theBox, ncc::rgb::rRed); gPhysX.mScene->addActor(*theBox); labscale::VIPs.container = theBox; }
void Spacetime::setState(matrix<double> stateVector) { std::vector<PxQuat> theta; for (int i = 0; i < joints.size(); i++) { PxQuat q = PxQuat::createIdentity(); if (i == 0) { if (DOF > X) { q *= PxQuat(stateVector((i)*DOF+X,0), PxVec3(1,0,0)); } if (DOF > Y) { q *= PxQuat(stateVector((i)*DOF+Y,0), PxVec3(0,1,0)); } if (DOF > Z) { q *= PxQuat(stateVector((i)*DOF+Z,0), PxVec3(0,0,1)); } } else { if (DOF > X) { q *= PxQuat(stateVector((i)*DOF+X,0), PxVec3(1,0,0)) * theta[(i-1)*DOF+X]; } if (DOF > Y) { q *= PxQuat(stateVector((i)*DOF+Y,0), PxVec3(0,1,0)) * theta[(i-1)*DOF+Y]; } if (DOF > Z) { q *= PxQuat(stateVector((i)*DOF+Z,0), PxVec3(0,0,1)) * theta[(i-1)*DOF+Z]; } } theta.push_back(q); } dynamic_actors[0]->setGlobalPose(PxTransform(root, PxQuat::createIdentity())); PxVec3 lastJointPos = dynamic_actors[0]->getGlobalPose().p + PxVec3(0,0.5,0); PxQuat lastJointRot = dynamic_actors[0]->getGlobalPose().q; for (int i = 0; i < joints.size(); i++) { PxRigidDynamic *current = dynamic_actors[i+1]; PxVec3 t = theta[i].rotate(-joint_local_positions[i]); PxVec3 gPos = lastJointPos + t; current->setGlobalPose(PxTransform(gPos, theta[i])); lastJointPos = lastJointPos + 2*t; } for (int i = 0; i < joints.size(); i++) { PxRigidDynamic *current = dynamic_actors[i+1]; PxVec3 angularVelocity; if (DOF > X) { angularVelocity[X] = stateVector(joints.size()*DOF + i*DOF+X,0); } else { angularVelocity[X] = 0.0; } if (DOF > Y) { angularVelocity[Y] = stateVector(joints.size()*DOF + i*DOF+Y,0); } else { angularVelocity[Y] = 0.0; } if (DOF > Z) { angularVelocity[Z] = stateVector(joints.size()*DOF + i*DOF+Z,0); } else { angularVelocity[Z] = 0.0; } current->setAngularVelocity(angularVelocity); current->setLinearVelocity(PxVec3(0,0,0)); } }
void CThrowBomb::initThrow() { lcurrent = hcurrent = 0; initial_pos = transform->getPosition(); VEC3 offset = offset_init_throw.x * dir_throw.Cross(VEC3_UP) + offset_init_throw.y * VEC3_UP + offset_init_throw.z * dir_throw; initial_pos += offset; rd->setGlobalPose(PxTransform( PhysxConversion::Vec3ToPxVec3(transform->getPosition()), PhysxConversion::CQuaternionToPxQuat(transform->getRotation()) )); }
void UPhysicsHandleComponent::UpdateHandleTransform(const FTransform& NewTransform) { if(!KinActorData) { return; } #if WITH_PHYSX bool bChangedPosition = true; bool bChangedRotation = true; PxRigidDynamic* KinActor = KinActorData; // Check if the new location is worthy of change PxVec3 PNewLocation = U2PVector(NewTransform.GetTranslation()); PxVec3 PCurrentLocation = KinActor->getGlobalPose().p; if((PNewLocation - PCurrentLocation).magnitudeSquared() <= 0.01f*0.01f) { PNewLocation = PCurrentLocation; bChangedPosition = false; } // Check if the new rotation is worthy of change PxQuat PNewOrientation = U2PQuat(NewTransform.GetRotation()); PxQuat PCurrentOrientation = KinActor->getGlobalPose().q; if(!(FMath::Abs(PNewOrientation.dot(PCurrentOrientation)) < (1.f - KINDA_SMALL_NUMBER))) { PNewOrientation = PCurrentOrientation; bChangedRotation = false; } // Don't call moveKinematic if it hasn't changed - that will stop bodies from going to sleep. if (bChangedPosition || bChangedRotation) { KinActor->setKinematicTarget(PxTransform(PNewLocation, PNewOrientation)); //LOC_MOD //PxD6Joint* Joint = (PxD6Joint*) HandleData; //if(Joint)// && (PNewLocation - PCurrentLocation).magnitudeSquared() > 0.01f*0.01f) //{ // PxRigidActor* Actor0, *Actor1; // Joint->getActors(Actor0, Actor1); // //Joint->setDrivePosition(PxTransform(Actor0->getGlobalPose().transformInv(PNewLocation))); // Joint->setDrivePosition(PxTransform::createIdentity()); // //Joint->setDriveVelocity(PxVec3(0), PxVec3(0)); //} } #endif // WITH_PHYSX }
void ResetScene() { PxVec3 resetPosition; for(int i = 0; i < boxes.size(); i++) { srand((time(NULL) * i) + time(NULL)); resetPosition = PxVec3((float)((rand() % (2 * PLANET_HEIGHT)) - PLANET_HEIGHT), (float)((rand() % (2 * PLANET_HEIGHT)) - PLANET_HEIGHT), (float)((rand() % (2 * PLANET_HEIGHT)) - PLANET_HEIGHT)); boxes[i]->actor->isRigidDynamic()->setLinearVelocity(PxVec3(0,0,0)); boxes[i]->actor->setGlobalPose(PxTransform(resetPosition, PxQuat::createIdentity())); } }
void FBXActor::createCollisionShapes(PhysicsDemoScene *a_app) { float density = 300; //pole PxBoxGeometry box = PxBoxGeometry(0.1f,4,0.1f); PxTransform transform(*((PxMat44*)(&m_world))); //cast from glm to PhysX matrices PxRigidDynamic* dynamicActor = PxCreateDynamic(*a_app->g_Physics, transform, box, *a_app->g_PhysicsMaterial, density); dynamicActor->userData = this; //set the user data to point at this FBXActor class //offset int nShapes = dynamicActor->getNbShapes(); PxShape* shapes; dynamicActor->getShapes(&shapes, nShapes); PxTransform relativePose = PxTransform(PxVec3(0.0f,4.0f,0.0f)); shapes->setLocalPose(relativePose); //head box = PxBoxGeometry(0.8f,0.5f,0.3f); relativePose = PxTransform(PxVec3(0.0f,2.0f,0.0f)); PxShape* shape = dynamicActor->createShape(box, *a_app->g_PhysicsMaterial); if (shape) { shape->setLocalPose(relativePose); } PxRigidBodyExt::updateMassAndInertia(*dynamicActor, (PxReal)density); //add to scene a_app->g_PhysicsScene->addActor(*dynamicActor); a_app->g_PhysXActors.push_back(dynamicActor); }
// add some physics objects into the scene void AddPhyObjects() { PxRigidStatic* groundPlane = PxCreatePlane(*gPhysics, PxPlane(0, 1, 0, 0), *gMaterial); gScene->addActor(*groundPlane); PxShape* shape = gPhysics->createShape(PxBoxGeometry(1.0f, 1.0f, 1.0f), *gMaterial); PxTransform localTm(PxVec3(-3.0f, 5.0f, 0.f)); PxRigidDynamic* body = gPhysics->createRigidDynamic(localTm); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); shape->release(); shape = gPhysics->createShape(PxSphereGeometry(1.0f), *gMaterial); PxTransform localTmS(PxVec3(3.0f, 5.0f, 0.f)); body = gPhysics->createRigidDynamic(localTmS); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); shape->release(); PxRigidDynamic* dynamic = PxCreateDynamic(*gPhysics, PxTransform(PxVec3(0, 20, 20)), PxSphereGeometry(1), *gMaterial, 10.0f); dynamic->setAngularDamping(0.5f); dynamic->setLinearVelocity(PxVec3(0, -5, -10)); gScene->addActor(*dynamic); // add capsule into the scene shape = gPhysics->createShape(PxCapsuleGeometry(1.0f, 3.0f), *gMaterial); PxTransform localTmC(PxVec3(3.0f, 5.0f, -3.f)); body = gPhysics->createRigidDynamic(localTmC); body->attachShape(*shape); PxRigidBodyExt::updateMassAndInertia(*body, 10.0f); gScene->addActor(*body); // add a static box as the trigger shape = gPhysics->createShape(PxBoxGeometry(1.0f, 1.0f, 1.0f), *gMaterial); PxTransform localTmTrigger(PxVec3(0.0f, 1.0f, -10.f)); body = gPhysics->createRigidDynamic(localTmTrigger); shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, false); shape->setFlag(PxShapeFlag::eTRIGGER_SHAPE, true); body->attachShape(*shape); body->setRigidBodyFlag(PxRigidBodyFlag::eKINEMATIC, true); gScene->addActor(*body); shape->release(); }