Пример #1
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);
		}
	}
}
Пример #2
0
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;
}
Пример #3
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;
}
		//-----------------------------------------------------------------------
		void PhysXActorExtern::_processParticle(
			ParticleTechnique* particleTechnique, 
			Particle* particle, 
			Ogre::Real timeElapsed, 
			bool firstParticle)
		{
			// Only update after a PhysX simulation step
			if (mSynchronize)
			{
				if (particle->particleType != Particle::PT_VISUAL)
					return;

				if (!particle->physicsActor)
					return;

				VisualParticle* visualParticle = static_cast<VisualParticle*>(particle);
				PhysXActor* physXActor = static_cast<PhysXActor*>(particle->physicsActor);
				NxActor* nxActor = physXActor->nxActor;
				if (nxActor)
				{
					// Synchronize both the particle and the pysicsActor with the nxActor
					particle->position = PhysXMath::convert(nxActor->getGlobalPosition());
					particle->direction = PhysXMath::convert(nxActor->getLinearVelocity());
					visualParticle->orientation = PhysXMath::convert(nxActor->getGlobalOrientationQuat());
					physXActor->position = particle->position;
					physXActor->direction = particle->direction;
					physXActor->orientation = visualParticle->orientation;

					if (nxActor->getNbShapes())
					{
						NxShape *shape = nxActor->getShapes()[0]; // Max one.
						switch(shape->getType())
						{
							case NX_SHAPE_BOX:
								(static_cast<NxBoxShape*>(shape))->setDimensions(
									PhysXMath::convert(0.5 * Ogre::Vector3(
									visualParticle->width, visualParticle->height, visualParticle->depth)));
							break;
							 case NX_SHAPE_SPHERE:
								(static_cast<NxSphereShape*>(shape))->setRadius(0.5f * visualParticle->width);
							break;
							case NX_SHAPE_CAPSULE:
							{
								(static_cast<NxCapsuleShape*>(shape))->setRadius(0.5f * visualParticle->width);
								(static_cast<NxCapsuleShape*>(shape))->setHeight(0.5f * visualParticle->height);
							}
							break;
						}
					}
				}
			}
		}
Пример #5
0
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);	
		}
	}
}
Пример #6
0
//-----------------------------------------------------------------------------
//  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 );
    }
}
Пример #7
0
void PhysicsLib::updateVisualization(const VC3 &cameraPosition, float range, bool forceUpdate)
{
	bool visualizeCollisionShapes = data->featureMap[PhysicsLib::VISUALIZE_COLLISION_SHAPES];
	bool visualizeDynamic = data->featureMap[PhysicsLib::VISUALIZE_DYNAMIC];
	bool visualizeStatic = data->featureMap[PhysicsLib::VISUALIZE_STATIC];
	bool visualizeCollisionContacts = data->featureMap[PhysicsLib::VISUALIZE_COLLISION_CONTACTS];
	bool visualizeFluids = data->featureMap[PhysicsLib::VISUALIZE_FLUIDS];
	bool visualizeJoints = data->featureMap[PhysicsLib::VISUALIZE_JOINTS];
	bool visualizeCCD = data->featureMap[PhysicsLib::VISUALIZE_CCD];

	if (forceUpdate
		|| visualizeCollisionShapes
		|| visualizeDynamic
		|| visualizeStatic
		|| visualizeCollisionContacts
		|| visualizeFluids
		|| visualizeJoints
		|| visualizeCCD)
	{
		// (do the update)
	} else {
		// do not unnecessarily do this stuff!
		return;
	}

	float rangeSq = range * range;

	int actorAmount = data->scene->getNbActors();
	NxActor **actorArray = data->scene->getActors();

	if(visualizeCollisionShapes || visualizeStatic || visualizeCollisionContacts)
		data->sdk->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	else
		data->sdk->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 0);

	if(visualizeDynamic)
		data->sdk->setParameter(NX_VISUALIZE_BODY_MASS_AXES, 1);
	else
		data->sdk->setParameter(NX_VISUALIZE_BODY_MASS_AXES, 0);

	data->sdk->setParameter(NX_VISUALIZE_CONTACT_NORMAL, visualizeCollisionContacts);
	data->sdk->setParameter(NX_VISUALIZE_CONTACT_FORCE, visualizeCollisionContacts);
	data->sdk->setParameter(NX_VISUALIZE_CONTACT_POINT, visualizeCollisionContacts);

	data->sdk->setParameter(NX_VISUALIZE_COLLISION_SKELETONS, visualizeCCD);	

	for(int i = 0; i < actorAmount; ++i)
	{
		NxActor *actor = actorArray[i];
		if(!actor)
			continue;

		NxVec3 nxpos = actor->getGlobalPosition();
		VC3 pos(nxpos.x, nxpos.y, nxpos.z);
		VC3 diff = (pos - cameraPosition);
		diff.y = 0; // ignore height

		bool inRange = false;		
		if (diff.GetSquareLength() < rangeSq)
			inRange = true;

		if(actor->isDynamic())
		{
			//if(visualizeDynamic && inRange)
			if(visualizeDynamic)
				actor->raiseBodyFlag(NX_BF_VISUALIZATION);
			else
				actor->clearBodyFlag(NX_BF_VISUALIZATION);
		}

		int shapeAmount = actor->getNbShapes();
		NxShape *const*shapes = actor->getShapes();

		while(shapeAmount--)
		{
			NxShape *shape = shapes[shapeAmount];

			if(actor->isDynamic())
			{
				//if(visualizeCollisionShapes && inRange)
				if(visualizeCollisionShapes)
					shape->setFlag(NX_SF_VISUALIZATION, true);
				else
					shape->setFlag(NX_SF_VISUALIZATION, false);
			}
			else
			{
				if(visualizeStatic && !shape->isHeightField() && inRange)
					shape->setFlag(NX_SF_VISUALIZATION, true);
				else
					shape->setFlag(NX_SF_VISUALIZATION, false);
			}
		}
	}
}
Пример #8
0
void Controller::move(SweptVolume& volume, const NxVec3& disp, NxU32 activeGroups, NxF32 minDist, NxU32& collisionFlags, NxF32 sharpness, const NxGroupsMask* groupsMask, bool constrainedClimbingMode)
	{
	// Dynamic-load the utility library
	if(!gUtilLib)
		gUtilLib = NxGetUtilLib();
	assert(gUtilLib);
	if(!gUtilLib)	return;

	SweepTest* ST = &cctModule;

	// Init CCT with per-controller settings
	ST->debugData		= manager->debugData;
	ST->mSkinWidth		= skinWidth;
	ST->mStepOffset		= stepOffset;
	ST->mUpDirection	= upDirection;
	ST->mHandleSlope	= handleSlope;
	ST->mSlopeLimit		= slopeLimit;
	ST->mFirstUpdate	= true;

	///////////

	Controller** boxUserData = NULL;
	NxExtendedBounds3* boxes = NULL;
	NxU32 nbBoxes = 0;

	Controller** capsuleUserData = NULL;
	NxExtendedCapsule* capsules = NULL;
	NxU32 nbCapsules = 0;

	if(1)
		{
		// Experiment - to do better
		NxU32 nbControllers = manager->getNbControllers();
		Controller** controllers = manager->getControllers();

		boxes = (NxExtendedBounds3*)NxAlloca(nbControllers*sizeof(NxExtendedBounds3));
		capsules = (NxExtendedCapsule*)NxAlloca(nbControllers*sizeof(NxExtendedCapsule));	// It's evil to waste that ram
		boxUserData = (Controller**)NxAlloca(nbControllers*sizeof(Controller*));
		capsuleUserData = (Controller**)NxAlloca(nbControllers*sizeof(Controller*));

		while(nbControllers--)
			{
			Controller* currentController = *controllers++;
			if(currentController==this)	continue;

			NxActor* pActor = currentController->getActor();
			int nbShapes = pActor->getNbShapes();
			NX_ASSERT( nbShapes == 1 );
			NxShape* pCurrentShape= pActor->getShapes()[0];

			// Depending on user settings the current controller can be:
			// - discarded
			// - always kept
			// - or tested against filtering flags
			NxCCTInteractionFlag interactionFlag = currentController->getInteraction();
			bool keepController = true;
			if(interactionFlag==NXIF_INTERACTION_EXCLUDE)			keepController = false;
			else if(interactionFlag==NXIF_INTERACTION_USE_FILTER)	keepController = (activeGroups & ( 1 << pCurrentShape->getGroup()))!=0;

			if(keepController)
				{
				if(currentController->type==NX_CONTROLLER_BOX)
					{
					currentController->getWorldBox(boxes[nbBoxes]);
					boxUserData[nbBoxes++] = currentController;
					}
				else if(currentController->type==NX_CONTROLLER_CAPSULE)
					{
					CapsuleController* CC = static_cast<CapsuleController*>(currentController);
					NxExtendedVec3 p0 = CC->position;
					NxExtendedVec3 p1 = CC->position;
					p0[ST->mUpDirection] -= CC->height*0.5f;
					p1[ST->mUpDirection] += CC->height*0.5f;
					capsules[nbCapsules].p0 = p0;
					capsules[nbCapsules].p1 = p1;
					capsules[nbCapsules].radius = CC->radius;
					capsuleUserData[nbCapsules++] = currentController;
					}
				else ASSERT(0);
				}
			}
		}

	///////////

	ST->mWalkExperiment = false;

	NxExtendedVec3 Backup = volume.mCenter;
	ST->MoveCharacter(scene,
		(Controller*)this,
		volume, disp,
		nbBoxes, nbBoxes ? boxes : NULL, nbBoxes ? (const void**)boxUserData : NULL,
		nbCapsules, nbCapsules ? capsules : NULL, nbCapsules ? (const void**)capsuleUserData : NULL,
		activeGroups, minDist, collisionFlags, groupsMask, constrainedClimbingMode);

	if(ST->mHitNonWalkable)
		{
		// A bit slow, but everything else I tried was less convincing...
		ST->mWalkExperiment = true;
		volume.mCenter = Backup;
		ST->MoveCharacter(scene,
			(Controller*)this,
			volume, disp,
			nbBoxes, nbBoxes ? boxes : NULL, nbBoxes ? (const void**)boxUserData : NULL,
			nbCapsules, nbCapsules ? capsules : NULL, nbCapsules ? (const void**)capsuleUserData : NULL,
			activeGroups, minDist, collisionFlags, groupsMask, constrainedClimbingMode);
		ST->mWalkExperiment = false;
		}

if(sharpness<0.0f)
volume.mCenter = Backup;

	// Copy results back
	position = volume.mCenter;

	NxVec3 Delta = Backup - volume.mCenter;
	NxF32 deltaM2 = Delta.magnitudeSquared();
	if(deltaM2!=0.0f)
		{
		// Update kinematic actor
		if(kineActor)
			kineActor->moveGlobalPosition(NxVec3((float)position.x, (float)position.y, (float)position.z));
		}

	filteredPosition = position;

sharpness = fabsf(sharpness);

	// Apply feedback filter if needed
	if(sharpness<1.0f)
		filteredPosition[upDirection] = feedbackFilter(position[upDirection], memory, sharpness);

//	if(manager->debugData)
//		manager->debugData->addAABB(cctModule.mCachedTBV, NX_ARGB_YELLOW);
	}
Пример #9
0
void Part::render()
{
	assert(act && "partrender: physics equivalent invalid");
	glPushMatrix();
	float glMat[16];
	NxActor* actor;
	actor=act;
	if(NULL==actor) return;
	actor->getGlobalPose().getColumnMajor44(glMat);
	glMultMatrixf(glMat);

	if(actor->userData!=NULL && gRenderUserData) {
		glPushMatrix();
		((GraphicsObject*)actor->userData)->render();
		glPopMatrix();
	}
	else {
		//render according to shape descriptions in actor
		for(unsigned s=0; s < actor->getNbShapes(); s++) {
			NxShape *shape = actor->getShapes()[s];

			glPushMatrix();
			shape->getLocalPose().getColumnMajor44(glMat);
			glMultMatrixf(glMat);

			//render shapes
			if(shape->getFlag(NX_TRIGGER_ENABLE)) {
				//do nothing, triggers are not to be rendered and have different userdata
			}
			else if(shape->userData!=NULL) {
				((GraphicsObject*)shape->userData)->render();
			}
			else {
				NxShapeType type=shape->getType();
				if(NX_SHAPE_BOX==type) {
					NxBoxShape *sh=(NxBoxShape *)shape;
					NxVec3 dim=sh->getDimensions();
					BoxGraphicsObject g(dim.x,dim.z,dim.y);  //wrond dimensions
					g.render();
				}
				else if(NX_SHAPE_CAPSULE==type) {
					NxCapsuleShape *sh=(NxCapsuleShape *)shape;
					float radius=sh->getRadius();
					float height=sh->getHeight();
					CapsuleGraphicsObject g(radius,height);
					g.render();
				}
				else if(NX_SHAPE_SPHERE==type) {
					NxSphereShape *sh=(NxSphereShape *)shape;
					float radius=sh->getRadius();
					SphereGraphicsObject g(radius);
					g.render();
				}
				else {
					//render a default sphere if shape type unknown
					SphereGraphicsObject sg(1);
					sg.render();
				}

			}
			glPopMatrix();
		}
	}
	glPopMatrix();
}
Пример #10
0
void ReCreateExperiment()
{
	gScene->simulate(0);
	gScene->checkResults(NX_ALL_FINISHED,true); // make sure time step is done
	
	// Re-set the crucial SDK parameters
	if (gPhysicsSDK)
	{
		gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES,0);
		gPhysicsSDK->setParameter(NX_VISUALIZE_WORLD_AXES,0);
		if (gBounceEps>0)
			gPhysicsSDK->setParameter(NX_BOUNCE_THRESHOLD,-gBounceEps);
		if (gSkinWidth>0)
			gPhysicsSDK->setParameter(NX_SKIN_WIDTH, gSkinWidth);
	}
	if (gScene)
	{
		if (bVarTimeStep)
			gScene->setTiming(gDeltaTime/4.0,4,NX_TIMESTEP_VARIABLE);
		else
			gScene->setTiming(gDeltaTime/4.0,4,NX_TIMESTEP_FIXED);
		gScene->setGravity(gDefaultGravity*bGravity);
	}

	// Next get to cleaning up the scene that was maybe loaded from file.
	if (gScene)
	{
		// Get rid of defined materials (who knows where they've been...)
		NxMaterial* mats[20]; // I hardly think we'll have more than 20
		NxU32 iter=0; // don't worry about it
		int nmats = gScene->getMaterialArray(mats,20,iter);
		while (nmats--)
		{
			gScene->releaseMaterial(*(mats[nmats]));
		}
		gCellMaterial=NULL;
		gLanderUpMaterial=NULL;
		gLanderDownMaterial=NULL;

		CreateExperimentMaterials(); // make shiny new materials

		// Now, look over all the actors, who knows where they've been. Find out then.
		NxU32 nbActors = gScene->getNbActors();
		NxActor** actors = gScene->getActors();
		while (nbActors--)
		{
			NxActor* actor = *actors++;
			const char *name=actor->getName();
			NxShape*const* shapes;
			shapes = actor->getShapes();
			NxU32 nShapes = actor->getNbShapes();

			// If it's a rubble grain, make sure it uses the default material
			if      (strcmp(name,"rubble")==0 || strcmp(name,"boulder")==0)
				while (nShapes--) shapes[nShapes]->setMaterial(0);

			// If it's a cell container, make sure it uses the cell material, and remember its pointer
			else if (strcmp(name,"left wall")==0) {
				shapes[0]->setMaterial(gCellMaterial->getMaterialIndex());
				gContainerCell[0]=actor;
			}
			else if (strcmp(name,"right wall")==0) {
				shapes[0]->setMaterial(gCellMaterial->getMaterialIndex());
				gContainerCell[1]=actor;
			}
			else if (strcmp(name,"in wall")==0) {
				shapes[0]->setMaterial(gCellMaterial->getMaterialIndex());
				gContainerCell[2]=actor;
			}
			else if (strcmp(name,"out wall")==0) {
				shapes[0]->setMaterial(gCellMaterial->getMaterialIndex());
				gContainerCell[3]=actor;
			}

			// If it's the ground plane it also uses default material
			else if (strcmp(name,"ground")==0) {
				shapes[0]->setMaterial(0);
				groundPlane=actor;
			}

			// If it's the lander, it has two shapes made of different material, but the lander will be recreated elsewhere...

			// Anything else, get rid of
			else
				gScene->releaseActor(*actor);
		
		}

		// If the container is damaged, recreate it
		for (int k=0; k<4; k++)
		{
			if (gContainerCell[k]==NULL) {
				for (int j=0; j<4; j++)
				{
					if (gContainerCell[j]) {
						gScene->releaseActor(*gContainerCell[j]);
						gContainerCell[j]=NULL;
					}
				}
				CreateContainerCell(gCellSize);
				break;
			}
		}
	}

	// OK, all clean, now create the experiment as needed.
	switch (gExperimentType) {
	case LANDER:
		gLander=CreateLander(NxVec3(0.0f,gCellSize/2,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()); // not sure why this is a problem when reading from previous xml
			isRunning=true;
		}
		else {
			printf("Error: Unable to create lander\a\n");
			isRunning=false;
		}
		break;
	case LAY_SUBSTRATE:
		{
			isRunning=true;
			break;
		}
	default:
		printf("Error: Unknown experiment type\a\n");
		isRunning=false;
		break;
	}
	if (!isManualControl){bPause=false;}
}
Пример #11
0
void NxRobot::cloneRobot(int indexNewScene, int indexNewRobot, NxVec3 newPosition, int indexNewTeam)
{
    NxRobot* nxRobotSource = Simulation::gScenes[this->indexScene]->allRobots->getRobotByIdByTeam(this->id, this->idTeam);

    NxActor* robotActor = Simulation::cloneActor(nxRobotSource->getActor(),indexNewScene);
    //NxBounds3 bodyBounds;
    //robotShapes[0]->getWorldBounds(bodyBounds);

    NxVehicleDesc vehicleDesc;

    vehicleDesc.position				= NxVec3(robotActor->getGlobalPosition());
    vehicleDesc.mass					= robotActor->getMass();
    //vehicleDesc.motorForce				= 70000;
    //vehicleDesc.maxVelocity				= 300.f;
    //vehicleDesc.cameraDistance			= 8.0f;
    vehicleDesc.centerOfMass.set(robotActor->getCMassLocalPosition());
    //vehicleDesc.differentialRatio = 3.42f;
    //vehicleDesc.transmissionEfficiency
    vehicleDesc.actor = robotActor;

    //Motor descricao
    //NxVehicleMotorDesc motorsDesc[4];
    //for(NxU32 i=0;i<4;i++)
    //{
    //motorsDesc[i].setToCorvette();
    //vehicleDesc.motorsDesc.push_back(&motorsDesc[i]);
    //}

    //Roda (Wheel) descricao
    int numberWheels = nxRobotSource->getNbWheels();
    NxWheelDesc* wheelDesc = new NxWheelDesc[numberWheels];
    for(NxU32 i=0; i<numberWheels; i++)
    {
        //NxActor* wheelModel = Simulation::getActorWheel(indexSourceScene,indexNewRobot,i);
        //NxActorDesc wheelActorDesc;
        //wheelModel->saveToDesc(wheelActorDesc);
        //Simulation::gScenes[0]->releaseActor(*wheelModel);

        //NxShape*const* wheelShapes = actorWheel->getShapes();
        //NxBounds3 wheelBounds;
        //wheelShapes[0]->getWorldBounds(wheelBounds);

        const NxWheel* wheel = nxRobotSource->getWheel(i);
        NxWheelShape* wheelShape = ((NxWheel2*)wheel)->getWheelShape();
        //wheelDesc[i].wheelApproximation = 10;
        wheelDesc[i].wheelOrientation = wheelShape->getGlobalOrientation();
        wheelDesc[i].position.set(wheelShape->getGlobalPosition()-robotActor->getGlobalPosition());
        //wheelDesc[i].position.z = 0;
        wheelDesc[i].id = i;
        wheelDesc[i].wheelFlags = ((NxWheel*)wheel)->getWheelFlags();
        wheelDesc[i].wheelRadius = wheel->getRadius();
        //wheelDesc[i].wheelWidth = 100;
        wheelDesc[i].wheelSuspension = wheelShape->getSuspensionTravel();
        wheelDesc[i].springRestitution = 0;
        wheelDesc[i].springDamping = 0;
        wheelDesc[i].springBias = 0.0f;
        wheelDesc[i].maxBrakeForce = 100;
        wheelDesc[i].frictionToFront = 0.1f;//0.1f;
        wheelDesc[i].frictionToSide = 0;//0.02f;//
        wheelDesc[i].inverseWheelMass = wheelShape->getInverseWheelMass(); //TODO: CONFIGURAR PARÂMETRO

        //Angulo das Rodas (Omni)
        wheelDesc[i].angWheelRelRobot = ((NxWheel2*)wheel)->angWheelRelRobot;

        vehicleDesc.robotWheels.pushBack(&wheelDesc[i]);
    }

    //Criar robot, vehicle base
    NxRobot* robot = (NxRobot*)NxRobot::createVehicle(Simulation::gScenes[indexNewScene], &vehicleDesc);
    //NxRobot* robot = (NxRobot*)NxRobot::createVehicle(gScenes[indexSourceScene], &vehicleDesc);
    robot->setId(indexNewRobot);
    robot->setIdTeam(indexNewTeam);
    robot->indexScene = indexNewScene;
    robot->bodyRadius = nxRobotSource->bodyRadius;

    //Dribbler and Kicker
    NxShape*const* robotShapes = robotActor->getShapes();
    for(int i=0; i<robotActor->getNbShapes(); i++) {
        const char* shapeName = robotShapes[i]->getName();
        if(shapeName) {
            char* dribblerName = new char[10];//"Driblador\0"
            dribblerName[9] = 0;
            memcpy(dribblerName, shapeName, strlen(dribblerName));

            if(strcmp(dribblerName, "Driblador") == 0) {
                robot->dribbler->dribblerShapes.push_back(robotShapes[i]);
            }
            delete dribblerName;
        }
    }
    robot->kicker->kickerShapeDesc = new NxBoxShapeDesc();
    NxShapeDesc* shapeDesc = nxRobotSource->kicker->kickerShapeDesc;
    robot->kicker->kickerShapeDesc->localPose = shapeDesc->localPose;
    ((NxBoxShapeDesc*)(robot->kicker->kickerShapeDesc))->dimensions = ((NxBoxShapeDesc*)shapeDesc)->dimensions;

    //Initial Pose
    robot->setInitialPose(robotActor->getGlobalPose());

    robotActor->putToSleep();

    //Transladando o robo
    robot->getActor()->setGlobalPosition(newPosition);

    string label;
    string plabel = "Robo";
    stringstream out;
    out << indexNewRobot;
    out << "-";
    out << indexNewTeam;
    //out << "-";
    //out << indexNewScene;
    label.append(plabel);
    label.append(out.str());
    char* arrayLabel = new char[label.size()+1];
    arrayLabel[label.size()]=0;
    memcpy(arrayLabel, label.c_str(), label.size());
    robotActor->setName(arrayLabel);
    //delete arrayLabel;
}
Пример #12
0
void Simulation::buildModelRobot(int indexRobot, int indexScene, int indexTeam)
{
    //Veiculo descricao
    //Body Descricao
    NxActor* robotActor = Simulation::getActorRobot(indexScene, indexRobot);
    //NxBounds3 bodyBounds;
    //robotShapes[0]->getWorldBounds(bodyBounds);
    NxVehicleDesc vehicleDesc;

    vehicleDesc.position				= NxVec3(robotActor->getGlobalPosition());
    float mass = 5.;
    vehicleDesc.mass					= mass;//robotActor->getMass(); //PLUGIN TAH COM PROBLEMA XML ERRADO
    //vehicleDesc.motorForce				= 70000;
    //vehicleDesc.maxVelocity				= 300.f;
    //vehicleDesc.cameraDistance			= 8.0f;
    vehicleDesc.centerOfMass.set(NxVec3(0,0,0));//robotActor->getCMassLocalPosition());
    //vehicleDesc.differentialRatio = 3.42f;
    //vehicleDesc.transmissionEfficiency
    vehicleDesc.actor = robotActor;
    vehicleDesc.actor->setMaxAngularVelocity(6.2);
    vehicleDesc.actor->setMass(mass);

    //TODO: LEVANTAR DAMPING
    float t = vehicleDesc.actor->getLinearDamping();
    float b = vehicleDesc.actor->getAngularDamping();
    //vehicleDesc.actor->setAngularDamping(0.5);
    //vehicleDesc.actor->setLinearDamping(0.5);

    //TODO: LEVANTAR CMASS E INERTIA TENSOR

    //vehicleDesc.actor->setCMassOffsetGlobalPosition(NxVec3(0, 0, 0));
    NxMat33 inertiaTensor = NxMat33(NxVec3(1294.4362, 3.14502, -66.954), NxVec3(3.14502, 1094.42351, -0.24279), NxVec3(-66.954, -0.24279, 1754.80511));
    vehicleDesc.actor->setCMassOffsetLocalPose( NxMat34( inertiaTensor, NxVec3(0,0,0) ) );
    //TODO: Diagonalizar inertiaTensor e passar para setMassSpaceInertiaTensor
    vehicleDesc.actor->setMassSpaceInertiaTensor(/*vehicleDesc.actor->getMassSpaceInertiaTensor()*1000.*/NxVec3(1764.3, 1284.9, 1094.4) );

    //Motor descricao
    //NxVehicleMotorDesc motorsDesc[4];
    //for(NxU32 i=0;i<4;i++)
    //{
    //motorsDesc[i].setToCorvette();
    //vehicleDesc.motorsDesc.push_back(&motorsDesc[i]);
    //}

    //Roda (Wheel) descricao
    int numberWheels = Simulation::getNumberWheels(indexScene, indexRobot);
    NxWheelDesc* wheelDesc = new NxWheelDesc[numberWheels];
    for(NxU32 i=0; i<numberWheels; i++)
    {
        //NxActor* wheelModel = Simulation::getActorWheel(indexScene,indexRobot,i);
        //NxActorDesc wheelActorDesc;
        //wheelModel->saveToDesc(wheelActorDesc);
        //Simulation::gScenes[0]->releaseActor(*wheelModel);
        NxActor* actorWheel = Simulation::getActorWheel(indexScene,indexRobot,i);//wheelModel;//Simulation::gScenes[0]->createActor(wheelActorDesc);
        //NxShape*const* wheelShapes = actorWheel->getShapes();
        //NxBounds3 wheelBounds;
        //wheelShapes[0]->getWorldBounds(wheelBounds);

        //Para exportar modelo da roda do 3ds Max
        //	NxWhee
        //wheelDesc[i]
        //robot1Shapes[0]->isConvexMesh()->getConvexMesh().saveToDesc(convexMesh);
        //NxWheelShape* wheelShape = (NxWheelShape*)wheel;
        //NxTriangleMeshDesc meshDesc = *((NxTriangleMeshDesc*)(mesh->userData));
        //robot1Shapes[0]->isWheel()->

        //wheelDesc[i].wheelApproximation = 10;

        wheelDesc[i].wheelOrientation = actorWheel->getGlobalOrientation();
        wheelDesc[i].position.set(actorWheel->getGlobalPosition()-robotActor->getGlobalPosition());
        //wheelDesc[i].position.z = 0;
        wheelDesc[i].id = i;
        wheelDesc[i].wheelRadius = 27.6;
        //wheelDesc[i].wheelWidth = 100;
        wheelDesc[i].wheelSuspension = 0;
        wheelDesc[i].springRestitution = 0;
        wheelDesc[i].springDamping = 0;
        wheelDesc[i].springBias = 0.0f;
        wheelDesc[i].maxBrakeForce = 100;
        wheelDesc[i].frictionToFront = 0.1f;//0.1f;	//TODO: CONFIGURAR PARÂMETRO
        wheelDesc[i].frictionToSide = 0;//0.02f;	//TODO: CONFIGURAR PARÂMETRO
        wheelDesc[i].inverseWheelMass = 0.1;		//TODO: CONFIGURAR PARÂMETRO

        //Angulo das Rodas (Omni)
        NxVec3 wheelPosRel = actorWheel->getGlobalPosition() - robotActor->getGlobalPosition();
        wheelDesc[i].angWheelRelRobot = NxMath::atan2( wheelPosRel.y, wheelPosRel.x );

        vehicleDesc.robotWheels.pushBack(&wheelDesc[i]);
        Simulation::gScenes[indexScene]->scene->releaseActor(*actorWheel);

        //NxU32 flags = NX_WF_BUILD_LOWER_HALF;
        wheelDesc[i].wheelFlags = NX_WF_ACCELERATED | NX_WF_AFFECTED_BY_HANDBRAKE | NX_WF_USE_WHEELSHAPE | NX_WF_BUILD_LOWER_HALF;// |/*NX_WF_STEERABLE_INPUT |*/ flags;
    }

    //NxBall* teste = Simulation::gScenes[indexScene]->ball;

    //Criar robot, vehicle base
    NxRobot* robot = (NxRobot*)NxRobot::createVehicle(Simulation::gScenes[indexScene], &vehicleDesc);
    if(robot) {
        robot->setId(indexRobot);
        robot->setIdTeam(indexTeam);
        robot->indexScene = indexScene;

        //Dribbler and Kicker
        for(int i=0; i<robotActor->getNbShapes(); i++) {
            NxShape*const* robotShapes = robotActor->getShapes();
            const char* shapeName = robotShapes[i]->getName();
            if(shapeName) {
                char* dribblerName = new char[10];//"Driblador\0"
                dribblerName[9] = 0;
                memcpy(dribblerName, shapeName, strlen(dribblerName));

                char* kickerName = new char[9];//"Chutador\0"
                kickerName[8] = 0;
                memcpy(kickerName, shapeName, strlen(kickerName));

                if(strcmp(dribblerName, "Driblador") == 0) {
                    robot->dribbler->dribblerShapes.push_back(robotShapes[i]);
                }
                else if(strcmp(kickerName, "Chutador") == 0) {
                    robot->kicker->kickerShapeDesc = Simulation::copyShapeDesc(robotShapes[i]);
                    robotActor->releaseShape(*(robotShapes[i]));
                }
                delete dribblerName;
                delete kickerName;
            }
        }

        //Initial Pose
        robot->setInitialPose(robotActor->getGlobalPose());

        robotActor->putToSleep();

        //Mudar pose do robo
        //NxQuat q;
        //q.
        //q.fromAngleAxis(180.0f, NxVec3(0.0f, 1.0f, 0.0f));
        //robot->getActor()->setGlobalPose(pose);

        //Release no actor importado do 3ds Max
        //gScenes[0]->releaseActor(*robotActor);

        string label;
        string plabel = "Robo";
        stringstream out;
        out << indexRobot;
        out << "-";
        out << indexTeam;
        //out << "-";
        //out << indexScene;
        label.append(plabel);
        label.append(out.str());
        char* arrayLabel = new char[label.size()+1];
        arrayLabel[label.size()]=0;
        memcpy(arrayLabel, label.c_str(), label.size());
        robotActor->setName(arrayLabel);
        //delete arrayLabel;
    }
}