Ejemplo n.º 1
0
bool Hud::OnEvent(const SEvent& event)
{
	if (!_showMinimap)
		return false;

	ISceneManager* scene;
	IVideoDriver* video;

	switch (Game::ToGameEvent(event)) {
	
	case EGE_ADDITIONAL_RENDER_STARTING:
		scene = _game->getDevice()->getSceneManager();
		video = _game->getDevice()->getVideoDriver();

		_previousCamera = scene->getActiveCamera();
		scene->setActiveCamera(_minimapCamera);
		video->setRenderTarget(_minimapTexture);

		show(false);
		break;

	case EGE_ADDITIONAL_RENDER_FINISHED:
		scene = _game->getDevice()->getSceneManager();
		video = _game->getDevice()->getVideoDriver();

		scene->setActiveCamera(_previousCamera);
		video->setRenderTarget(NULL);

		show(true);
		break;

	}

	return false;
}
Ejemplo n.º 2
0
	/// Add self into scene manager's render queue
	void CameraComponent::setActive(bool active)
	{
		if (this->active == active) return;

		this->active = active;

		ISceneManager* smgr = getNode()->getSceneManager();
		smgr->setActiveCamera(getNode());
	}
Ejemplo n.º 3
0
CGameCamera::CGameCamera()
{
	m_targetObject = NULL;
	m_objectType = CGameObject::CameraObject;

#ifdef GSEDITOR
	m_cameraMesh = NULL;
#endif

	ISceneManager *smgr = getIView()->getSceneMgr();

	// save old camera
	ICameraSceneNode *oldCam = smgr->getActiveCamera();

	// create new camera
	m_camera = smgr->addCameraSceneNode();		
	m_camera->setFOV( core::degToRad(60.0f) );
	m_camera->setFarValue( 8000.0f );
	m_camera->grab();	
	
	core::vector3df	pos(0,0,0);
	setPosition( pos );

	core::vector3df target(1,0,0);
	setTarget( target );

#ifdef GSEDITOR	
	CColladaMeshComponent *comp = new CColladaMeshComponent( this );
	comp->loadFromFile( getIView()->getPath("data/editor/camera.dae") );
	addComponent( comp );
	setLighting( false );

	m_cameraMesh = m_node;	
	m_cameraMesh->setVisible( true );	

	ITriangleSelector *selector = smgr->createTriangleSelectorFromBoundingBox( m_cameraMesh );
	m_cameraMesh->setTriangleSelector(selector);
	selector->drop();
#endif

	// set camera node
	m_node = m_camera;

	// restore camera
	smgr->setActiveCamera( oldCam );
		
	m_animator = NULL;

#ifndef GSGAMEPLAY
	setEditorCamera();
#else
	setFreeCamera();
#endif
}
Ejemplo n.º 4
0
STATE StateTemp::Update()
{
	SmartPointer<PacketAddr> pAddr;

 	m_pNetworkControl->ReceivePacket();
	ISceneManager * smgr = Irrdevice::GetInstance()->GetSceneManager();
 	if((pAddr= m_pNetworkControl->GetPacket()) != NULL)
 	{
 		ServerPacketParsing(pAddr.getPoint());
 	}

	if(IsKeyDown(irr::KEY_KEY_T))
	{
		smgr->setActiveCamera(m_pCamera);
	}
	if(IsKeyDown(irr::KEY_KEY_H))
	{
		m_pMe->SetActiveCamera();
	}
	if(IsKeyDown(irr::KEY_KEY_N))
	{
		m_pYou->SetActiveCamera();
	}
	


// 	if(IsKeyDown(irr::KEY_KEY_T))
// 	{
// 		Packet p(BASE_ACK,m_MyId);	
// 		p<<1;
// 		m_pNetworkControl->SendClientToPacket(p);
// 	}
// 	if(IsKeyDown(irr::KEY_KEY_F))
// 	{
// 		Packet p(BASE_ACK,m_MyId);	
// 		p<<2;
// 		m_pNetworkControl->SendClientToPacket(p);
// 	}
// 	if(IsKeyDown(irr::KEY_KEY_G))
// 	{
// 		Packet p(BASE_ACK,m_MyId);	
// 		p<<3;
// 		m_pNetworkControl->SendClientToPacket(p);
// 	}
// 	if(IsKeyDown(irr::KEY_KEY_H))
// 	{
// 		Packet p(BASE_ACK,m_MyId);	
// 		p<<4;
// 		m_pNetworkControl->SendClientToPacket(p);
// 	}

	return STATE_NONE;
}
Ejemplo n.º 5
0
CGameCamera::~CGameCamera()
{
#ifdef GSEDITOR
	m_cameraMesh->drop();
#endif
	
    if ( getIView()->getActiveCamera() == this )
        getIView()->setActiveCamera(NULL);
    
	ISceneManager *smgr = getIView()->getSceneMgr();

	// set null camera on scenenode
	if ( smgr->getActiveCamera() == m_node )
		smgr->setActiveCamera( NULL );
}
Ejemplo n.º 6
0
/*
Ok, now the main-function:
First, we initialize the device, get the SourceManager and
VideoDriver, load an animated mesh from .md2 and a map from
.pk3. Because that's old stuff, I won't explain every step.
Just take care of the maps position.
*/
int main()
{
	// ask user for driver
	video::E_DRIVER_TYPE driverType=driverChoiceConsole();
	if (driverType==video::EDT_COUNT)
		return 1;

	//Instance of the EventReceiver
	MyEventReceiver receiver;

	//Initialise the engine
	IrrlichtDevice *device = createDevice(driverType,
			dimension2du(ResX,ResY), 32, fullScreen,
			false, false, &receiver);
	if (!device)
		return 1;

	ISceneManager *smgr = device->getSceneManager();
	IVideoDriver *driver = device->getVideoDriver();

	//Load model
	IAnimatedMesh *model = smgr->getMesh("../../media/sydney.md2");
	if (!model)
		return 1;
	IAnimatedMeshSceneNode *model_node = smgr->addAnimatedMeshSceneNode(model);
	//Load texture
	if (model_node)
	{
		ITexture *texture = driver->getTexture("../../media/sydney.bmp");
		model_node->setMaterialTexture(0,texture);
		model_node->setMD2Animation(scene::EMAT_RUN);
		//Disable lighting (we've got no light)
		model_node->setMaterialFlag(EMF_LIGHTING,false);
	}

	//Load map
	device->getFileSystem()->addFileArchive("../../media/map-20kdm2.pk3");
	IAnimatedMesh *map = smgr->getMesh("20kdm2.bsp");
	if (map)
	{
		ISceneNode *map_node = smgr->addOctreeSceneNode(map->getMesh(0));
		//Set position
		map_node->setPosition(vector3df(-850,-220,-850));
	}

/*
Now we create our four cameras. One is looking at the model
from the front, one from the top and one from the side. In
addition there's a FPS-camera which can be controlled by the
user.
*/
	// Create 3 fixed and one user-controlled cameras
	//Front
	camera[0] = smgr->addCameraSceneNode(0, vector3df(50,0,0), vector3df(0,0,0));
	//Top
	camera[1] = smgr->addCameraSceneNode(0, vector3df(0,50,0), vector3df(0,0,0));
	//Left
	camera[2] = smgr->addCameraSceneNode(0, vector3df(0,0,50), vector3df(0,0,0));
	//User-controlled
	camera[3] = smgr->addCameraSceneNodeFPS();
	// don't start at sydney's position
	if (camera[3])
		camera[3]->setPosition(core::vector3df(-50,0,-50));

/*
Create a variable for counting the fps and hide the mouse:
*/
	//Hide mouse
	device->getCursorControl()->setVisible(false);
	//We want to count the fps
	int lastFPS = -1;

/*
There wasn't much new stuff - till now!
Only by defining four cameras, the game won't be splitscreen.
To do this you need several steps:
  - Set the viewport to the whole screen
  - Begin a new scene (Clear screen)

  - The following 3 steps are repeated for every viewport in the splitscreen
    - Set the viewport to the area you wish
    - Activate the camera which should be "linked" with the viewport
    - Render all objects

  - If you have a GUI:
    - Set the viewport the whole screen
    - Display the GUI
  - End scene

Sounds a little complicated, but you'll see it isn't:
*/

	while(device->run())
	{
		//Set the viewpoint to the whole screen and begin scene
		driver->setViewPort(rect<s32>(0,0,ResX,ResY));
		driver->beginScene(true,true,SColor(255,100,100,100));
		//If SplitScreen is used
		if (SplitScreen)
		{
			//Activate camera1
			smgr->setActiveCamera(camera[0]);
			//Set viewpoint to the first quarter (left top)
			driver->setViewPort(rect<s32>(0,0,ResX/2,ResY/2));
			//Draw scene
			smgr->drawAll();
			//Activate camera2
			smgr->setActiveCamera(camera[1]);
			//Set viewpoint to the second quarter (right top)
			driver->setViewPort(rect<s32>(ResX/2,0,ResX,ResY/2));
			//Draw scene
			smgr->drawAll();
			//Activate camera3
			smgr->setActiveCamera(camera[2]);
			//Set viewpoint to the third quarter (left bottom)
			driver->setViewPort(rect<s32>(0,ResY/2,ResX/2,ResY));
			//Draw scene
			smgr->drawAll();
			//Set viewport the last quarter (right bottom)
			driver->setViewPort(rect<s32>(ResX/2,ResY/2,ResX,ResY));
		}
		//Activate camera4
		smgr->setActiveCamera(camera[3]);
		//Draw scene
		smgr->drawAll();
		driver->endScene();

		/*
		As you can probably see, the image is rendered for every
		viewport seperately. That means, that you'll loose much performance.
		Ok, if you're aksing "How do I have to set the viewport
		to get this or that screen?", don't panic. It's really
		easy: In the rect-function you define 4 coordinates:
		- X-coordinate of the corner left top
		- Y-coordinate of the corner left top
		- X-coordinate of the corner right bottom
		- Y-coordinate of the corner right bottom

		That means, if you want to split the screen into 2 viewports
		you would give the following coordinates:
		- 1st viewport: 0,0,ResX/2,ResY
		- 2nd viewport: ResX/2,0,ResX,ResY

		If you didn't fully understand, just play arround with the example
		to check out what happens.

		Now we just view the current fps and shut down the engine,
		when the user wants to:
		*/
		//Get and show fps
		if (driver->getFPS() != lastFPS)
		{
			lastFPS = driver->getFPS();
			core::stringw tmp = L"Irrlicht SplitScreen-Example (FPS: ";
			tmp += lastFPS;
			tmp += ")";
			device->setWindowCaption(tmp.c_str());
		}
	}
	//Delete device
	device->drop();
	return 0;
}
Ejemplo n.º 7
0
bool Editor::run(IrrlichtDevice* irr_device,Configuration* conf){
	// Do Irrlicht Stuff
	_device = irr_device;
	IVideoDriver* driver = GetDevice()->getVideoDriver();
	ISceneManager* smgr = GetDevice()->getSceneManager();
	IGUIEnvironment* guienv = GetDevice()->getGUIEnvironment();	
	GetDevice()->setEventReceiver(this);

	if (!conf->getSettingAsBool("fullscreen"))
		GetDevice()->setResizable(true);

	// Project and state
	Project* proj = new Project();
	_state = new EditorState(GetDevice(),proj,conf);

	// Menu State
	MenuState* ms = new MenuState(GetState());
	GetState()->SetMenu(ms);

	// Add editor modes
	GetState()->AddMode(new NBEditor(GetState()));

	// Set up project
	proj->AddNode(new Node(GetDevice(),GetState()));
	proj->SelectNode(0);

	// Load user interface
	LoadScene();	
	GetState()->Menu()->init();
	GetState()->Mode()->load();
	printf("Complete!\n");

	int LastX = driver->getScreenSize().Width;
	if (!GetState()->Settings()->getSettingAsBool("hide_sidebar"))
			LastX -= 256;
	int LastY = driver->getScreenSize().Height;
	int lastFPS = -1;
	while (GetDevice()->run()){
		if (GetState()->NeedsClose()){
			GetDevice()->closeDevice();
			return true;
		}

		driver->beginScene(true, true, irr::video::SColor(255,150,150,150));

		int ResX = driver->getScreenSize().Width;
		if (!GetState()->Settings()->getSettingAsBool("hide_sidebar"))
			ResX -= 256;
		
		int ResY = driver->getScreenSize().Height;

		if (currentWindow == -1)
		{
			// Draw Camera 0
			if (camera[0]){
				smgr->setActiveCamera(camera[0]);
				rect<s32> offset = rect<s32>(0,0,ResX/2,ResY/2);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (GetState()->Mode())
					GetState()->Mode()->viewportTick(EVIEW_PERS, driver, offset);
			}

			// Draw Camera 1
			if (camera[1]){
				smgr->setActiveCamera(camera[1]);
				rect<s32> offset = rect<s32>(ResX/2,0,ResX,ResY/2);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (GetState()->Mode())
					GetState()->Mode()->viewportTick(EVIEW_XZ, driver, offset);
			}

			// Draw Camera 2
			if (camera[2]){
				smgr->setActiveCamera(camera[2]);
				rect<s32> offset = rect<s32>(0,ResY/2,ResX/2,ResY);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (GetState()->Mode())
					GetState()->Mode()->viewportTick(EVIEW_XY, driver, offset);

			}

			// Draw Camera 3
			if (camera[3]){
				smgr->setActiveCamera(camera[3]);
				rect<s32> offset = rect<s32>(ResX/2,ResY/2,ResX,ResY);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (GetState()->Mode())
					GetState()->Mode()->viewportTick(EVIEW_ZY, driver, offset);
			}

			// Draw GUI
			driver->setViewPort(rect<s32>(0,0,driver->getScreenSize().Width,driver->getScreenSize().Height));
			driver->draw2DLine(vector2d<irr::s32>(0,ResY/2),vector2d<irr::s32>(ResX,ResY/2),SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(0,ResY/2-1),vector2d<irr::s32>(ResX,ResY/2-1),SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(ResX/2,0),vector2d<irr::s32>(ResX/2,ResY),SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(ResX/2+1,0),vector2d<irr::s32>(ResX/2+1,ResY),SColor(175,255,255,255));
		}else if (camera[currentWindow]){
			smgr->setActiveCamera(camera[currentWindow]);
			driver->setViewPort(rect<s32>(0,0,ResX,ResY));
			smgr->drawAll();

			if (GetState()->Mode())
					GetState()->Mode()->viewportTick((VIEWPORT)currentWindow, driver, rect<s32>(0,0,ResX,ResY));

			driver->setViewPort(rect<s32>(0,0,driver->getScreenSize().Width,driver->getScreenSize().Height));
		}

		if (GetState()->Menu())
			GetState()->Menu()->draw(driver);
		if (GetState()->Mode())
			GetState()->Mode()->draw(driver);

		guienv->drawAll();
		driver->endScene();

		int fps = driver->getFPS();
        if (lastFPS != fps)
        {
            irr::core::stringw str = L"Nodebox Editor [FPS: ";
            str += fps;
			str += "]";

            GetDevice()->setWindowCaption(str.c_str());
            lastFPS = fps;
        }

		if (LastX != ResX || LastY != ResY){
			printf("Adjusting FOV to new screen size...\n");
			LastX = ResX;
			LastY = ResY;
			camera[0]->setAspectRatio((float)ResX/(float)ResY);

			// reset matrix
			matrix4 projMat;
			irr::f32 orth_w = (float)ResX / (float)ResY;
			orth_w = 3 * orth_w;
			projMat.buildProjectionMatrixOrthoLH(orth_w,3,1,100);

			for (int i=1;i<4;i++){
				if (camera[i]){
					camera[i]->remove();
					camera[i]=NULL;
				}
			}

			// Remake cameras
			camera[1]=smgr->addCameraSceneNode(target,vector3df(0,2,-0.01),vector3df(0,0,0));
			camera[1]->setProjectionMatrix(projMat,true);
			camera[2]=smgr->addCameraSceneNode(target,vector3df(0,0,-5),vector3df(0,0,0));
			camera[2]->setProjectionMatrix(projMat,true);
			camera[3]=smgr->addCameraSceneNode(target,vector3df(-5,0,0),vector3df(0,0,0));
			camera[3]->setProjectionMatrix(projMat,true);
		}
	}

	return true;
}
Ejemplo n.º 8
0
int main()
{
    const int nRobots = 2;
    //given robot numbers will be controlled by humans
    vector<int> humanBrainIds; 
    //humanBrainIds.push_back(1);
    //humanBrainIds.push_back(0);

//-- device ------------------------------------------------------------//

    IrrlichtDevice* device;

    device = createDevice(
        EDT_OPENGL, //driverType
        windowSize,
        16,  //bits
        false,
        false, //stencilbuffer
        false, //vsync
        NULL //receiver
    );
    //advanced device params
        //SIrrlichtCreationParameters params;
        //params.DeviceType = EIDT_CONSOLE;
        //params.DriverType = EDT_OPENGL;
        //params.WindowSize = windowSize;
        //device = createDeviceEx(params);

    if (device == 0)
        return EXIT_FAILURE; // could not create selected driver.

    IVideoDriver* driver = device->getVideoDriver();
    ISceneManager* smgr = device->getSceneManager();

//-- lights ------------------------------------------------------------//

    //ambient light
    //smgr->setAmbientLight( SColorf(1.0f,1.0f,1.0f,1.0f) );
        //smgr->setAmbientLight( SColorf(.3f,.3f,.3f,1.0f) );

    //diffusive light
        SLight light_data;
        light_data.AmbientColor = SColorf(.3,.3,.3);
        //light_data.Attenuation = vector3df(.3,.3,.3); //Attenuation cte, linear quadratic TODO ??
        light_data.DiffuseColor = SColorf(.0,.0,.0);
        light_data.SpecularColor = SColorf(.0,.0,.0);
        light_data.CastShadows = true;
        light_data.Radius = 100.0f;
        light_data.Type = ELT_DIRECTIONAL;
            //ELT_POINT 	point light, it has a position in space and radiates light in all directions
            //ELT_SPOT    spot light, it has a position in space, a direction, and a limited cone of influence
            //ELT_DIRECTIONAL 	directional light, coming from a direction from an infinite distance 
            
        ILightSceneNode* light = smgr->addLightSceneNode(0, core::vector3df(.5f,.0f,.5f));
        light->setLightData(light_data);

//-- objects ------------------------------------------------------------//

    IMesh* mesh;
    ISceneNode * node;
    float HEIGHT=1000.f, WIDTH=1.f;
    //height between center/sky == height bottom/center
    //large so that scene looks 2d on interactive test mode.
    //on automatic mode, only middle pixel row is taken, so this does not matter

    //outter boundary
        
        //square
            node = smgr->addCubeSceneNode(
                2.f*WIDTH,  // width
                0,      // parent
                -1,     // id
                vector3df(0, 0, 0),               // center
                vector3df(0, 0, 0),               // rotation
                vector3df(1.0f, HEIGHT, 1.0f)*-1.f    // scale. *-1 turns it inside out. to use both faces make two cubes.
            );

        //circle
            //mesh = smgr->getGeometryCreator()->createCylinderMesh(
                //1.f,    //radius
                //1.,     //length
                //50,     //tesselation
                //SColor(0,0,0,255),     //color
                //false,                 //closeTop
                //0.f                    //oblique
            //);
            //node = smgr->addMeshSceneNode(
                //mesh,
                //0,     //ISceneNode * parent
                //-1,    //s32 id
                //vector3df(0, -HEIGHT, 0),            //const core::vector3df & position
                //vector3df(0, 0, 0),                     //const core::vector3df & rotation
                //vector3df(1.0f, 2.f*HEIGHT, 1.0f)      //const core::vector3df & scale
            //);

        node->getMaterial(0).AmbientColor.set(0,0,0,0);
        node->getMaterial(0).DiffuseColor.set(0,0,0,0);
        //node->getMaterial(0).SpecularColor.set(255,255,255,255);
        //node->getMaterial(0).Shininess = 20.0f;
        //node->getMaterial(0).EmissiveColor.set(0,0,0,0);
        //node->setMaterialFlag(EMF_WIREFRAME,true); //wireframe only

    //left cube
        node = smgr->addCubeSceneNode(
            0.2,    // width
            0,      // parent
            -1,     // id
            vector3df(-.3, 0, 0),       // center
            vector3df(0, 0, 0),           // rotation
            vector3df(1.0f, HEIGHT, 1.0f)   // scale
        );
        node->getMaterial(0).AmbientColor.set(0,255,0,0);
        node->getMaterial(0).DiffuseColor.set(0,255,0,0);

    //right cube
        node = smgr->addCubeSceneNode(
            .2f,    // width
            0,      // parent
            -1,     // id
            vector3df(.3, 0, 0),        // center
            vector3df(0, 0, 0),           // rotation
            vector3df(1.0f, HEIGHT, 1.0f)   // scale
        );
        node->getMaterial(0).AmbientColor.set(0,0,255,0);
        node->getMaterial(0).DiffuseColor.set(0,0,255,0);

    //cylinder
        //mesh = smgr->getGeometryCreator()->createCylinderMesh(
            //.1f,    //radius
            //1.,     //length
            //50,     //tesselation
            //SColor(),              //color
            //false,                 //closeTop
            //0.f                    //oblique
        //);
        //node = smgr->addMeshSceneNode(
            //mesh,
            //0,     //ISceneNode * parent
            //-1,    //s32 id
            //vector3df(0, -HEIGHT, 0),            //const core::vector3df & position
            //vector3df(0, 0, 0),                  //const core::vector3df & rotation
            //vector3df(1.0f, 2.*HEIGHT, 1.0f)     //const core::vector3df & scale
        //);
        //node->getMaterial(0).AmbientColor.set(0,0,0,255);
        //node->getMaterial(0).DiffuseColor.set(0,0,0,255);

    //sphere
        //node = smgr->addSphereSceneNode(
            //0.1,     // radius
            //50,     // poly count
            //0,      // parent
            //FruitID,     // id
            //vector3df(0, 0, 0),         // center
            //vector3df(0, 0, 0),           // rotation
            //vector3df(1.0f, 1.0f, 1.0f)   // scale
        //);
        //node->getMaterial(0).AmbientColor.set(0,0,0,255);
        //node->getMaterial(0).DiffuseColor.set(0,0,0,255);
        //node->getMaterial(0).Lighting = true;

//-- collision ------------------------------------------------------------//

    /* Put everything we want to do collision checking with inside the meta selector. */
    IMetaTriangleSelector * meta = smgr->createMetaTriangleSelector();
    array<ISceneNode *> nodes;
    smgr->getSceneNodesFromType(ESNT_ANY, nodes); // Find all nodes

    for (u32 i=0; i < nodes.size(); ++i)
    {
        ISceneNode * node = nodes[i];
        ITriangleSelector * selector = 0;

        switch(node->getType())
        {
            case ESNT_CUBE:
            case ESNT_ANIMATED_MESH:
            // Because the selector won't animate with the mesh,
            // and is only being used for camera collision, we'll just use an approximate
            // bounding box instead of ((IAnimatedMeshSceneNode*)node)->getMesh(0)
            selector = smgr->createTriangleSelectorFromBoundingBox(node);
            break;

            case ESNT_MESH:
            case ESNT_SPHERE: // Derived from IMeshSceneNode
            selector = smgr->createTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node);
            break;

            case ESNT_TERRAIN:
            selector = smgr->createTerrainTriangleSelector((ITerrainSceneNode*)node);
            break;

            case ESNT_OCTREE:
            selector = smgr->createOctreeTriangleSelector(((IMeshSceneNode*)node)->getMesh(), node);
            break;

            default:
            // Don't create a selector for this node type
            break;
        }

        if(selector)
        {
            // Add it to the meta selector, which will take a reference to it
            meta->addTriangleSelector(selector);
            // And drop my reference to it, so that the meta selector owns it.
            selector->drop();
        }
    }

//-- robots ------------------------------------------------------------//

    //create robots
    Fly2D::Brain* brains[nRobots];


    //all to a default type
    //for ( int i=0; i<nRobots; i++ )
    //{
        //brains[i] = new Fly2D::BrainForward;
        ////brains[i] = new Fly2D::BrainCircle();
    //}

    brains[0] = new Fly2D::BrainForward;
    brains[1] = new Fly2D::BrainForward;

    //decide human control
        vector<Fly2D::BrainHuman*> hBrains;
        for (
            vector<int>::iterator i = humanBrainIds.begin();
            i != humanBrainIds.end();
            ++i
        )
        {
            if ( *i > nRobots )
            {
                cerr << "no such robot: " << *i << endl;
                exit(EXIT_FAILURE);
            }
            delete brains[*i];
            Fly2D::BrainHuman* hBrain = new Fly2D::BrainHuman;
            brains[*i] = hBrain;
            hBrains.push_back(hBrain);
        }
        Fly2D::ReceiverHuman hReceiver = Fly2D::ReceiverHuman( hBrains );
        device->setEventReceiver( &hReceiver );

    Robot* robots[nRobots];
    robots[0] = new Fly2D::Robot( *device, *meta, *brains[0], vector3df(0,0,-0.5f), vector3df(0,0, 0.5f),  0.01 );
    robots[1] = new Fly2D::Robot( *device, *meta, *brains[1], vector3df(0,0,0.5f),  vector3df(0,0, -0.5f), 0.01 );

    meta->drop(); // As soon as we're done with the selector, drop it.

//-- run ------------------------------------------------------------//
    //TEST
    vector3df oldpos, oldtarget;
    //END TEST
    
    int nFrames = 0;
    ITimer* timer = device->getTimer();
    int t0 = timer->getTime();
    int w = driver->getScreenSize().Width;
    int h = driver->getScreenSize().Height;
    int dh = h/nRobots;
    int observeRobot = 0;

	while(device->run())
	{
        //if (device->isWindowActive()) //only work if window has focus.

        //draw

        driver->setViewPort(rect<s32>(0,0,w,h));
        driver->beginScene(true,true,0);
        for(int i=0; i<nRobots; i++)
        {
            driver->setViewPort(rect<s32>(0,dh*i,w,dh*(i+1)));
            //only part of window gets drawn into

            smgr->setActiveCamera(robots[i]->camera);

            smgr->drawAll(); 
            //draws on window scene of active camera
 
            robots[i]->update();
        }
        driver->endScene();

        //TEST
        //if
        //(
            //robots[observeRobot].getPosition() != oldpos
            //|| robots[observeRobot].getTarget() != oldtarget
        //)
        //oldpos = robots[observeRobot].getPosition();
        //oldtarget = robots[observeRobot].getTarget();

        cout << robots[observeRobot]->str();

        //FPS info
            //cout << "frame no:" << endl << nFrames << endl;;
            //cout << "average fps:" << endl << 1000*nFrames/(float)(timer->getTime()-t0) << endl;
            //nFrames++;
            cout << "fps:" << endl << driver->getFPS() << endl;
        //END TEST
	}
	device->drop();
	return 0;
}
Ejemplo n.º 9
0
void Editor::viewportTick(Viewport viewport, rect<s32> rect,
		bool mousehit, bool middlehit)
{
	// Init
	IVideoDriver *driver = device->getVideoDriver();
	ISceneManager *smgr = device->getSceneManager();
	IGUIEnvironment *guienv = device->getGUIEnvironment();
	ViewportType type = state->getViewportType(viewport);

	// Draw camera
	smgr->setActiveCamera(camera[(int)viewport]);
	driver->setViewPort(rect);
	if (type == VIEWT_BOTTOM)
		plane->setVisible(false);
	smgr->drawAll();
	if (type == VIEWT_BOTTOM)
		plane->setVisible(true);

	// Callbacks
	if (state->Mode())
		state->Mode()->viewportTick(viewport, driver, rect);

	if (viewport_drag == viewport) {
		vector2di delta = state->mouse_position;
		delta -= viewport_drag_last;
		viewport_drag_last = state->mouse_position;
		viewport_offset[(int)viewport].X -= (f32)delta.X * 0.01f;
		viewport_offset[(int)viewport].Y += (f32)delta.Y * 0.01f;
		if (viewport_offset[(int)viewport].X > 0.5)
			viewport_offset[(int)viewport].X = 0.5;
		if (viewport_offset[(int)viewport].X < -0.5)
			viewport_offset[(int)viewport].X = -0.5;
		if (viewport_offset[(int)viewport].Y > 0.5)
			viewport_offset[(int)viewport].Y = 0.5;
		if (viewport_offset[(int)viewport].Y < -0.5)
			viewport_offset[(int)viewport].Y = -0.5;
		applyCameraOffsets(viewport);
	}

	if (middlehit && rect.isPointInside(state->mouse_position)
			&& type != VIEWT_PERS) {
		viewport_drag = viewport;
		viewport_drag_last = state->mouse_position;
	}

	// Draw text
	driver->setViewPort(rects32(0, 0, driver->getScreenSize().Width,
			driver->getScreenSize().Height));
	{
		static const wchar_t* labels[7] = {L"Perspective", L"Front", L"Left",
				L"Top", L"Back", L"Right", L"Bottom"};

		// Handle clicking
		position2d<s32> labelpos(rect.LowerRightCorner.X - 86,
				rect.UpperLeftCorner.Y + ((rect.UpperLeftCorner.Y < 50)?30:10));
		rects32 backgroundrect(rect.LowerRightCorner.X - 96,
					rect.UpperLeftCorner.Y + ((rect.UpperLeftCorner.Y < 50)?25:5),
					rect.LowerRightCorner.X - 5,
					rect.UpperLeftCorner.Y + ((rect.UpperLeftCorner.Y < 50)?185:165));
		bool context_is_open = (viewport_contextmenu == viewport);
		if (mousehit && !state->menu->dialog) {
			if ((rects32(labelpos.X, labelpos.Y, labelpos.X + 90,
					labelpos.Y + 25)).isPointInside(state->mouse_position)) {
				viewport_contextmenu = viewport;
			} else if (context_is_open) {
				context_is_open = false;
				viewport_contextmenu = VIEW_NONE;
				if (backgroundrect.isPointInside(state->mouse_position)) {
					int y = 0;
					for (int i = 0; i < 7; i++) {
						if (i != (int)type) {
							int ty = rect.UpperLeftCorner.Y +
									((rect.UpperLeftCorner.Y < 50)?56:36)
									+ y * 20;
							rects32 trect(rect.LowerRightCorner.X - 96,
									ty,
									rect.LowerRightCorner.X - 5, ty + 20);
							y++;
							if (trect.isPointInside(state->mouse_position)) {
								viewport_offset[(int)viewport] = vector3df(0, 0, 0);
								state->settings->set(viewportToSetting(viewport),
									viewportTypeToSetting((ViewportType)i));
								recreateCameras();
								break;
							}
						}
					}
				}
			}
		}

		// Context menu
		if (context_is_open) {
			// Context menu background
			driver->draw2DRectangle(SColor(100, 32, 32, 32), backgroundrect);
			s32 y2 = rect.UpperLeftCorner.Y + ((rect.UpperLeftCorner.Y < 50)?52:32);
			driver->draw2DLine(position2d<s32>(rect.LowerRightCorner.X - 96, y2),
					position2d<s32>(rect.LowerRightCorner.X - 5, y2),
					SColor(100, 255, 255, 255));
			// Draw options
			guienv->getSkin()->getFont()->draw(labels[(int)type],
					core::rect<s32>(labelpos.X, labelpos.Y, 200, 50),
					video::SColor(255, 255, 255, 255));
			int y = 0;
			for (int i = 0; i < 7; i++) {
				if (i != (int)type) {
					guienv->getSkin()->getFont()->draw(
						labels[i],
						core::rect<s32>(rect.LowerRightCorner.X - 86,
							rect.UpperLeftCorner.Y + ((rect.UpperLeftCorner.Y < 50)?59:39) + y * 20,
							200, 50),
						video::SColor(255, 255, 255, 255)
					);
					y++;
				}
			}
		} else {
			// Draw label
			guienv->getSkin()->getFont()->draw(labels[(int)type],
					core::rect<s32>(rect.LowerRightCorner.X - wcslen(labels[(int)type]) * 6
					- 20, labelpos.Y, 200, 50),
					video::SColor(255, 255, 255, 255));
		}
	}

	// Draw coordinate arrows
	if (type != VIEWT_PERS) {
		switch(type) {
		case VIEWT_TOP:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"X", L"Z");
			break;
		case VIEWT_BOTTOM:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"X", L"-Z");
			break;
		case VIEWT_LEFT:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"-Z", L"Y");
			break;
		case VIEWT_RIGHT:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"Z", L"Y");
			break;
		case VIEWT_FRONT:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"X", L"Y");
			break;
		case VIEWT_BACK:
			drawCoord(guienv->getSkin()->getFont(), driver, rect.UpperLeftCorner.X + 10,
					rect.LowerRightCorner.Y - 42, L"-X", L"Y");
			break;
		}
	}
}
Ejemplo n.º 10
0
int main(int argc, char** argv) {
	CustomEventReceiver receiver;
	IrrlichtDevice *device = createDevice( video::EDT_OPENGL, dimension2d<u32>(800, 600), 16, false, false, false, &receiver);
	if (!device) {
		return EXIT_FAILURE;
    }
	device->setWindowCaption(L"Solar System Simulator");
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* sceneManager = device->getSceneManager();
	scene::ISceneCollisionManager* collisionManager= sceneManager->getSceneCollisionManager();
	IGUIEnvironment* guiEnv = device->getGUIEnvironment();
	guiEnv->addStaticText(L"Click on a planet to attach the camera to it", rect<s32>(10,10,260,22), false);

	sf::SoundBuffer buffer;
	if (buffer.loadFromFile(currentPath() + "/sounds/burning.aif")) {
		sf::Listener::setPosition(0, 0,0);

		sf::Sound sound;
		sound.setBuffer(buffer);
		sound.setPosition(0, 0, 0);
		sound.setLoop(true);
		sound.play();
	}

	const char* spaceTexturePath = ( currentPath() + "/textures/space.jpg" ).c_str();
	video::ITexture* space = driver->getTexture(spaceTexturePath);
	scene::ISceneNode* skybox = sceneManager->addSkyBoxSceneNode(space, space, space, space, space, space);

	sceneManager->addLightSceneNode(0, vector3df(0, 0, -50),  video::SColorf(1.0f, 1.0f, 1.0f), 50.0f, 1001);

	PlanetFactory planetFactory(sceneManager, driver);
	Planet sun = planetFactory.create(PlanetId::Sun);
	Planet earth = planetFactory.create(PlanetId::Earth);
	Planet pluto = planetFactory.create(PlanetId::Pluto);
	Planet jupiter = planetFactory.create(PlanetId::Jupiter);
	Planet uranus = planetFactory.create(PlanetId::Uranus);
	Planet neptune = planetFactory.create(PlanetId::Neptune);

	vector<Planet> planets = { sun, planetFactory.create(PlanetId::Mercury) };
	planets.push_back(planetFactory.create(PlanetId::Venus));
	planets.push_back(earth);
	planets.push_back(planetFactory.create(PlanetId::Mars));
	planets.push_back(jupiter);
	planets.push_back(planetFactory.create(PlanetId::Saturn));
	planets.push_back(uranus);
	planets.push_back(neptune);
	planets.push_back(pluto);

	ICameraSceneNode* camera = sceneManager->addCameraSceneNode(0, vector3df(0,0,40), vector3df(0,0,0));
	rect<s32> mainCameraViewPortRect(0, 0, 800, 600);

	ICameraSceneNode* topViewCamera = sceneManager->addCameraSceneNode(0, vector3df(0,50,0), vector3df(0,0,0));
	
	sceneManager->setAmbientLight(video::SColorf(255.0,255.0,255.0));

	ISceneNode* selectedNode = sun.node;
	while(device->run()) {

		if(receiver.GetMouseState().LeftButtonDown) {
			position2di mousepos = receiver.GetMouseState().Position;
			line3df ray = sceneManager->getSceneCollisionManager()->getRayFromScreenCoordinates( mousepos, camera);

			vector3df intersection;
			triangle3df tri;

            for(Planet& planet : planets) {
				ITriangleSelector* wselector = sceneManager->createTriangleSelectorFromBoundingBox(planet.node);
				if (collisionManager->getCollisionPoint(ray, wselector, intersection, tri, planet.node)) {
					selectedNode = planet.node;
				}
				wselector->drop();
			}
		}

		camera->setTarget(selectedNode->getAbsolutePosition());

		skybox->setVisible(true);		
        
		driver->setViewPort(mainCameraViewPortRect);
		driver->beginScene(true, true, SColor(255,100,101,140));
		sceneManager->setActiveCamera(camera);
		sceneManager->drawAll();
		guiEnv->drawAll();

		driver->setViewPort(rect<s32>(0, 380, 200, 600));
		driver->draw2DRectangle(SColor(100,0,0,190), mainCameraViewPortRect);
		skybox->setVisible(false);		
		sceneManager->setActiveCamera(topViewCamera);
		sceneManager->drawAll();
		
		driver->endScene();
	}
	device->drop();

	return EXIT_SUCCESS;
}
Ejemplo n.º 11
0
bool Editor::run(IrrlichtDevice* irr_device,Configuration* conf)
{
	// Do Irrlicht Stuff
	device = irr_device;
	IVideoDriver *driver = device->getVideoDriver();
	ISceneManager *smgr = device->getSceneManager();
	IGUIEnvironment *guienv = device->getGUIEnvironment();	
	device->setEventReceiver(this);
	device->setWindowCaption(L"Node Box Editor");

	if (!conf->getBool("fullscreen")) {
		device->setResizable(true);
	}

	// Project and state
	Project *proj = new Project();
	state = new EditorState(device, proj, conf);

	// Menu State
	state->menu = new MenuState(state);

	// Add editor modes
	state->AddMode(new NBEditor(state));
	state->AddMode(new NodeEditor(state));

	// Set up project
	proj->AddNode(state, true, false);

	// Load user interface
	LoadScene();	
	state->SelectMode(0);

	int LastX = driver->getScreenSize().Width;
	if (!state->settings->getBool("hide_sidebar")) {
			LastX -= 256;
	}
	int LastY = driver->getScreenSize().Height;
#ifdef _DEBUG
	int lastFPS = -1;
#endif

	bool dosleep = state->settings->getBool("use_sleep");
	u32 last = std::clock();
	double dtime = 0;
	while (device->run()) {
		if (state->NeedsClose()) {
			device->closeDevice();
			return true;
		}

		driver->beginScene(true, true, irr::video::SColor(255, 150, 150, 150));

		int ResX = driver->getScreenSize().Width;
		if (!state->settings->getBool("hide_sidebar"))
			ResX -= 256;
		
		int ResY = driver->getScreenSize().Height;

		if (currentWindow == -1) {
			// Draw Camera 0
			if (camera[0]) {
				smgr->setActiveCamera(camera[0]);
				rect<s32> offset = rect<s32>(0, 0, ResX/2, ResY/2);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (state->Mode())
					state->Mode()->viewportTick(VIEW_PERS, driver, offset);
			}

			// Draw Camera 1
			if (camera[1]) {
				smgr->setActiveCamera(camera[1]);
				rect<s32> offset = rect<s32>(ResX/2, 0, ResX, ResY/2);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (state->Mode())
					state->Mode()->viewportTick(VIEW_XZ, driver, offset);
			}

			// Draw Camera 2
			if (camera[2]) {
				smgr->setActiveCamera(camera[2]);
				rect<s32> offset = rect<s32>(0, ResY/2, ResX/2, ResY);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (state->Mode())
					state->Mode()->viewportTick(VIEW_XY, driver, offset);

			}

			// Draw Camera 3
			if (camera[3]) {
				smgr->setActiveCamera(camera[3]);
				rect<s32> offset = rect<s32>(ResX/2, ResY/2, ResX, ResY);
				driver->setViewPort(offset);
				smgr->drawAll();

				if (state->Mode())
					state->Mode()->viewportTick(VIEW_ZY, driver, offset);
			}

			// Draw GUI
			driver->setViewPort(rect<s32>(0, 0, driver->getScreenSize().Width, driver->getScreenSize().Height));
			driver->draw2DLine(vector2d<irr::s32>(0, ResY/2), vector2d<irr::s32>(ResX, ResY/2), SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(0, ResY/2-1), vector2d<irr::s32>(ResX, ResY/2-1), SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(ResX/2, 0), vector2d<irr::s32>(ResX/2, ResY), SColor(175,255,255,255));
			driver->draw2DLine(vector2d<irr::s32>(ResX/2+1, 0), vector2d<irr::s32>(ResX/2+1, ResY), SColor(175,255,255,255));
		} else if (camera[currentWindow]) {
			smgr->setActiveCamera(camera[currentWindow]);
			driver->setViewPort(rect<s32>(0, 0, ResX, ResY));
			smgr->drawAll();

			if (state->Mode()) {
				state->Mode()->viewportTick((Viewport) currentWindow,
						driver, rect<s32>(0, 0, ResX, ResY));
			}

			driver->setViewPort(rect<s32>(0, 0, driver->getScreenSize().Width, driver->getScreenSize().Height));
		}

		if (state->menu) {
			state->menu->draw(driver);
		}
		if (state->Mode()) {
			state->Mode()->draw(driver);
		}

		if (state->project && state->project->GetCurrentNode()) {
			vector3df pos = vector3df(
				state->project->GetCurrentNode()->position.X,
				state->project->GetCurrentNode()->position.Y,
				state->project->GetCurrentNode()->position.Z
			);
			target->setPosition(pos);

			camera[0]->setTarget(pos);
			camera[1]->setTarget(pos);
			camera[2]->setTarget(pos);
			camera[3]->setTarget(pos);
		}

		guienv->drawAll();

		driver->endScene();

		#ifdef _DEBUG
		int fps = driver->getFPS();
		if (lastFPS != fps) {
			irr::core::stringw str = L"Node Box Editor [FPS: ";
			str += fps;
			str += "]";

			device->setWindowCaption(str.c_str());
			lastFPS = fps;
		}
		#endif

		if (LastX != ResX || LastY != ResY) {
			LastX = ResX;
			LastY = ResY;
			camera[0]->setAspectRatio((float)ResX / (float)ResY);

			// reset matrix
			matrix4 projMat;
			irr::f32 orth_w = (float)ResX / (float)ResY;
			orth_w = 3 * orth_w;
			projMat.buildProjectionMatrixOrthoLH(orth_w,3,1,100);

			for (int i = 1; i < 4; i++) {
				if (camera[i]) {
					camera[i]->remove();
					camera[i] = NULL;
				}
			}

			// Remake cameras
			camera[1] = smgr->addCameraSceneNode(target, vector3df(0, 2, -0.01), vector3df(0, 0, 0));
			camera[1]->setProjectionMatrix(projMat, true);

			camera[2] = smgr->addCameraSceneNode(target, vector3df(0, 0, -5), vector3df(0, 0, 0));
			camera[2]->setProjectionMatrix(projMat, true);

			camera[3] = smgr->addCameraSceneNode(target, vector3df(-5, 0, 0), vector3df(0, 0, 0));
			camera[3]->setProjectionMatrix(projMat, true);
		}

		// Update
		if (state->Mode()) {
			state->Mode()->update(dtime);
		}

		// Do sleep
		unsigned int now = std::clock();
		if (dosleep) {
			u32 sleeptime = int(double(1000) / double(65)) - (now - last);
			if (sleeptime > 0 && sleeptime < 200)
				device->sleep(sleeptime);
		}
		dtime = double(now - last) / 1000;
		last = now;		
	}

	return true;
}