virtual void onSleep(NxActor** actors, NxU32 count) { while(count--) { NxActor *thisActor = *actors; // do whatever you need to do // with actors that have gone to sleep if(thisActor->userData) //sleep 之后改变颜色 { static_cast<UserData*>(thisActor->userData)->color = NxVec3(1.0f,1.0f,0.0f); } actors++; } }
void CPhysicActor::AddPlaneShape (const Vect3f& normal, float distance, uint32 group) { assert(m_pPhXActorDesc); // Add a plane shape to the actor descriptor NxPlaneShapeDesc *planeDesc = new NxPlaneShapeDesc(); assert(planeDesc); planeDesc->group = group; m_vPlaneDesc.push_back(planeDesc); planeDesc->normal = NxVec3( normal.x, normal.y, normal.z); planeDesc->d = distance; m_pPhXActorDesc->shapes.pushBack( planeDesc ); }
//--------------------------------------------------------------------------------------------------------- Vehicle::Vehicle(const std::string &fileName,Ogre::SceneManager* sm, Ogre::RenderWindow* win, NxScene* ns, const Ogre::Vector3 pos, const Ogre::Quaternion ori): mSpeed(0), mAngle(0),mAngleDelta(0),mTurnLeft(0),mTurnRight(0),mRollAngle(0) { //初始化各种变量 mSceneMgr = sm; mWindow = win; mOriginalPos = pos; mOriginalQuat = ori; mNxScene = ns; //mVehicleInfo.loadFromFile("carinfo.cfg"); mDecalShadow = NULL; VehicleWheel vw; mWheels.push_back(vw); mWheels.push_back(vw); mWheels.push_back(vw); mWheels.push_back(vw); loadScene(fileName); //load parameter data from file Ogre::FileInfoListPtr fp = Ogre::ResourceGroupManager::getSingleton().findResourceFileInfo("Popular", fileName + ".vpf"); Ogre::String total = fp->back().archive->getName() + "\\" + fileName + ".vpf"; mVehicleParam.loadFromFile(total); refreshParameter(); mCarNode = mBaseCarNode; //创建摄像机节点 mCameraDerivedNode = mCarNode->createChildSceneNode(Ogre::Vector3(0.0f, mBoundingBox.getSize().y, -mBoundingBox.getSize().z*2)); mVehicleCamer = new VehicleCamera(fileName + "VehicleCamera", mWindow, mSceneMgr); mVehicleCamer->setTarget(mCameraDerivedNode, mCarNode); mVehicleCamer->setTightness(2.5f); //获取VehicleCamera计算后得到的CameraNode mCameraNode = mVehicleCamer->getCameraNode(); //创建车的附加物体外设 createPeriphery(); CompositorManager::getSingleton().addCompositor(mWindow->getViewport(0), "Radial Blur"); CompositorManager::getSingleton().setCompositorEnabled(mWindow->getViewport(0), "Radial Blur", false); tforce = ttortue = NxVec3(0, 0, 0); isJet = false; }
static void CreateCube(const NxVec3& pos, const NxVec3 * vel = 0) { // Avoid creating one compound within another NxBounds3 bounds; bounds.setCenterExtents(pos, NxVec3(10.0f, 10.0f, 10.0f)); if(gScene->checkOverlapAABB(bounds)) return; // Create cube made up of 6 individual boxes as its faces, with each box having a different material NxActorDesc actorDesc; NxBodyDesc bodyDesc; bodyDesc.linearVelocity.set(0,5,0); if (vel) bodyDesc.linearVelocity += *vel; bodyDesc.angularVelocity.set(NxMath::rand(0.0f,10.0f),NxMath::rand(0.0f,10.0f),NxMath::rand(0.0f,10.0f)); //throw up the ball with a random initial angular vel as if to roll dice. NxBoxShapeDesc boxDesc[6]; boxDesc[0].dimensions.set(4,4,1); boxDesc[0].localPose.t.set(0,0,4); boxDesc[0].materialIndex = defaultMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[0]); boxDesc[1].dimensions.set(4,4,1); boxDesc[1].localPose.t.set(0,0,-4); boxDesc[1].materialIndex = somewhatBouncyMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[1]); boxDesc[2].dimensions.set(4,1,4); boxDesc[2].localPose.t.set(0,4,0); boxDesc[3].materialIndex = veryBouncyMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[2]); boxDesc[3].dimensions.set(4,1,4); boxDesc[3].localPose.t.set(0,-4,0); boxDesc[3].materialIndex = defaultMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[3]); boxDesc[4].dimensions.set(1,4,4); boxDesc[4].localPose.t.set(4,0,0); boxDesc[4].materialIndex = frictionlessMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[4]); boxDesc[5].dimensions.set(1,4,4); boxDesc[5].localPose.t.set(-4,0,0); boxDesc[5].materialIndex = highFrictionMaterialIndex; actorDesc.shapes.pushBack(&boxDesc[5]); actorDesc.body = &bodyDesc; actorDesc.density = 10.0f; actorDesc.globalPose.t = pos; gScene->createActor(actorDesc); }
void ProcessCameraKeys() { NxReal deltaTime; if (bPause) deltaTime = 0.02; else deltaTime = gDeltaTime; // Process camera keys for (int i = 0; i < MAX_KEYS; i++) { if (!gKeys[i]) { continue; } switch (i) { // Camera controls case 'w':{ gCameraPos += gCameraForward*gCameraSpeed*deltaTime; break; } case 's':{ gCameraPos -= gCameraForward*gCameraSpeed*deltaTime; break; } case 'a':{ gCameraPos -= gCameraRight*gCameraSpeed*deltaTime; break; } case 'd':{ gCameraPos += gCameraRight*gCameraSpeed*deltaTime; break; } case 'z':{ gCameraPos -= NxVec3(0,1,0)*gCameraSpeed*deltaTime; break; } case 'q':{ gCameraPos += NxVec3(0,1,0)*gCameraSpeed*deltaTime; break; } } } }
CPhysicUserData* CPhysicsManager::RaycastClosestActorShoot ( const Vect3f _vPosRay, const Vect3f& _vDirRay, uint32 _uiImpactMask, SCollisionInfo& _Info, float _fPower ) { //NxUserRaycastReport::ALL_SHAPES assert(m_pScene != NULL); NxRay ray; ray.dir = NxVec3 ( _vDirRay.x, _vDirRay.y, _vDirRay.z ); ray.orig = NxVec3 ( _vPosRay.x, _vPosRay.y, _vPosRay.z ); NxRaycastHit hit; NxShape* closestShape = NULL; closestShape = m_pScene->raycastClosestShape ( ray, NX_ALL_SHAPES, hit, _uiImpactMask ); if (!closestShape) { //No hemos tocado a ningún objeto físico de la escena. return NULL; } NxActor* actor = &closestShape->getActor(); CPhysicUserData* impactObject =(CPhysicUserData*)actor->userData; //Si está petando aquí quiere decir que se ha registrado un objeto físico sin proporcionarle UserData assert(impactObject); _Info.m_fDistance = hit.distance; _Info.m_Normal = Vect3f(hit.worldNormal.x, hit.worldNormal.y, hit.worldNormal.z ); _Info.m_CollisionPoint = Vect3f(hit.worldImpact.x, hit.worldImpact.y, hit.worldImpact.z ); Vect3f l_vDirection( _vDirRay.x-_vPosRay.x,_vDirRay.y-_vPosRay.y,_vDirRay.z-_vPosRay.z ); l_vDirection.Normalize(); NxVec3 l_vDirectionVec( _vDirRay.x, _vDirRay.y, _vDirRay.z ); NxF32 coeff = actor->getMass() * _fPower; actor->addForceAtLocalPos ( l_vDirectionVec*coeff, NxVec3(0,0,0), NX_IMPULSE,true ); return impactObject; }
void TumblingRobot::Create(){ if(this->pScene == NULL){ #ifdef _DEBUG std::cout<< "pScene == NULL at TumblingRobot::Create()" << std::endl; #endif //_DEBUG return; } TumblingBody* body = new TumblingBody(pScene, position); TumblingArm* leftArm = new TumblingArm(pScene, position, NxVec3(-2, 0, 0), NxQuat(-10, NxVec3(0, 1, 0)) ); TumblingArm* rightArm = new TumblingArm(pScene, position, NxVec3(2, 0, 0), NxQuat(10, NxVec3(0, 1, 0)) ); NxRevoluteJointDesc leftJointDesc; leftJointDesc.setToDefault(); leftJointDesc.actor[0] = body->getActor(); leftJointDesc.actor[1] = leftArm->getActor(); leftJointDesc.setGlobalAnchor(position + NxVec3(2, 0, 0)); leftJointDesc.setGlobalAxis(NxMat33(leftArm->getLocalOrientation()) * NxVec3(1, 0, 0)); NxJoint* leftJoint = pScene->createJoint( leftJointDesc ); NxRevoluteJointDesc rightJointDesc; rightJointDesc.setToDefault(); rightJointDesc.actor[0] = body->getActor(); rightJointDesc.actor[1] = rightArm->getActor(); rightJointDesc.setGlobalAnchor(position + NxVec3(2, 0, 0)); rightArm->getLocalOrientation(); rightJointDesc.setGlobalAxis(NxMat33(rightArm->getLocalOrientation()) * NxVec3(1, 0, 0)); NxJoint* rightJoint = pScene->createJoint( rightJointDesc ); //Register Parts this->parts.push_back(body); this->parts.push_back(leftArm); this->parts.push_back(rightArm); //Register Joints this->joints.push_back(leftJoint); this->joints.push_back(rightJoint); WalkControl* cWalk = new WalkControl(pHost); ArmControl* cLeftArm = new ArmControl(pHost); ArmControl* cRightArm = new ArmControl(pHost); cWalk->addTarget(cLeftArm); cWalk->addTarget(cRightArm); clients.push_back(cWalk); clients.push_back(cLeftArm); clients.push_back(cRightArm); pHost->addClient(cWalk); pHost->addClient(cLeftArm); pHost->addClient(cRightArm); leftArm->setClient(cLeftArm); rightArm->setClient(cRightArm); return; }
bool CPhysBody::Create(AABB boundingbox, Vec3 position, bool dynamic) { NxActorDesc actorDesc; NxBodyDesc bodyDesc; NxBoxShapeDesc boxDesc; //set size //boxDesc.dimensions.set(boundingbox.GetExtent(0), boundingbox.GetExtent(1), boundingbox.GetExtent(2)); boxDesc.dimensions.set((boundingbox.max.x - boundingbox.min.x)/2, (boundingbox.max.y - boundingbox.min.y)/2, (boundingbox.max.z - boundingbox.min.z)/2); //set local position within the body boxDesc.localPose.t = NxVec3(boundingbox.GetCenter(0), boundingbox.GetCenter(1), boundingbox.GetCenter(2)); //boxDesc.localPose.t = NxVec3(0.0f, 0.0f, 0.0f); actorDesc.shapes.pushBack(&boxDesc); if(dynamic) actorDesc.body = &bodyDesc; else actorDesc.body = 0; //set actor's global position actorDesc.globalPose.t = NxVec3(position.x, position.y, position.z); actorDesc.density = 10; m_pActor = g_pPhysScene->createActor(actorDesc); m_pActor->userData = new sNxActorUserData; return true; }
void RenderCallback() { if (gScene && !bPause) { StartPhysics(); GetPhysicsResults(); } // Clear buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ProcessInputs(); ProcessCameraKeys(); SetupCamera(); RenderActors(bShadows); // Render all the cloths in the scene for (MyCloth **cloth = gCloths.begin(); cloth != gCloths.end(); cloth++) { glColor4f(1.0f, 0.0f, 0.0f,1.0f); (*cloth)->draw(bShadows); } if (bForceMode) DrawForce(gSelectedActor, gForceVec, NxVec3(1,1,0)); else DrawForce(gSelectedActor, gForceVec, NxVec3(0,1,1)); gForceVec = NxVec3(0,0,0); // Render HUD hud.Render(); glFlush(); glutSwapBuffers(); }
void Simulation::buildModelBall(int indexScene){ NxBall* ball = Simulation::gScenes[indexScene]->ball; ball->ball = Simulation::getActorBall(indexScene); //velocidade maxima permitida segundo as rule 2010 (10m/s) //A bola pode atingir velocidade maior pq tem o caso de esta sendo usada pelo driblador, mas a principio consideremos isso ball->ball->setMaxAngularVelocity(10000./21.5); //0.031 medido da bola do lab //46g a bola da rules 2010 //estimativa da bola do laboratorio 31g ball->ball->setMass(0.046); //PLUGIN TAH COM PROBLEMA XML ERRADO //TODO: LEVANTAR INERTIA TENSOR, CMASS, DAMPINGS //float teste = ball->ball->getAngularDamping(); //ball->ball->setCMassOffsetGlobalPosition(NxVec3(0, 0, 0)); ball->ball->setCMassOffsetLocalPose( NxMat34( NxMat33(NxVec3(8.37673, 0, 0), NxVec3(0, 8.37673, 0), NxVec3(0, 0, 8.37673)), NxVec3(0, 0, 0) ) ); ball->ball->setAngularDamping(0.5); ball->ball->setLinearDamping(0.5); ball->ball->setMassSpaceInertiaTensor(/*ball->ball->getMassSpaceInertiaTensor()*100000.*/ NxVec3(8.37673, 8.37673, 8.37673) ); ball->initialPose = ball->ball->getGlobalPose(); ball->indexScene = indexScene; ball->ball->putToSleep(); }
void idle() { calcFPS(); glCheckError("idle"); static Timer t; double dt = t.elapsed_time(); if(IS_KEY_DOWN('w') || IS_KEY_DOWN('W')) g_CameraPos += g_CameraForward*g_Speed*dt; if(IS_KEY_DOWN('s') || IS_KEY_DOWN('S')) g_CameraPos -= g_CameraForward*g_Speed*dt; if(IS_KEY_DOWN('q') || IS_KEY_DOWN('Q')) g_CameraPos +=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt; if(IS_KEY_DOWN('e') || IS_KEY_DOWN('E')) g_CameraPos -=NxVec3(0.0f,1.0f,0.0f)*g_Speed*dt; if(IS_KEY_DOWN('a') || IS_KEY_DOWN('A')) g_CameraPos -= g_CameraRight*g_Speed*dt; if(IS_KEY_DOWN('d') || IS_KEY_DOWN('D')) g_CameraPos += g_CameraRight*g_Speed*dt; t.reset(); glutPostRedisplay(); }
bool CreateScenario() { DestroyScenario(); // Create the scene NxSceneDesc sceneDesc; sceneDesc.gravity = gDefaultGravity; sceneDesc.simType = bHWScene? NX_SIMULATION_HW : NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(0 == gScene) { bHWScene = !bHWScene; sceneDesc.simType = bHWScene? NX_SIMULATION_HW : NX_SIMULATION_SW; gScene = gPhysicsSDK->createScene(sceneDesc); if(0 == gScene) return false; } // Create the default material NxMaterial* defaultMaterial = gScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.5); defaultMaterial->setStaticFriction(0.5); defaultMaterial->setDynamicFriction(0.5); // Create the plane in primary scene groundPlane = CreateGroundPlane(); // Create compartment(HSM, managed hardware scene) attached to this scene NxCompartmentDesc desc; desc.type = NX_SCT_RIGIDBODY; desc.deviceCode = NxU32(NX_DC_PPU_0); gCompartmentHW = gScene->createCompartment(desc); desc.deviceCode = NxU32(NX_DC_CPU); gCompartmentSW = gScene->createCompartment(desc); // Create objects boxHW = CreateManagedBox(NxVec3(6, 0, 0), NxVec3(0.5, 1, 0.5), 20, gCompartmentHW); boxSW = CreateManagedBox(NxVec3(3, 0, 0), NxVec3(0.5, 1, 0.5), 20, gCompartmentSW); sphereHW = CreateManagedSphere(NxVec3(-6,0,0), 1, 10, gCompartmentHW); sphereHW = CreateManagedSphere(NxVec3(-3,0,0), 1, 10, gCompartmentSW); capsule = CreateManagedCapsule(NxVec3(0,0,0), 2, 1, 5, 0); gSelectedActor = boxHW; // Initialize HUD InitializeHUD(); // Start the first frame of the simulation StartPhysics(); return true; }
void CPhysicActor::SetLinearVelocity (const Vect3f& velocity) { if (m_pPhXActor) { if (velocity != v3fZERO) { m_pPhXActor->setLinearVelocity( NxVec3( velocity.x, velocity.y, velocity.z) ); } } else { //TODO log de error... } }
void DrawEllipse(NxU32 nbSegments, const NxMat34& matrix, const NxVec3& color, const NxF32 radius1, const NxF32 radius2, const bool semicircle) { NxF32 step = NxTwoPiF32/NxF32(nbSegments); NxU32 segs = nbSegments; if(semicircle) { segs /= 2; } for(NxU32 i=0;i<segs;i++) { NxU32 j=i+1; if(j==nbSegments) j=0; NxF32 angle0 = NxF32(i)*step; NxF32 angle1 = NxF32(j)*step; NxVec3 p0,p1; matrix.multiply(NxVec3(radius1 * sinf(angle0), radius2 * cosf(angle0), 0.0f), p0); matrix.multiply(NxVec3(radius1 * sinf(angle1), radius2 * cosf(angle1), 0.0f), p1); DrawLine(p0, p1, color); } }
void NPCAssist::onUpdate(float dt) { // follow cat toy until it is roaming if( getNPC()->getCatToy()->getPhase() == ::jpRoaming ) { call( new NPCFollow( getNPC(), 75.0f ) ); } // pull and drop ward's pilotchute else if( _ward && !_ward->getFreefallActor()->isSleeping() ) { // pilotchute pull frame Vector3f pp = Jumper::getLineHandJoint( getNPC()->getJumper()->getClump() )->getPos(); Vector3f py = _ward->getClump()->getFrame()->getPos() - getNPC()->getJumper()->getClump()->getFrame()->getPos(); py.normalize(); Vector3f px; px.cross( py, Vector3f(0,1,0) ); px.normalize(); Vector3f pz; py.cross( px, py ); pz.normalize(); // check wind float windSpeed = 0.5f * ( getNPC()->getScene()->getLocation()->getWindAmbient() + getNPC()->getScene()->getLocation()->getWindBlast() ); Vector3f wardAt = _ward->getClump()->getFrame()->getAt(); wardAt.normalize(); if( windSpeed < 2.0f || Vector3f::dot( wardAt, getNPC()->getScene()->getLocation()->getWindDirection() ) < 0 ) { // connect pilot chute _ward->getPilotchuteSimulator()->connect( _ward->getFreefallActor(), Jumper::getBackBone( _ward->getClump() ), _ward->getLocalPilotAnchor() ); // pull pilotchute _ward->getPilotchuteSimulator()->pull( Matrix4f( px[0], px[1], px[2], 0.0f, py[0], py[1], py[2], 0.0f, pz[0], pz[1], pz[2], 0.0f, pp[0], pp[1], pp[2], 1.0f ) ); _ward->getPilotchuteSimulator()->updateActivity( 0.0f ); // and drop _ward->getPilotchuteSimulator()->drop( NxVec3( 0,0,0 ) ); _ward->getPilotchuteSimulator()->setInflation( 0.25f ); } // and no longer track the ward happiness :) _ward = NULL; } }
Cutter::Cutter(NxVec3 pos, string fname) { m_cutterHeight = 0.0f; m_cutterRotateAngle = 0.0f; m_cutterON = false; m_cutterParams = new CutterParams; m_attachedTriPod = NULL; CfgLoader cfg(fname, m_cutterParams->getVariableList()); //D3DXMatrixRotationYawPitchRoll(&dimm->matChassisRotation, rotateChassis.y, rotateChassis.x, rotateChassis.z); ObjectParams temp; temp.loadFromFile("Objects\\" + m_cutterParams->chassisModel); m_objChassis = new Surface(temp.meshName, temp.generateMaterial(), Vec3(0, 0, 0)); temp.loadFromFile("Objects\\" + m_cutterParams->cutterModel); m_objCutter = new Surface(temp.meshName, temp.generateMaterial(), Vec3(0, 0, 0)); Vec3 min = m_objChassis->boundingBox.Min; //min.y -= 1.0f; Vec3 max = m_objChassis->boundingBox.Max; //max.y += 0.5f; m_actionBox = new ActionBox(min, max); core.game->getWorld()->addToWorld(m_objChassis, NO_COLLISION, 0, GROUP_NON_COLLIDABLE, NULL, 1); core.game->getWorld()->addToWorld(m_objCutter, NO_COLLISION, 0, GROUP_NON_COLLIDABLE, NULL, 1); m_cutterParams->dimm = Vec3(m_objChassis->boundingBox.getWidth()/2, m_objChassis->boundingBox.getHeight()/6, m_objChassis->boundingBox.getDepth()/2); m_actor = core.dynamics->createBox(pos, NxVec3(m_cutterParams->dimm), m_cutterParams->density); SetActorCollisionGroup(m_actor, GROUP_COLLIDABLE_NON_PUSHABLE); NxMaterial *anisoMaterial = NULL; //if(!anisoMaterial) { //Create an anisotropic material NxMaterialDesc material; //Anisotropic friction material material.restitution = 0.01f; material.staticFriction = 0.01f; material.dynamicFriction = 0.01f; material.dynamicFrictionV = 0.1f; material.staticFrictionV = 0.1f; material.dirOfAnisotropy.set(1,0,0); material.flags = NX_MF_ANISOTROPIC; anisoMaterial = core.dynamics->getScene()->createMaterial(material); } m_actor->getShapes()[0]->setMaterial(anisoMaterial->getMaterialIndex()); }
bool PhysicsManager::createScene() { if(!mSDK) return false; // Create a scene NxSceneDesc sceneDesc; sceneDesc.setToDefault(); //sceneDesc.timeStepMethod = NX_TIMESTEP_VARIABLE; sceneDesc.timeStepMethod = NX_TIMESTEP_FIXED; sceneDesc.gravity = NxVec3(0.0f, -14.1f, 0.0f); sceneDesc.simType = NX_SIMULATION_SW; mScene = mSDK->createScene(sceneDesc); if(mScene == NULL) { printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n"); return false; } mScene->setActorGroupPairFlags(0,0,NX_NOTIFY_ON_START_TOUCH|NX_NOTIFY_ON_TOUCH|NX_NOTIFY_ON_END_TOUCH); // Set default material NxMaterial* defaultMaterial = mScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane //NxPlaneShapeDesc planeDesc; //NxActorDesc actorDesc; //actorDesc.shapes.pushBack(&planeDesc); //mScene->createActor(actorDesc); mScene->setUserTriggerReport(this); mScene->setUserContactReport(this); mIsSceneCreated = true; mIsRunningSim = true; mCurrentTime = 0; return true; }
/*===============================================*/ CLaserBase::CLaserBase( void ) : m_pMouse( MOUSE ) , m_lpAGLEffect( nullptr ) , m_pHitObject( nullptr ) , m_pHitActor( nullptr ) , m_LaserReverseFlag( false ) { // 本体のメッシュの読み込み m_lpXFile = XFILE_MANAGER->Load( m_pd3d->GetDevice() , m_FilePass + "Object/Player/AntiGravityLaser/AGL.x" ); std::string AGLEffectPass = m_FilePass; AGLEffectPass += "Object/Player/AntiGravityLaser/AGLEffect.x"; m_lpAGLEffect = XFILE_MANAGER->Load ( m_pd3d->GetDevice() , AGLEffectPass ); m_Material = m_lpAGLEffect->GetMaterial(); m_vPos = D3DXVECTOR3( 0.8f , -0.5f , 0.0f ); m_vRot = D3DXVECTOR3( -3.0f , -4.0f , 0.0f ); // パーティクルエフェクトの作成 if( m_pParticleEmitter == nullptr ) m_pParticleEmitter = new CParticleEmitter( m_pPhysX->GetScene() , 5.0f , NxVec3( 0.0f , 5.0f , 0.0f ) ); // レーザー部分の作成 m_pLaser = new CLaser(); // ライトの初期化 ZeroMemory( &m_Light , sizeof( D3DLIGHT9 ) ); m_Light.Type = D3DLIGHT_POINT; // ポイントライト m_Light.Diffuse = D3DXCOLOR( 1.0f , 1.0f , 1.0f , 1.0f ); // ディフューズ色 m_Light.Specular = D3DXCOLOR( 1.0f , 1.0f , 1.0f , 1.0f ); // スペキュラー色 m_Light.Ambient = D3DXCOLOR( 1.0f , 1.0f , 1.0f , 1.0f ); // アンビエント色 m_Light.Position = D3DXVECTOR3( 0.0f , 0.0f , 0.0f ); // ライトの位置 m_Light.Range = 25.0f; // ライトの有効範囲 m_Light.Attenuation0 = 0.0f; // 減衰定数 // ライトを追加する m_LightIndex = m_pd3d->GetCLightManager()->AddLight( m_Light , FALSE ); // マテリアルの取得 //m_Material = m_lpXFile->GetMaterial(); }
void PxCloth::processTick( const Move *move ) { // Make sure the cloth is created. if ( !mCloth ) return; // TODO: Remove this hack! const bool enableWind = Con::getBoolVariable( "$PxCloth::enableWind", false ); if ( enableWind ) { NxVec3 windVec( 25.0f + NxMath::rand(-5.0f, 5.0f), NxMath::rand(-5.0f, 5.0f), NxMath::rand(-5.0f, 5.0f) ); mCloth->setWindAcceleration( windVec ); // Wake the cloth! mCloth->wakeUp(); } else mCloth->setWindAcceleration( NxVec3( 0, 0, 0 ) ); // Update bounds. if ( mWorld->getEnabled() ) { NxBounds3 box; mCloth->getWorldBounds( box ); Point3F min = pxCast<Point3F>( box.min ); Point3F max = pxCast<Point3F>( box.max ); mWorldBox.set( min, max ); mObjBox = mWorldBox; getWorldTransform().mul( mObjBox ); } else { mObjBox.set( 0, mThickness * -0.5f, 0, mPatchSize.x, mThickness * 0.5f, mPatchSize.y ); } resetWorldBox(); // Update the VB on the next render. mIsVBDirty = true; }
NxActor* CreateBox(const NxVec3& pos) { // Add a single-shape actor to the scene NxActorDesc actorDesc; NxBodyDesc bodyDesc; // The actor has one shape, a box, 1m on a side NxBoxShapeDesc boxDesc; boxDesc.dimensions.set(0.5,0.5,0.5); actorDesc.shapes.pushBack(&boxDesc); actorDesc.body = &bodyDesc; actorDesc.density = 10; actorDesc.globalPose.t = NxVec3(pos.x,pos.y,pos.z); return gScene->createActor(actorDesc); }
void updateTestObjects() { if(!gFreeze) frameCount++; //hacky hack if(followPart) { //camera following an object //setFollowTargetAndPanning(Vec3((float*)(followPart->act->getGlobalPosition()+NxVec3(0,20,0)).get()),frameCount*0.0002f); setFollowTargetAndPanning(Vec3((float*)(followPart->act->getGlobalPosition()+NxVec3(0,10,0)).get()),0); } //update all existing machines //also freeze this?? check BOOST_FOREACH(Machine* m, machines) { //m->update(frameCount/60.0f); m->update(frameCount*simTimeStep); }
void CreateExperiment() { switch (gExperimentType) { case LANDER: { gScene->releaseActor(*groundPlane); groundPlane=NULL; // will be recreated with the container cell CreateExperimentMaterials(); CreateContainerCell(gCellSize); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES,0); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS,0); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES,1); gPhysicsSDK->setParameter(NX_VISUALIZE_WORLD_AXES,0); //gLander=CreateLander(NxVec3(0.0f,0.0f,0.0f)); gLander=CreateLander(NxVec3(0.0f,gCellSize/2.0f,0.0f)); IdentifyGravitators(); if (gLander) { ReOrientActor(gLander); SpinActor(gLander,gLandingRoughness*sqrt(gCellSize*gDefaultGravity.magnitude()/(gLander->getMassSpaceInertiaTensor().magnitude()))); LaunchActor(gLander,gLandingRoughness*sqrt(gCellSize*gDefaultGravity.magnitude())); gSelectedActor=gLander; gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES,gLanderSize.magnitude()); isRunning=true; } else { printf("Error: Unable to create lander\a\n"); isRunning=false; } break; } case LAY_SUBSTRATE: { gScene->releaseActor(*groundPlane); groundPlane=NULL; // will be recreated with the container cell CreateExperimentMaterials(); CreateContainerCell(gCellSize); gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES,0); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_FNORMALS,0); gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES,1); gPhysicsSDK->setParameter(NX_VISUALIZE_WORLD_AXES,0); //ThrowStone(); isRunning=true; break; } default: {printf("Error: unimplemented experiment type\a\n"); isRunning=false; break;} } }
std::shared_ptr<SphericalJoint> PhysicsLib::createSphericalJoint(std::shared_ptr<ActorBase> &a, std::shared_ptr<ActorBase> &b, const VC3 &globalAnchor) { SphericalJoint *joint = 0; if(a && b && data->scene) { NxSphericalJointDesc jointDesc; jointDesc.setToDefault(); jointDesc.actor[0] = a->getActor(); jointDesc.actor[1] = b->getActor(); jointDesc.setGlobalAnchor(NxVec3(globalAnchor.x, globalAnchor.y, globalAnchor.z)); // Limits etc stuff? jointDesc.swingLimit.value = PI/20.f; /* jointDesc.swingLimit.value = PI/20.f; static int foofoo = 0; int value = foofoo++; if(value == 0) jointDesc.swingLimit.value /= 2.f; if(value == 1) jointDesc.swingLimit.value /= 2.f; if(value == 2) jointDesc.swingLimit.value /= 2.f; if(value == 3) jointDesc.swingLimit.value /= 2.f; */ jointDesc.swingLimit.restitution = 1.f; jointDesc.flags |= NX_SJF_SWING_LIMIT_ENABLED; jointDesc.twistLimit.low.value = -PI/8.f; jointDesc.twistLimit.high.value = PI/8.f; jointDesc.flags |= NX_SJF_TWIST_LIMIT_ENABLED; joint = new SphericalJoint(*data->scene, jointDesc, a, b); if(!joint->isValid()) { delete joint; joint = 0; } } return std::shared_ptr<SphericalJoint> (joint); }
//----------------------------------------------------------------------- bool PhysXBridge::initNx(Real gravityY) { if (!mPhysicsSDK) { // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; mPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, 0, new PhysXLogging(), desc, &errorCode); if(!mPhysicsSDK) { EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot initialise the PhysX SDK.", "PhysXBridge::initNx"); } mPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05f); } // Create a scene if (!mScene) { NxSceneDesc sceneDesc; sceneDesc.gravity = NxVec3(0.0f, gravityY, 0.0f); mScene = mPhysicsSDK->createScene(sceneDesc); if(!mScene) { EXCEPT(Exception::ERR_INTERNAL_ERROR, "PU: Cannot create a PhysX Scene.", "PhysXBridge::initNx"); } // Set the contact report mScene->setUserContactReport(&mPhysXContactReport); // Set default material NxMaterial* defaultMaterial = mScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(0.0f); defaultMaterial->setStaticFriction(0.5f); defaultMaterial->setDynamicFriction(0.5f); // Create ground plane createPlane(); } // Create a controller ControllerManager& controllerManager = ControllerManager::getSingleton(); ControllerValueRealPtr physXBridgeUpdateValue(PU_NEW PhysXBridgeUpdateValue(this)); mTimeController = controllerManager.createFrameTimePassthroughController(physXBridgeUpdateValue); return true; }
/** * Initializes the bee's attributes * * * @return bool */ bool Bee::DoExtraInits() { if (!GameCharacter::DoExtraInits()) { return false; } // add a health attribute HealthAttributePtr health = NiNew HealthAttribute(this); m_fMaxHealth = ConfigurationManager::Get()->bee_initialHealth; health->Reset(m_fMaxHealth); AddAttribute(GameCharacter::ATTR_HEALTH, (CharacterAttribute*)health); // add an armor attribute AddAttribute(GameCharacter::ATTR_ARMOR, NiNew ArmorAttribute(this)); // add a damage attribute DamageAttribute* dmg = NiNew DamageAttribute(this); dmg->Reset(ConfigurationManager::Get()->bee_damage); AddAttribute(GameCharacter::ATTR_DAMAGE, dmg); // add an FSMBeeAIControl AddAttribute(GameCharacter::ATTR_CONTROLLER, NiNew FSMBeeAIControl(this)); // set initial position m_pActor->setGlobalPosition(GameManager::Get()-> GetQueen()->GetActor()->getGlobalPosition() - NxVec3(50.0, 0.0, 0.0)); SoundPtr sound = ResourceManager::Get()->GetSound( ResourceManager::RES_SOUND_BEE, this); if (sound) { AddAttribute(GameCharacter::ATTR_SOUND_DEFAULT, (CharacterAttribute*)sound); sound->Play(); } AddAttribute(GameCharacter::ATTR_SOUND_1, (CharacterAttribute*) ResourceManager::Get()->GetSound( ResourceManager::RES_SOUND_BEE_AWAITING, this)); AddAttribute(GameCharacter::ATTR_SOUND_2, (CharacterAttribute*) ResourceManager::Get()->GetSound( ResourceManager::RES_SOUND_BEE_DYING, this)); // set dampings m_pActor->setLinearDamping(8.0f); m_pActor->setAngularDamping(8.0f); return true; }
static void CreateCube(NxU32 sceneIndex, const NxVec3& pos, int size=2, const NxVec3* initial_velocity=NULL) { // Create body NxBodyDesc BodyDesc; BodyDesc.angularDamping = 0.5f; if(initial_velocity) BodyDesc.linearVelocity = *initial_velocity; NxBoxShapeDesc BoxDesc; BoxDesc.dimensions = NxVec3(float(size), float(size), float(size)); NxActorDesc ActorDesc; ActorDesc.shapes.pushBack(&BoxDesc); ActorDesc.body = &BodyDesc; ActorDesc.density = 10.0f; ActorDesc.globalPose.t = pos; gScenes[sceneIndex]->createActor(ActorDesc)->userData = (void*)size; }
//----------------------------------------------------------------------------- // CreateBox //----------------------------------------------------------------------------- NxActor* CPhysicScene::CreateBox (const NxVec3& pos, const NxVec3& boxDim, const NxReal density) { // Add a single-shape actor to the scene NxActorDesc actorDesc; NxBodyDesc bodyDesc; // The actor has one shape, a box NxBoxShapeDesc boxDesc; boxDesc.dimensions.set (boxDim.x, boxDim.y, boxDim.z); boxDesc.localPose.t = NxVec3 (0, boxDim.y, 0); actorDesc.shapes.pushBack (&boxDesc); actorDesc.body = &bodyDesc; actorDesc.density = density; actorDesc.globalPose.t = pos; return m_pScene->createActor(actorDesc); }
//----------------------------------------------------------------------------- // CreateSphere //----------------------------------------------------------------------------- NxActor* CPhysicScene::CreateSphere (const NxVec3& pos, const NxReal radius, const NxReal density) { // Add a single-shape actor to the scene NxActorDesc actorDesc; NxBodyDesc bodyDesc; // The actor has one shape, a sphere NxSphereShapeDesc sphereDesc; sphereDesc.radius = radius; sphereDesc.localPose.t = NxVec3 (0, radius, 0); actorDesc.shapes.pushBack (&sphereDesc); actorDesc.body = &bodyDesc; actorDesc.density = density; actorDesc.globalPose.t = pos; return m_pScene->createActor(actorDesc); }
void SweptCapsule::ComputeTemporalBox(const SweepTest& test, NxExtendedBounds3& box, const NxExtendedVec3& center, const NxVec3& direction) const { NxVec3 mExtents(mRadius, mRadius, mRadius); mExtents[test.mUpDirection] += mHeight*0.5f; //mExtents *= 2.0f; const NxVec3 SkinExtents = mExtents + NxVec3(test.mSkinWidth, test.mSkinWidth, test.mSkinWidth); NxExtendedVec3 tmp = center; tmp += direction; NxExtendedBounds3 DestBox; DestBox.setCenterExtents(tmp, SkinExtents); box.setCenterExtents(center, SkinExtents); box.add(DestBox); }
static bool SweepBoxMesh(const SweepTest* sweep_test, const SweptVolume* volume, const TouchedGeom* geom, const NxExtendedVec3& center, const NxVec3& dir, SweptContact& impact) { ASSERT(volume->GetType()==SWEPT_BOX); ASSERT(geom->mType==TOUCHED_MESH); const SweptBox* SB = static_cast<const SweptBox*>(volume); const TouchedMesh* TM = static_cast<const TouchedMesh*>(geom); NxU32 NbTris = TM->mNbTris; if(!NbTris) return false; // Fetch triangle data for current mesh (the stream may contain triangles from multiple meshes) const NxTriangle* T = &sweep_test->mWorldTriangles[TM->mIndexWorldTriangles]; const NxTriangle* ET = &sweep_test->mWorldEdgeNormals[TM->mIndexWorldEdgeNormals]; const NxU32* EdgeFlags = &sweep_test->mEdgeFlags[TM->mIndexEdgeFlags]; NxBounds3 Box; Box.setCenterExtents(NxVec3(float(center.x - TM->mOffset.x), float(center.y - TM->mOffset.y), float(center.z - TM->mOffset.z)), SB->mExtents); // Precompute // PT: this only really works when the CCT collides with a single mesh, but that's the most common case. When it doesn't, there's just no speedup but it still works. NxU32 CachedIndex = sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex]; if(CachedIndex>=NbTris) CachedIndex=0; NxVec3 Hit, Normal; float t; NxU32 Index; if(gUtilLib->NxSweepBoxTriangles(NbTris, T, ET, EdgeFlags, Box, dir, impact.mDistance, Hit, Normal, t, Index, &CachedIndex)) { if(t>=impact.mDistance) return false; impact.mDistance = t; impact.mWorldNormal = Normal; impact.mWorldPos.x = Hit.x + TM->mOffset.x; impact.mWorldPos.y = Hit.y + TM->mOffset.y; impact.mWorldPos.z = Hit.z + TM->mOffset.z; // Returned index is only between 0 and NbTris, i.e. it indexes the array of cached triangles, not the original mesh. assert(Index<NbTris); sweep_test->mCachedTriIndex[sweep_test->mCachedTriIndexIndex] = Index; // The CCT loop will use the index from the start of the cache... impact.mIndex = Index + TM->mIndexWorldTriangles; return true; } return false; }