Example #1
0
//----------------------------------------------------------------------------
// ReleaseAllActors : Alliberem tots els actors de l'escena de PhysX 
//----------------------------------------------------------------------------
bool CPhysicsManager::ReleaseAllActors ( void ) //EUserDataFlag _eFlags )
{
	assert ( m_pScene != NULL );
	assert ( m_pPhysicsSDK != NULL );

	bool isOk = true;

	NxActor** l_ppActorList = m_pScene->getActors();
	NxU32 l_TotalActors		= m_pScene->getNbActors();

	while ( l_TotalActors -- )
	{
		NxActor* nxActor = *l_ppActorList;
		if ( nxActor != 0)
		{
			NxArray<NxCCDSkeleton*> skeletons;
			for (NxU32 i = 0; i < nxActor->getNbShapes(); i++) 
			{
				NxShape* shape = nxActor->getShapes()[i];
				if (shape->getCCDSkeleton() != NULL) {
					skeletons.pushBack(shape->getCCDSkeleton());
				}
			}

			for (NxU32 i = 0; i < skeletons.size(); i++) 
			{
				m_pPhysicsSDK->releaseCCDSkeleton(*skeletons[i]);
			}
			m_pScene->releaseActor(*nxActor);
			nxActor = 0;
		}
	}
	
	return isOk;
}
bool CPhysicsManager::ReleasePhysicActor (CPhysicActor* actor)
{
	assert(actor != NULL);
	assert(m_pScene != NULL);
	assert(m_pPhysicsSDK != NULL);

	bool isOk = false;
	NxActor* nxActor = actor->GetPhXActor();

	if( nxActor != 0)
	{
		NxArray<NxCCDSkeleton*> skeletons;
		for (NxU32 i = 0; i < nxActor->getNbShapes(); i++) 
		{
			NxShape* shape = nxActor->getShapes()[i];
			if (shape->getCCDSkeleton() != NULL) {
				skeletons.pushBack(shape->getCCDSkeleton());
			}
		}

		for (NxU32 i = 0; i < skeletons.size(); i++) 
		{
			m_pPhysicsSDK->releaseCCDSkeleton(*skeletons[i]);
		}
		m_pScene->releaseActor(*nxActor);
		nxActor = 0;
	}
	
	return true;
}
void SetupTearingScene()
{
    sprintf(gTitleString, "Tearing Demo");

	// Create the objects in the scene
	groundPlane = CreateGroundPlane();
	NxActor* bar = CreateBox(NxVec3(0,12,0), NxVec3(3,0.5,0.5), 0);
	NxActor* box = CreateBox(NxVec3(-2.3,4.0,0), NxVec3(0.5,0.5,0.5), 10); 

	// Cloth
	NxClothDesc clothDesc;
	clothDesc.globalPose.t = NxVec3(2.5,12,0);
	clothDesc.globalPose.M.rotX(-NxHalfPiF32);
	clothDesc.thickness = 0.1;
	clothDesc.tearFactor = 2;
	clothDesc.flags |= NX_CLF_BENDING;
	clothDesc.flags |= NX_CLF_COLLISION_TWOWAY;
	clothDesc.flags |= NX_CLF_TEARABLE | NX_CLF_VISUALIZATION; // Tearable cloth

	if (gHardwareCloth)
		clothDesc.flags |= NX_CLF_HARDWARE;

	MyCloth* regularCloth = new MyCloth(gScene, clothDesc, 5, 8, 0.1, "rug512.bmp", gTearLines);
	gCloths.push_back(regularCloth);

	regularCloth->getNxCloth()->attachToShape(*bar->getShapes(), 0);
	regularCloth->getNxCloth()->attachToShape(*box->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY);
}
Example #4
0
void GravitateToGravitators()
{
	NxU32 nbActors = gScene->getNbActors();
	NxActor** actors = gScene->getActors();
	NxReal m1,m2,G=gUniversalBigG,R;
	NxVec3 r,F;
	while (nbActors--)
	{
		NxActor* actor = *actors++;
		const char* name=actor->getName();
		if (strcmp(name,"~lander")==0)
		{
			F.zero();
			m1=actor->getMass();
			for (int k=0; k<gRavitators.size(); k++)
			{
				r = (gRavitators[k]->getCMassGlobalPosition() - actor->getCMassGlobalPosition());
				R = r.magnitudeSquared();
				m2= gRavitators[k]->getMass();
				F = r;
				F.setMagnitude(G*m1*m2/R);
				actor->addForce(F);
			}
		}
	}
}
Example #5
0
void World::SetupFlagScene()
{
	NxActor* capsule = MyCreateCapsule(NxVec3(0.0f,-0.2f,0.0f), 10, 0.2f, 0);

	// Create Cloth
	NxClothDesc clothDesc;
	clothDesc.globalPose.t = NxVec3(0,10,0);
	clothDesc.globalPose.M.rotX(-NxHalfPiF32);
	clothDesc.thickness = 0.2;
	clothDesc.bendingStiffness = 0.5;
	clothDesc.dampingCoefficient = 1;
	clothDesc.flags |= NX_CLF_BENDING;
	//clothDesc.flags |= NX_CLF_DAMPING | NX_CLF_COMDAMPING;
	clothDesc.flags |= NX_CLF_COLLISION_TWOWAY | NX_CLF_VISUALIZATION;
	clothDesc.windAcceleration = NxVec3(-20, 20, 0);	// set wind

	MyCloth* regularCloth = new MyCloth(gScene, clothDesc, 5, 5, 0.15, "nvidia.bmp");

	if (!regularCloth->getNxCloth())
	{
		printf("Error: Cloth creation failed.\n");
		delete regularCloth;
	}
	else
	{
		gCloths.push_back(regularCloth);
		regularCloth->getNxCloth()->attachToShape(*capsule->getShapes(), NX_CLOTH_ATTACHMENT_TWOWAY);
	}
}
Example #6
0
void DrawLanders()
{
	// draw the landers in 2 colors
	NxU32 nbActors = gScene->getNbActors();
	NxActor** actors = gScene->getActors();
	while (nbActors--)
	{
		NxActor* actor = *actors++;
		const char *name=actor->getName();
		if (strcmp(name,"~lander")==0) {
			NxShape*const* shapes;
			shapes = actor->getShapes();
			NxU32 nShapes = actor->getNbShapes();
			//glDisable(GL_LIGHTING);
			char sname[256]="";
			while (nShapes--)
			{
				sprintf(sname,"%s",shapes[nShapes]->getName());
				if      (strcmp(sname,"upside")==0)
					glColor4f(0.0f,1.0f,0.0f,1.0f);
				else if (strcmp(sname,"downside")==0)
					glColor4f(1.0f,0.0f,0.0f,1.0f);
				else if (strcmp(sname,"U1")==0)
					glColor4f(1.0f,0.0f,0.0f,1.0f);
				else if (strcmp(sname,"U2")==0)
					glColor4f(0.0f,1.0f,0.0f,1.0f);
				else if (strcmp(sname,"U3")==0)
					glColor4f(0.0f,0.0f,1.0f,1.0f);
				DrawShape(shapes[nShapes], false);
			}
			//glEnable(GL_LIGHTING);
		}
	}
}
Example #7
0
//################################################################
//
// Body functions
//
pRigidBody*PhysicManager::getBody(const char*name,int flags/* =0 */)
{

	for (pWorldMapIt it  = getWorlds()->Begin(); it!=getWorlds()->End(); it++)
	{
		pWorld *w = *it;
		if(w)
		{
			int nbActors = w->getScene()->getNbActors();
			NxActor** actors = w->getScene()->getActors();
			while(nbActors--)
			{
				NxActor* actor = *actors++;
				if(actor->userData != NULL)
				{
					if (!strcmp(actor->getName(),name) )
					{

						pRigidBody* body =static_cast<pRigidBody*>(actor->userData);
						if (body)
						{
							return body;
						}
					}
				}
			}
		}
	}
	return 0;
}
Example #8
0
static void CreateCube(const NxVec3& pos, int size=2, const NxVec3* initial_velocity=NULL, bool kinematic = false, bool Static = false)
{
	// Create body
	NxBodyDesc BodyDesc;
	BodyDesc.angularDamping	= 0.5f;
	//	BodyDesc.maxAngularVelocity	= 10.0f;
	if(initial_velocity)	BodyDesc.linearVelocity = *initial_velocity;

	NxBoxShapeDesc BoxDesc;
	BoxDesc.dimensions		= NxVec3(float(size), float(size), float(size));

	NxActorDesc ActorDesc;
	//	ActorDesc.userData		= (void*)size;
	ActorDesc.shapes.pushBack(&BoxDesc);
	if (!Static)
		ActorDesc.body			= &BodyDesc;
	ActorDesc.density		= 10.0f;
	ActorDesc.globalPose.t  = pos;
	ActorDesc.userData = (void*)size;

	NxActor* actor = gMyPhysX.getScene()->createActor(ActorDesc);

	if (kinematic) {
		KinematicActor k;
		k.actor = actor;
		actor->raiseBodyFlag(NX_BF_KINEMATIC);
		if (initial_velocity) {
			k.vel = *initial_velocity;
		} else {
			k.vel.set(0,0,0);
		}
		gKinematicActors.pushBack(k);
	}

}
Example #9
0
NxActor* CreateBoard(const NxVec3& pos)
{
	NxActor* actor = CreateBox(pos + NxVec3(0,0.5,0), NxVec3(1,0.25,0.5), 10);
	actor->raiseBodyFlag(NX_BF_FROZEN_ROT_X);
	actor->setAngularDamping(0.5);

	// Left wheel
	NxWheelDesc wheelDesc;
	//wheelDesc.wheelAxis.set(0,0,1);
	//wheelDesc.downAxis.set(0,-1,0);
    wheelDesc.wheelApproximation = 10;
	wheelDesc.wheelRadius = 0.5;
	wheelDesc.wheelWidth = 0.1;
	wheelDesc.wheelSuspension = 0.5;
//	wheelDesc.wheelSuspension = 1.0;
	wheelDesc.springRestitution = 7000;
	wheelDesc.springDamping = 0;
	wheelDesc.springBias = 0;  
//	wheelDesc.springRestitution = 20;
//	wheelDesc.springDamping = 0.5;
//	wheelDesc.springBias = 0; 
	wheelDesc.maxBrakeForce = 1;
	wheelDesc.frictionToFront = 0.1;
	wheelDesc.frictionToSide = 0.99;
	wheelDesc.position = NxVec3(1.5,0.5,0);
	wheelDesc.wheelFlags = NX_WF_USE_WHEELSHAPE | NX_WF_BUILD_LOWER_HALF | NX_WF_ACCELERATED | 
		                   NX_WF_AFFECTED_BY_HANDBRAKE | NX_WF_STEERABLE_INPUT;

    wheel1 = AddWheelToActor(actor, &wheelDesc);

	// Right wheel
	NxWheelDesc wheelDesc2;
	//wheelDesc2.wheelAxis.set(0,0,1);
	//wheelDesc2.downAxis.set(0,-1,0);
    wheelDesc2.wheelApproximation = 10;
	wheelDesc2.wheelRadius = 0.5;
	wheelDesc2.wheelWidth = 0.1;
	wheelDesc2.wheelSuspension = 0.5;
//	wheelDesc2.wheelSuspension = 1.0;  
	wheelDesc2.springRestitution = 7000;
	wheelDesc2.springDamping = 0;
	wheelDesc2.springBias = 0;
//	wheelDesc2.springRestitution = 20;
//	wheelDesc2.springDamping = 0.5;
//	wheelDesc2.springBias = 0;  
	wheelDesc2.maxBrakeForce = 1;
	wheelDesc2.frictionToFront = 0.1;
	wheelDesc2.frictionToSide = 0.99;
	wheelDesc2.position = NxVec3(-1.5,0.5,0);
	wheelDesc2.wheelFlags = NX_WF_USE_WHEELSHAPE | NX_WF_BUILD_LOWER_HALF | NX_WF_ACCELERATED | 
		                    NX_WF_AFFECTED_BY_HANDBRAKE | NX_WF_STEERABLE_INPUT;

    wheel2 = AddWheelToActor(actor, &wheelDesc2);

	return actor;
}
Example #10
0
void KeyboardUpCallback(unsigned char key, int x, int y)
{
	gKeys[key] = false;

	switch (key)
	{
		case 'p': { bPause = !bPause; 
					if (bPause)
						hud.SetDisplayString(2, "Paused - Hit \"p\" to Unpause", 0.3f, 0.55f);
					else
						hud.SetDisplayString(2, "", 0.0f, 0.0f);	
					break; }
		case 'x': { bShadows = !bShadows; break; }
		case 'b': { bDebugWireframeMode = !bDebugWireframeMode; break; }		
		case 'f': { bForceMode = !bForceMode; break; }

		case 'o': 
		{     
			NxCloth** cloths = gScene->getCloths();
			for (NxU32 i = 0; i < gScene->getNbCloths(); i++) 
			{
				cloths[i]->setFlags(cloths[i]->getFlags() ^ NX_CLF_BENDING_ORTHO);
			}
			break;
		}

		case 'g': 
		{     
			NxCloth** cloths = gScene->getCloths();
			for (NxU32 i = 0; i < gScene->getNbCloths(); i++) 
			{
				cloths[i]->setFlags(cloths[i]->getFlags() ^ NX_CLF_GRAVITY);
			}
			break;
		}

		case 'y': 
		{
			NxCloth** cloths = gScene->getCloths();
			for (NxU32 i = 0; i < gScene->getNbCloths(); i++) 
			{
				cloths[i]->setFlags(cloths[i]->getFlags() ^ NX_CLF_BENDING);
			}	            
			break;
		}
		case ' ': 
		{
			NxActor* sphere = CreateSphere(gCameraPos, 1, 1);
			sphere->setLinearVelocity(gCameraForward * 20);
			break; 
		}
		case 27 : { exit(0); break; }
		default : { break; }
	}
}
Example #11
0
void PxWorld::_releaseQueues()
{
   AssertFatal( mScene, "PhysXWorld::_releaseQueues() - The scene is null!" );

   // We release joints still pending in the queue 
   // first as they depend on the actors.
   for ( S32 i = 0; i < mReleaseJointQueue.size(); i++ )
   {
      NxJoint *currJoint = mReleaseJointQueue[i];
      mScene->releaseJoint( *currJoint );
   }
   
   // All the joints should be released, clear the queue.
   mReleaseJointQueue.clear();

   // Now release any actors still pending in the queue.
   for ( S32 i = 0; i < mReleaseActorQueue.size(); i++ )
   {
      NxActor *currActor = mReleaseActorQueue[i];
      
      bool isStatic = !currActor->isDynamic();

      mScene->releaseActor( *currActor );

      if ( isStatic )
         PhysicsStatic::smDeleteSignal.trigger();
   }

   // All the actors should be released, clear the queue.
   mReleaseActorQueue.clear();

   // Now release any cloth still pending in the queue.
   for ( S32 i = 0; i < mReleaseClothQueue.size(); i++ )
   {
      NxCloth *currCloth = mReleaseClothQueue[i];
      mScene->releaseCloth( *currCloth );
   }

   // All the actors should be released, clear the queue.
   mReleaseClothQueue.clear();

   // Release heightfields that don't still have references.
   for ( S32 i = 0; i < mReleaseHeightFieldQueue.size(); i++ )
   {
      NxHeightField *currHeightfield = mReleaseHeightFieldQueue[i];
      
      if ( currHeightfield->getReferenceCount() == 0 )
      {
         gPhysicsSDK->releaseHeightField( *currHeightfield );      
         mReleaseHeightFieldQueue.erase_fast( i );
         i--;
      }
   }
}
Example #12
0
void IdentifyGravitators()
{
	gRavitators.clear();
	NxU32 nbActors = gScene->getNbActors();
	NxActor** actors = gScene->getActors();
	while (nbActors--)
	{
		NxActor* actor = *actors++;
		if (actor->getMass()>gRavitatorThresholdMass)
			gRavitators.push_back(actor);
	}
}
Example #13
0
void World::SetupAnimalScene()
{
	// Create the objects in the scene
	NxSoftBodyDesc softBodyDesc;
	softBodyDesc.globalPose.t		= NxVec3(0.0f, 3.0f, 0.0f);
	softBodyDesc.particleRadius		= 0.2f;
	softBodyDesc.volumeStiffness	= 0.5f;
	softBodyDesc.stretchingStiffness= 1.0f;
	softBodyDesc.friction			= 1.0f;
	softBodyDesc.attachmentResponseCoefficient = 0.1f;
	softBodyDesc.solverIterations	= 5;

	char *fileName = "froggyNormalized";

	char tetFileName[256], objFileName[256], s[256];
	sprintf(tetFileName, "%s.tet", fileName);
	sprintf(objFileName, "%s.obj", fileName);

	ObjMesh *objMesh = new ObjMesh();
	objMesh->loadFromObjFile(FindMediaFile(objFileName, s));
	gObjMeshes.pushBack(objMesh);

	if(objMesh == NULL)
	{
		printf("objMesh %s\n");
	}

	NxMat33 rot;
	rot.rotX(NxHalfPiF32);

	for (int i = 0; i < 5; i++)
	{
		softBodyDesc.globalPose.t	= NxVec3(0, 3+i*3, 0);
		MySoftBody *softBody		= new MySoftBody(gScene, softBodyDesc, FindMediaFile(tetFileName, s), objMesh);
		assert(softBody);
		if (!softBody->getNxSoftBody())
		{
			printf("Error: unable to create the softbody for the current scene.\n");
			delete softBody;
		}
		else
		{
			gSoftBodies.pushBack(softBody);
			NxActor *caps = MyCreateCapsule(NxVec3(0.0f, 3.0f + i*3.0f, -0.3f), 1.0f, 0.73f, 1.0f);
			caps->userData = (void*)&gInvisible;
			caps->setGlobalOrientation(rot);
			softBody->getNxSoftBody()->attachToShape(caps->getShapes()[0], NX_SOFTBODY_ATTACHMENT_TWOWAY);
		}
	}
}
Example #14
0
void myTrigger::onTrigger(NxShape& triggerShape, NxShape& otherShape, NxTriggerFlag status){

	if ( ! triggerShape.getActor().userData && ! otherShape.getActor().userData )
	{
		return;
	}
	
	if (status & NX_TRIGGER_ON_ENTER)
	{
		// A body just entered the trigger area
		NxActor* triggerActor = &triggerShape.getActor();
		String name = triggerActor->getName();
		int thisTarget = StringConverter::parseInt(name);
		creditTarget(thisTarget);
	}
	
}
Example #15
0
	virtual bool handle( const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
	{
		osgViewer::Viewer *viewer=dynamic_cast<osgViewer::Viewer*>(&aa);
		if(!viewer) return false;

		switch(ea.getEventType())
		{
		case osgGA::GUIEventAdapter::FRAME:
			{
				//printf("Time %f\n",ea.getTime());
				gMyPhysX.simulate(1.0f/60.0f);
				int nbActors = gMyPhysX.getScene()->getNbActors();
				NxActor** actors = gMyPhysX.getScene()->getActors();
				//int userdateNum = 0;
				while(nbActors--)
				{
					NxActor* actor = *actors++;
					if(!actor->userData) continue;
					osg::MatrixTransform *mt = static_cast<osg::MatrixTransform*>(actor->userData);
					if (mt)
					{
						float glmat[16];      
						actor->getGlobalPose().getColumnMajor44(glmat);//得到角色的世界位置			

						osg::Matrix mat;
						mat.set(glmat);
						mt->setMatrix(mat);
						//userdateNum+=1;
						//printf("userdateNum = %d\n",userdateNum);
					}
				}				
				return false;
			}
		case(osgGA::GUIEventAdapter::KEYDOWN):
			{
				if(ea.getKey()=='w'||ea.getKey()=='W')
				{
					CreateCubeFromEye(2,viewer->getCamera());
				}
				return false;
			}
		default:
			return false;
		}
	}
void CPhysicsManager::ReleaseActorCapsule (CPhysicActor* actor)
{
	assert(actor != NULL);
	assert(m_pScene != NULL);
	assert(m_pPhysicsSDK != NULL);

	NxActor* nxActor = actor->GetPhXActor();
	if( nxActor != 0)
	{
		NxArray<NxCCDSkeleton*> skeletons;
		for (NxU32 i = 0; i < nxActor->getNbShapes(); i++) 
		{
			NxShape* shape = nxActor->getShapes()[i];
			if (shape->isCapsule())
				shape->setGroup(ECG_LAST_GROUP);	
		}
	}
}
Example #17
0
void PxWorld::releaseActor( NxActor &actor )
{
   AssertFatal( &actor.getScene() == mScene, "PhysXWorld::releaseActor() - Bad scene!" );

   // Clear the userdata.
   actor.userData = NULL;   

   // If the scene is not simulating then we have the
   // write lock and can safely delete it now.
   if ( !mIsSimulating )
   {
      bool isStatic = !actor.isDynamic();
      mScene->releaseActor( actor );
      if ( isStatic )
         PhysicsStatic::smDeleteSignal.trigger();
   }
   else
      mReleaseActorQueue.push_back( &actor );
}
Example #18
0
void PhysUpdate ( void )
{
	int iObject = 1;

    // Render all the actors in the scene
    int nbActors = gScene->getNbActors();
    NxActor** actors = gScene->getActors();

	while (nbActors--)
    {
        NxActor* actor = *actors++;

		// Get an OpenGL transform (float[16]) from a Novodex shape’s global pose     
		// (NxMat34)
		NxShape* shape = NULL;

		NxMat34 pose = actor->getGlobalPose();

		NxMat33 orient = pose.M;
		NxVec3 pos = pose.t;	

		float glmat[16];    // 4x4 column major OpenGL matrix
		orient.getColumnMajorStride4(&(glmat[0]));
		pos.get(&(glmat[12]));

		// clear the elements we don't need:
		glmat[3] = glmat[7] = glmat[11] = 0.0f;
		glmat[15] = 1.0f;

		{
			sPhysObject* pPhys = ( sPhysObject* ) actor->userData;
			
			if ( pPhys )
			{
				SetWorldMatrix ( pPhys->iID, ( D3DXMATRIX* ) &glmat );

				sObject* pObject = dbGetObject ( pPhys->iID );

				pObject->position.vecPosition = D3DXVECTOR3 ( glmat [ 12 ], glmat [ 13 ], glmat [ 14 ] );
			}
		}
    }
}
//-----------------------------------------------------------------------------
//  ApplyExplosionPart
//-----------------------------------------------------------------------------
void    CPhysicObj::ApplyExplosionPart (int nPartIdx, float fForce, const NxVec3& vPos)
{
    assert( m_bActivated && (nPartIdx < GetNumParts()) );

	// Solo podemos aplicar fuerzas a objetos físicos dinámicos
	if (!IsDynamic())	return;

    NxActor*    pActor = GetActor( nPartIdx );

    // Aplicamos una fuerza en cada shape, proporcional a su volumen.
    // NOTA: Para que fuese mas realista realmente habria que modular la 
    //       fuerza en funcion de la superficie de proyeccion de cada shape
    //       hacia el punto de origen de la explosion, para aproximar lo que
    //       seria la superficie de impacto.
    uint    nNumShapes = pActor->getNbShapes();
    assert( nNumShapes > 0 );

    NxShape* const* pShapes = pActor->getShapes(); 
    for (uint i = 0; i < nNumShapes; i++)
    {
        NxShape*    pShape = pShapes[i];
        // - Calcular BBox de la shape
        NxBox       shapeBox = PhysicUtils::CalcOBBox( *pShape );
        // - Calcular punto de impacto de la explosion
        NxVec3      vImpactPoint = PhysicUtils::CalcExplosionImpact( shapeBox, vPos );
        //NxVec3      vImpactPoint = shapeBox.GetCenter();
        // - Modular la fuerza de la explosion por el area expuesta de la shape
        float       fVolume     = (shapeBox.extents * 2.f).magnitudeSquared();            
        float       fForceMod   = fForce * fVolume;
        // - Modular a su vez en funcion de la distancia al centro de la explosion
        //   usando una funcion exponencial de atenuacion
        NxVec3      vImpactDir  = vImpactPoint - vPos;
        float       fDist       = vImpactDir.normalize();
        // NOTA: vamos a marcar una zona de radio minimo donde se aplique la fuerza maxima
        //static float s_fMinDist = 0.1f;
        //fDist += s_fMinDist;
        static float s_fAttenuationFactor = 0.05f;
        fForceMod *= exp( -s_fAttenuationFactor * fDist );
        // - Aplicar la fuerza en el punto de impacto
        pActor->addForceAtPos( vImpactDir * fForceMod, vImpactPoint, NX_IMPULSE );
    }
}
Example #20
0
void render()
{
	static Timer t;
	if(gScene && !gPauseSimulation)  //start the simulation
	{
		gTouchedTris.clear();
		gScene->simulate(t.elapsed_time());
		//printf("%f\n",t.elapsed_time());
		t.reset();
		gScene->flushStream();
		/*ASYNC: in here we can do computations which depend only on the old
	      state of the scene "actors". Writing to the scene is not allowed.
		  Write calls in here are skipped.
		*/
		gScene->fetchResults(NX_RIGID_BODY_FINISHED,true);
	}
	// Clear buffers
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	glColor4f(0.0,1.0,1.0,1.0);
	DrawSkyBox(5000.0f);
	//drawPlane(2000.0);
	 //Render all actors
	int nbActors = gScene->getNbActors();
	NxActor** actors = gScene->getActors();
	while(nbActors--)
	{
		NxActor* actor = *actors++;
		if(!actor->userData) continue;

		// Render actor
		glPushMatrix();
		float glMat[16];
		actor->getGlobalPose().getColumnMajor44(glMat);
		glMultMatrixf(glMat);
		NxVec3 color = static_cast<UserData*>(actor->userData)->color;
		glColor4f(color.x,color.y,color.z,1.0f);
		glutSolidCube((static_cast<UserData*>(actor->userData)->size)*2.0f);
		glPopMatrix();
	}
	RenderTerrain();
}
Example #21
0
void SceneManager::init()
{
	m_SceneManager = m_Root->createSceneManager(Ogre::ST_GENERIC, "Bow and Arrow");

	NxPlaneShapeDesc groundPlaneDesc;
	PhysicsManager::instance()->getPlaneDesc(Ogre::Vector3(0,1,0),0,&groundPlaneDesc);
	NxActor* T = PhysicsManager::instance()->addActor(groundPlaneDesc);
	T->setGlobalPosition(NxVec3(0,0,0));

	//Create the level
	m_Level = new Level();
	m_Level->createLevel();
	m_Level->parseLevelFile("BloodGulch.scene","General", m_SceneManager);

	if ( PhysicsManager::instance()->loadPhysxCollection("../../Media/Level/LevelPhysicsScene.xml") )
	{
		m_Player = new Player("Test Player", Ogre::Vector3(0,0,-20), Controller, m_SceneManager);
	}

}
Example #22
0
	SoftBone(const NXU::NxuBone &b,unsigned int acount,NxActor **alist,SoftBone *parent)
  {
  	mParent = parent;
		mActor = 0;

		for (unsigned int i=0; i<acount; i++)
		{
			NxActor *a = alist[i];
			const char *name = a->getName();
			if ( name )
			{
				if ( strcmp(name, b.mName) == 0 )
				{
					mActor = a;
					break;
				}
			}
		}

		NxQuat q( b.mOrientation );
		mLocalTransform.M.fromQuat(q);
		mLocalTransform.t.set( b.mPosition );

		if ( mActor )
		{
			mGlobalTransform = mActor->getGlobalPose();
		}
		else
		{
			if ( mParent )
			{
  			mGlobalTransform = parent->mGlobalTransform * mLocalTransform;
			}
  		else
			{
  			mGlobalTransform = mLocalTransform;
			}
		}

		mGlobalTransform.getInverse(mComposite);
  }
bool CPhysicsManager::AddPhysicActor (CPhysicActor* actor, float mass)
{
	assert(actor != NULL);
	assert( m_pScene != NULL );

	bool isOk = false;
	NxActor* nxActor;
	NxActorDesc* actorDesc = actor->GetActorDesc();

	assert(actorDesc!=NULL);
	nxActor = m_pScene->createActor( *actorDesc );
	if (nxActor!=NULL)
	{
		nxActor->userData = actor->GetUserData();
		if (mass > 0.0f)
			nxActor->setMass(mass);
		actor->CreateActor(nxActor);
		isOk = true;
	}

	return isOk;
}
CPhysicUserData* CPhysicsManager::RaycastClosestActorShoot (const Vect3f posRay, const Vect3f& dirRay, uint32 impactMask, SCollisionInfo& info, float _fPower)
{

	//NxUserRaycastReport::ALL_SHAPES
	assert(m_pScene != NULL);

	NxRay ray; 
	ray.dir =  NxVec3(dirRay.x, dirRay.y, dirRay.z);
	ray.orig = NxVec3(posRay.x, posRay.y, posRay.z);

	NxRaycastHit hit;
	NxShape* closestShape = NULL;

	closestShape = m_pScene->raycastClosestShape(ray, NX_ALL_SHAPES, hit, impactMask);
	if (!closestShape) 
	{
		//No hemos tokado 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(dirRay.x-posRay.x,dirRay.y-posRay.y,dirRay.z-posRay.z);
	l_vDirection.Normalize();

	NxVec3 l_vDirectionVec(dirRay.x,dirRay.y,dirRay.z); 
	NxF32 coeff = actor->getMass() * _fPower;
	actor->addForceAtLocalPos(l_vDirectionVec*coeff, NxVec3(0,0,0), NX_IMPULSE,true);


	return impactObject;
}
void AddUserDataToActors(NxScene* scene)
{
    NxU32 i = 0;

	NxActor** actors = scene->getActors();
	NxU32 nbActors = scene->getNbActors();
	while (nbActors--)
	{
		NxActor* actor = actors[nbActors];
        actor->userData = new ActorUserData;
		((ActorUserData *)(actor->userData))->id = i++;
		// FIXME: After setting it, actorDesc.managedHwSceneIndex gets cleared for some reason...
#if 0
		NxActorDesc actorDesc;
		actor->saveToDesc(actorDesc);
		if (actorDesc.managedHwSceneIndex > 0)  
		{
			// To identify the actor when render it, set a bit in the userdata flags
			((ActorUserData *)(actor->userData))->flags |= UD_IS_HW_ACTOR;
		}
#endif
        AddUserDataToShapes(actor);
	}
}
Example #26
0
void ParticleEmitter::addParticle()
{

	if ((_iTailIndex == _iHeadIndex) && (_iParticleCount != 0)) // FIFO is full
	{
		removeParticle();
		// Now there is a slot free
	}

	// Add a single-shape actor to the scene
	NxActorDesc actorDesc;
	NxBodyDesc bodyDesc;

	NxSphereShapeDesc sphereDesc;
	sphereDesc.radius = 1.0f;
	sphereDesc.group = cParticleCollisionGroup; // this group does not collide with itself
	actorDesc.shapes.pushBack(&sphereDesc);

	actorDesc.body = &bodyDesc;
	actorDesc.density = 10.0f;
	actorDesc.globalPose.t = _vStartingPos;

	NxActor* pNewActor =  _pScene->createActor(actorDesc);

	// Give it an initial linear velocity, scaled by _fStartingVelScale
	NxVec3 vRandVec(NxReal(rand()*_fStartingVelScale), NxReal(rand()*_fStartingVelScale), NxReal(rand()*_fStartingVelScale));
	pNewActor->setLinearVelocity(vRandVec);

	// Turn off gravity for smoke
	pNewActor->raiseBodyFlag(NX_BF_DISABLE_GRAVITY);

	_aParticleArray[_iHeadIndex] = new Particle(pNewActor, _vThermoDynamicAcceleration);

	_iHeadIndex = (_iHeadIndex+1) % ciMaxParticles;
	++_iParticleCount;
}
Example #27
0
NxActor* PxSingleActorData::createActor( NxScene *scene, const NxMat34 *nxMat, const Point3F& scale )
{
   if ( !scene )
   {
      Con::errorf( "PxSingleActorData::createActor() - returned null NxScene" );
      return NULL;
   }

   PxSingleActor_Notify pxNotify( scale );

   NXU::instantiateCollection( physicsCollection, *gPhysicsSDK, scene, nxMat, &pxNotify );

   NxActor *actor = pxNotify.getActor();

   actor->setGlobalPose( *nxMat );

   if ( !actor )
   {
      Con::errorf( "PxSingleActorData::createActor() - Could not create actor!" );
      return NULL;
   }

   return actor;
}