void main_loop() { device->run(); // Work out a frame delta time. const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds then = now; /* Check if keys W, S, A or D are being held down, and move the sphere node around respectively. */ core::vector3df nodePosition = node->getPosition(); if(receiver.IsKeyDown(irr::KEY_KEY_W)) nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_S)) nodePosition.Y -= MOVEMENT_SPEED * frameDeltaTime; if(receiver.IsKeyDown(irr::KEY_KEY_A)) nodePosition.X -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_D)) nodePosition.X += MOVEMENT_SPEED * frameDeltaTime; node->setPosition(nodePosition); driver->beginScene(true, true, video::SColor(255,113,113,133)); smgr->drawAll(); // draw the 3d scene device->getGUIEnvironment()->drawAll(); // draw the gui environment (the logo) driver->endScene(); }
int main() { MyEventReceiver receiver; IrrlichtDevice* device = createDevice(video::EDT_OPENGL, core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); smgr->addLightSceneNode(0,vector3df(50,50,50)); ICameraSceneNode *camera = smgr->addCameraSceneNode(); IMeshSceneNode *node = smgr->addCubeSceneNode(); node->setPosition(vector3df(0,75,0)); camera->setTarget(vector3df(0,1,0)); smgr->getMeshManipulator()->setVertexColors(node->getMesh(), SColor(0,0,255,255)); smgr->addLightSceneNode(); while(device->run()){ if(receiver.IsKeyDown(irr::KEY_LEFT)){ node->setPosition(node->getPosition()+vector3df(0,0,-0.1)); } else if(receiver.IsKeyDown(irr::KEY_RIGHT)){ node->setPosition(node->getPosition()+vector3df(0,0,0.1)); } else if(receiver.IsKeyDown(irr::KEY_SPACE)){ } driver->beginScene(true, true, SColor(123,100,100,100)); smgr->drawAll(); driver->endScene(); } return 0; }
int main() { srand(time(NULL)); int numPlayers = 4; //Setup irrlicht MyEventReceiver Receiver; IrrlichtDevice *device = createDevice(EDT_OPENGL,dimension2d<u32>(SCREENX,SCREENY),32,FULLSCREEN,false,false,&Receiver); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); IGUIEnvironment* guienv = device->getGUIEnvironment(); //Load key config Receiver.KeyConfig.loadFromFile("KeyConfig.txt"); //Generate maze MazeGenerator MG; /* MG.NewSize(495,497,495,497); MG.Generate("DrunkenWalk2",500,numPlayers);//500,numPlayers); MG.Minimise(); MG.MinimalSolids(false); MG.ConvertLoneToCover();*/ MG.MapFromFile("Maps/01g.txt", "Maps/01m.txt", "Maps/01e.txt"); vector<int> PlayerStartPos; PlayerStartPos.push_back(10); PlayerStartPos.push_back(11); PlayerStartPos.push_back(12); PlayerStartPos.push_back(13); MG.ParseForPlayerStartPositions(PlayerStartPos); //Setup textures ITexture *FloorTexture = driver->getTexture("Textures/Floor.png"); ITexture *WallTexture = driver->getTexture("Textures/Wall.png"); ITexture *CoverTexture = driver->getTexture("Textures/Cover.png"); //Import maze MazeRenderer MR; MR.CreateFromMazeGenerator( MG, smgr ); MR.SetTextures( FloorTexture, WallTexture, CoverTexture ); //Setup camera GameCamera gameCam(70); gameCam.camera = smgr->addCameraSceneNode(); gameCam.camera->setPosition( vector3df( (MR.XSize/2)*MR.TileSize, 40, (MR.YSize/2)*MR.TileSize ) ); gameCam.camera->setRotation( vector3df(0,90,90)); //Create players (4) for testing //Have to use an array as you can't copy boost::threads which pushing into vectors does EntityManager PlayerManager(numPlayers); //Textures ITexture* PlayerTexture[4]; PlayerTexture[0] = driver->getTexture("Textures/Player1.png"); PlayerTexture[1] = driver->getTexture("Textures/Player2.png"); PlayerTexture[2] = driver->getTexture("Textures/Player3.png"); PlayerTexture[3] = driver->getTexture("Textures/Player4.png"); //Names vector<std::string> PlayerName; PlayerName.push_back("Motoko"); PlayerName.push_back("Saito"); PlayerName.push_back("Batou"); PlayerName.push_back("Togusa"); //use this method to get starting cells for an enemy group vector<v2d> vv = GetFreeCells(MG.Convert(),MG.StartX,MG.StartY,4); //HUD test hud HUD(guienv,dimension2d<s32>(SCREENX,SCREENY),"Font\\myfont.xml"); for (int i = 0; i < numPlayers; i++ ) { PlayerManager.GetEntity(i)->Construct(smgr,MG.Convert(), PlayerTexture[i]); PlayerManager.GetEntity(i)->Stats.Name = PlayerName[i]; PlayerManager.GetEntity(i)->Stats.MaxHealth = 100; PlayerManager.GetEntity(i)->Stats.RestoreAll(); PlayerManager.GetEntity(i)->X = MG.XStarts[i]; PlayerManager.GetEntity(i)->Y = MG.YStarts[i]; PlayerManager.GetEntity(i)->Stats.MovementSteps = 5+i; PlayerManager.GetEntity(i)->ReachableTile = driver->getTexture("Textures/TurnReachable.png"); PlayerManager.GetEntity(i)->UnreachableTile = driver->getTexture("Textures/TurnUnreachable.png"); PlayerManager.GetEntity(i)->Stats.RealFiringDistance = 100; PlayerManager.GetEntity(i)->CellShootable = driver->getTexture("Textures/CellShootable.png"); PlayerManager.GetEntity(i)->CellShootableCover = driver->getTexture("Textures/CellShootableCover.png"); PlayerManager.GetEntity(i)->Position(); path filename = "Avatars/"; filename.append(PlayerName[i].c_str()); filename.append(".png"); PlayerManager.GetEntity(i)->Avatar = driver->getTexture( filename ); //test stats PlayerManager.GetEntity(i)->Stats.Accuracy = 100; PlayerManager.GetEntity(i)->Stats.Attack = 100; PlayerManager.GetEntity(i)->Stats.AttackVariance = 0; PlayerManager.GetEntity(i)->Stats.Defense = 0; PlayerManager.GetEntity(i)->Stats.DefenseVariance = 0; } // Create the 3D cursor ISceneNode *Cursor = smgr->addSphereSceneNode(4); //Setup AI int numEnemies = 1; EntityManager EnemyManager(numEnemies); //Textures (none for now) //Need to keep track of all entity positions, so they don't get placed ontop of each other vector<Entity*> EntityList( PlayerManager.GetEntityList() ); for (int i = 0; i < numEnemies; i++) { EnemyManager.GetEntity(i)->Construct(smgr,MG.Convert(), driver->getTexture("Textures/Enemy.png")); EnemyManager.GetEntity(i)->Stats.Name = PlayerName[i]; EnemyManager.GetEntity(i)->Stats.MaxHealth = 100; EnemyManager.GetEntity(i)->Stats.RestoreAll(); EnemyManager.GetEntity(i)->Stats.MovementSteps = 5+i; EnemyManager.GetEntity(i)->Stats.RealFiringDistance = 100; EnemyManager.GetEntity(i)->Stats.Attack = 50; EnemyManager.GetEntity(i)->Stats.Accuracy = 100; //Stats //steup random position EnemyManager.GetEntity(i)->AI_SetRandomDestination(EntityList); EnemyManager.GetEntity(i)->X = EnemyManager.GetEntity(i)->AI_DestinationX; EnemyManager.GetEntity(i)->Y = EnemyManager.GetEntity(i)->AI_DestinationY; //new path will be created EnemyManager.GetEntity(i)->Position(); EnemyManager.GetEntity(i)->AI_State = AI::Patrol; EnemyManager.GetEntity(i)->isAI = true; EntityList.push_back(EnemyManager.GetEntity(i)); } bool rkf = false; //Game loop while (device->run()) { //Create a list of all entities EntityList.clear(); vector<Entity*> EnemyList( EnemyManager.GetEntityList() ); EntityList.insert( EntityList.end(), EnemyList.begin(), EnemyList.end() ); /* * * * * * * * * * * * * * */ /* Player switching module */ /* * * * * * * * * * * * * * */ for (int i = 0; i < PlayerManager.Size; i++) PlayerManager.GetEntity(i)->CheckIfDead(); PlayerManager.ManageCharacterSwitching(Receiver); /* * * * * * * * * * * */ /* Pathfinding module */ /* * * * * * * * * * * */ PlayerManager.GetCurrentEntity()->UpdatePathDisplayTimer(); if (Receiver.MouseState.LeftButtonDown && PlayerManager.GetCurrentEntity()->NewPathDisplayTimer < 1) PlayerManager.GetCurrentEntity()->CreatePathToDestination(EntityList,smgr,Receiver,Cursor->getPosition(),dimension2d<s32>(MR.XSize,MR.YSize),MG.Convert()); /* * * * * * * * * * * * * */ /* Update position module */ /* * * * * * * * * * * * * */ PlayerManager.GetCurrentEntity()->Position(); /* * * * * * * * * * * */ /* Follow path module */ /* * * * * * * * * * * */ if (Receiver.IsKeyDown(Receiver.KeyConfig.FOLLOW_PATH)) PlayerManager.GetCurrentEntity()->FollowPath(EntityList); /* * * * * * * * * */ /* End turn module */ /* * * * * * * * * */ if (Receiver.IsKeyDown(Receiver.KeyConfig.END_TURN) && !rkf) { rkf = true; PlayerManager.EndTurn(); EnemyManager.AI_StartTurn(EntityList, PlayerManager, smgr, Receiver, irr::core::dimension2d<s32>(MR.XSize,MR.YSize), MG.Convert(), MR.MetaTriangleSelector, MR.MetaCoverTriangleSelector); PlayerManager.StartTurn(); } else if (!Receiver.IsKeyDown(Receiver.KeyConfig.END_TURN)) rkf = false; /* * * * * * * * */ /* Cursor module */ /* * * * * * * * */ Cursor->setPosition( vftovi(MouseTo3D( Receiver, MR.CollisionManager, MR.TriSelector)) ); /* * * * * * * * */ /* Camera module */ /* * * * * * * * */ gameCam.Update(Receiver,PlayerManager.GetCurrentEntity()->Node); /* * * * * * * * * * * * */ /* Stats monitor module */ /* * * * * * * * * * * * */ for (int i=0;i<PlayerManager.Size;i++) PlayerManager.GetEntity(i)->Stats.MonitorAll(); /* * * * * * * * * * */ /* Draw scene module */ /* * * * * * * * * * */ driver->beginScene(true,true,SColor(255,100,101,140)); smgr->drawAll(); guienv->drawAll(); HUD.Draw(guienv,PlayerManager.GetCurrentEntity()->Stats,PlayerManager.GetCurrentEntity()->Avatar); //HUD.DrawAIDebug(guienv,*EnemyManager.GetEntity(0),PlayerManager); driver->endScene(); /* * * * * * * */ /* Menu module */ /* * * * * * * */ if (Receiver.IsKeyDown(Receiver.KeyConfig.MENU)) return 0; /* * * * * * * * * * * * */ /* Firing display module */ /* * * * * * * * * * * * */ if (!Receiver.IsKeyDown(KEY_KEY_S)) PlayerManager.GetCurrentEntity()->ShootDisplayKeyFlag = false; else { PlayerManager.GetCurrentEntity()->ShootDisplayKeyFlag = true; PlayerManager.GetCurrentEntity()->DisplayAllCellsThatCanBeShotUsingThreads(smgr,MR.CollisionManager,MR.MetaTriangleSelector,MR.MetaCoverTriangleSelector); } /* * * * * * * * * */ /* Firing module * */ /* * * * * * * * * */ if (Receiver.MouseState.RightButtonDown && !PlayerManager.GetCurrentEntity()->RightMouseFlag) { PlayerManager.GetCurrentEntity()->RightMouseFlag = true; //second playerManager needs to replaced with enemyManager when in place, the function will also need to be edited FireAtTarget(Receiver, PlayerManager, EnemyManager, MR, smgr, Cursor); } else if (!Receiver.MouseState.RightButtonDown) PlayerManager.GetCurrentEntity()->RightMouseFlag = false; } return 0; }
/* The event receiver for keeping the pressed keys is ready, the actual responses will be made inside the render loop, right before drawing the scene. So lets just create an irr::IrrlichtDevice and the scene node we want to move. We also create some other additional scene nodes, to show that there are also some different possibilities to move and animate scene nodes. */ int main() { // ask user for driver video::E_DRIVER_TYPE driverType=driverChoiceConsole(); if (driverType==video::EDT_COUNT) return 1; // create device MyEventReceiver receiver; IrrlichtDevice* device = createDevice(driverType, core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); if (device == 0) return 1; // could not create selected driver. video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); const io::path mediaPath = getExampleMediaPath(); /* Create the node which will be moved with the WSAD keys. We create a sphere node, which is a built-in geometry primitive. We place the node at (0,0,30) and assign a texture to it to let it look a little bit more interesting. Because we have no dynamic lights in this scene we disable lighting for each model (otherwise the models would be black). */ scene::ISceneNode * node = smgr->addSphereSceneNode(); if (node) { node->setPosition(core::vector3df(0,0,30)); node->setMaterialTexture(0, driver->getTexture(mediaPath + "wall.bmp")); node->setMaterialFlag(video::EMF_LIGHTING, false); } /* Now we create another node, movable using a scene node animator. Scene node animators modify scene nodes and can be attached to any scene node like mesh scene nodes, billboards, lights and even camera scene nodes. Scene node animators are not only able to modify the position of a scene node, they can also animate the textures of an object for example. We create a cube scene node and attach a 'fly circle' scene node animator to it, letting this node fly around our sphere scene node. */ scene::ISceneNode* n = smgr->addCubeSceneNode(); if (n) { n->setMaterialTexture(0, driver->getTexture(mediaPath + "t351sml.jpg")); n->setMaterialFlag(video::EMF_LIGHTING, false); scene::ISceneNodeAnimator* anim = smgr->createFlyCircleAnimator(core::vector3df(0,0,30), 20.0f); if (anim) { n->addAnimator(anim); anim->drop(); } } /* The last scene node we add to show possibilities of scene node animators is a b3d model, which uses a 'fly straight' animator to run between to points. */ scene::IAnimatedMeshSceneNode* anms = smgr->addAnimatedMeshSceneNode(smgr->getMesh(mediaPath + "ninja.b3d")); if (anms) { scene::ISceneNodeAnimator* anim = smgr->createFlyStraightAnimator(core::vector3df(100,0,60), core::vector3df(-100,0,60), 3500, true); if (anim) { anms->addAnimator(anim); anim->drop(); } /* To make the model look right we disable lighting, set the frames between which the animation should loop, rotate the model around 180 degrees, and adjust the animation speed and the texture. To set the right animation (frames and speed), we would also be able to just call "anms->setMD2Animation(scene::EMAT_RUN)" for the 'run' animation instead of "setFrameLoop" and "setAnimationSpeed", but this only works with MD2 animations, and so you know how to start other animations. But a good advice is to not use hardcoded frame-numbers... */ anms->setMaterialFlag(video::EMF_LIGHTING, false); anms->setFrameLoop(0, 13); anms->setAnimationSpeed(15); // anms->setMD2Animation(scene::EMAT_RUN); anms->setScale(core::vector3df(2.f,2.f,2.f)); anms->setRotation(core::vector3df(0,-90,0)); // anms->setMaterialTexture(0, driver->getTexture(mediaPath + "sydney.bmp")); } /* To be able to look at and move around in this scene, we create a first person shooter style camera and make the mouse cursor invisible. */ smgr->addCameraSceneNodeFPS(); device->getCursorControl()->setVisible(false); /* Add a colorful irrlicht logo */ device->getGUIEnvironment()->addImage( driver->getTexture(mediaPath + "irrlichtlogoalpha2.tga"), core::position2d<s32>(10,20)); gui::IGUIStaticText* diagnostics = device->getGUIEnvironment()->addStaticText( L"", core::rect<s32>(10, 10, 400, 20)); diagnostics->setOverrideColor(video::SColor(255, 255, 255, 0)); /* We have done everything, so lets draw it. We also write the current frames per second and the name of the driver to the caption of the window. */ int lastFPS = -1; // In order to do framerate independent movement, we have to know // how long it was since the last frame u32 then = device->getTimer()->getTime(); // This is the movemen speed in units per second. const f32 MOVEMENT_SPEED = 5.f; while(device->run()) { // Work out a frame delta time. const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds then = now; /* Check if keys W, S, A or D are being held down, and move the sphere node around respectively. */ core::vector3df nodePosition = node->getPosition(); if(receiver.IsKeyDown(irr::KEY_KEY_W)) nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_S)) nodePosition.Y -= MOVEMENT_SPEED * frameDeltaTime; if(receiver.IsKeyDown(irr::KEY_KEY_A)) nodePosition.X -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_D)) nodePosition.X += MOVEMENT_SPEED * frameDeltaTime; node->setPosition(nodePosition); driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, video::SColor(255,113,113,133)); smgr->drawAll(); // draw the 3d scene device->getGUIEnvironment()->drawAll(); // draw the gui environment (the logo) driver->endScene(); int fps = driver->getFPS(); if (lastFPS != fps) { core::stringw tmp(L"Movement Example - Irrlicht Engine ["); tmp += driver->getName(); tmp += L"] fps: "; tmp += fps; device->setWindowCaption(tmp.c_str()); lastFPS = fps; } } /* In the end, delete the Irrlicht device. */ device->drop(); return 0; }
/* The event receiver for keeping the pressed keys is ready, the actual responses will be made inside the render loop, right before drawing the scene. So lets just create an irr::IrrlichtDevice and the scene node we want to move. We also create some other additional scene nodes, to show that there are also some different possibilities to move and animate scene nodes. */ int main() { // ask user for driver video::E_DRIVER_TYPE driverType=driverChoiceConsole(); if (driverType==video::EDT_COUNT) return 1; // create device MyEventReceiver receiver; IrrlichtDevice* device = createDevice(driverType, core::dimension2d<u32>(1280, 800), 16, false, false, false, &receiver); if (device == 0) return 1; // could not create selected driver. video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); /* Create the node which will be moved with the WSAD keys. We create a sphere node, which is a built-in geometry primitive. We place the node at (0,0,30) and assign a texture to it to let it look a little bit more interesting. Because we have no dynamic lights in this scene we disable lighting for each model (otherwise the models would be black). */ scene::ISceneNode * node = smgr->addSphereSceneNode(EARTH_RADIUS, 36); if (node) { node->setPosition(core::vector3df(0,0,30)); #ifdef _MSC_VER node->setMaterialTexture(0, driver->getTexture("../../../src/vendor/irrlicht/media/wall.bmp")); #else node->setMaterialTexture(0, driver->getTexture("../../src/vendor/irrlicht/media/wall.bmp")); #endif node->setMaterialFlag(video::EMF_LIGHTING, false); } /* To be able to look at and move around in this scene, we create a first person shooter style camera and make the mouse cursor invisible. */ scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(); camera->setPosition(core::vector3df(0, 0, -EARTH_RADIUS * START_DISTANCE)); camera->setTarget(core::vector3df(0, 0, 0)); const f32 ONE_AU = 149597870.0f; #if(0) camera->setFarValue(ONE_AU); #else camera->setFarValue(2<<23); #endif device->getCursorControl()->setVisible(false); /* We have done everything, so lets draw it. We also write the current frames per second and the name of the driver to the caption of the window. */ int lastFPS = -1; // In order to do framerate independent movement, we have to know // how long it was since the last frame u32 then = device->getTimer()->getTime(); // This is the movemen speed in units per second. //#if(1) const f32 MOVEMENT_SPEED = .5f; //#else //const f32 MOVEMENT_SPEED = EARTH_RADIUS; //#endif Skybox skybox(smgr, driver); while(device->run()) { // Work out a frame delta time. const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds then = now; /* Check if keys W, S, A or D are being held down, and move the sphere node around respectively. */ core::vector3df nodePosition = node->getPosition(); if(receiver.IsKeyDown(irr::KEY_KEY_W)) nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_S)) nodePosition.Y -= MOVEMENT_SPEED * frameDeltaTime; if(receiver.IsKeyDown(irr::KEY_KEY_A)) nodePosition.X -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_D)) nodePosition.X += MOVEMENT_SPEED * frameDeltaTime; node->setPosition(nodePosition); driver->beginScene(true, true, video::SColor(255,113,113,133)); smgr->drawAll(); // draw the 3d scene device->getGUIEnvironment()->drawAll(); // draw the gui environment (the logo) driver->endScene(); int fps = driver->getFPS(); if (lastFPS != fps) { core::stringw tmp(L"Movement Example - Irrlicht Engine ["); tmp += driver->getName(); tmp += L"] fps: "; tmp += fps; device->setWindowCaption(tmp.c_str()); lastFPS = fps; } } /* In the end, delete the Irrlicht device. */ device->drop(); return 0; }
int main(int argc, char* argv[]) { // ask user for driver video::E_DRIVER_TYPE driverType=driverChoiceConsole(); if (driverType==video::EDT_COUNT) return 1; MyEventReceiver receiver; IrrlichtDevice* device = createDevice(driverType, core::dimension2du(800, 600), 32, false, false, false, &receiver); if(device == 0) return 1; IVideoDriver *driver = device->getVideoDriver(); ISceneManager *smgr = device->getSceneManager(); device->setWindowCaption(L"Irrlicht Example for SMesh usage."); /* Create the custom mesh and initialize with a heightmap */ TMesh mesh; HeightMap hm = HeightMap(255, 255); hm.generate(eggbox); mesh.init(hm, 50.f, grey, driver); // Add the mesh to the scene graph IMeshSceneNode* meshnode = smgr -> addMeshSceneNode(mesh.Mesh); meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, false); // light is just for nice effects ILightSceneNode *node = smgr->addLightSceneNode(0, vector3df(0,100,0), SColorf(1.0f, 0.6f, 0.7f, 1.0f), 500.0f); if (node) { node->getLightData().Attenuation.set(0.f, 1.f/500.f, 0.f); ISceneNodeAnimator* anim = smgr->createFlyCircleAnimator(vector3df(0,150,0),250.0f); if (anim) { node->addAnimator(anim); anim->drop(); } } ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(); if (camera) { camera->setPosition(vector3df(-20.f, 150.f, -20.f)); camera->setTarget(vector3df(200.f, -80.f, 150.f)); camera->setFarValue(20000.0f); } /* Just a usual render loop with event handling. The custom mesh is a usual part of the scene graph which gets rendered by drawAll. */ while(device->run()) { if(!device->isWindowActive()) { device->sleep(100); continue; } if(receiver.IsKeyDown(irr::KEY_KEY_W)) { meshnode->setMaterialFlag(video::EMF_WIREFRAME, !meshnode->getMaterial(0).Wireframe); } else if(receiver.IsKeyDown(irr::KEY_KEY_1)) { hm.generate(eggbox); mesh.init(hm, 50.f, grey, driver); } else if(receiver.IsKeyDown(irr::KEY_KEY_2)) { hm.generate(moresine); mesh.init(hm, 50.f, yellow, driver); } else if(receiver.IsKeyDown(irr::KEY_KEY_3)) { hm.generate(justexp); mesh.init(hm, 50.f, yellow, driver); } driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, SColor(0xff000000)); smgr->drawAll(); driver->endScene(); } device->drop(); return 0; }
/* We create an irr::IrrlichtDevice and the scene nodes. One occluder, one occluded. The latter is a complex sphere, which has many triangles. */ int main() { // ask user for driver video::E_DRIVER_TYPE driverType=driverChoiceConsole(); if (driverType==video::EDT_COUNT) return 1; // create device MyEventReceiver receiver; IrrlichtDevice* device = createDevice(driverType, core::dimension2d<u32>(640, 480), 16, false, false, false, &receiver); if (device == 0) return 1; // could not create selected driver. video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); const io::path mediaPath = getExampleMediaPath(); smgr->getGUIEnvironment()->addStaticText(L"Press Space to hide occluder.", core::recti(10,10, 200,50)); /* Create the node to be occluded. We create a sphere node with high poly count. */ scene::ISceneNode * node = smgr->addSphereSceneNode(10, 64); if (node) { node->setPosition(core::vector3df(0,0,60)); node->setMaterialTexture(0, driver->getTexture(mediaPath + "wall.bmp")); node->setMaterialFlag(video::EMF_LIGHTING, false); } /* Now we create another node, the occluder. It's a simple plane. */ scene::ISceneNode* plane = smgr->addMeshSceneNode(smgr->addHillPlaneMesh( "plane", core::dimension2df(10,10), core::dimension2du(2,2)), 0, -1, core::vector3df(0,0,20), core::vector3df(270,0,0)); if (plane) { plane->setMaterialTexture(0, driver->getTexture(mediaPath + "t351sml.jpg")); plane->setMaterialFlag(video::EMF_LIGHTING, false); plane->setMaterialFlag(video::EMF_BACK_FACE_CULLING, true); } /* Here we create the occlusion query. Because we don't have a plain mesh scene node (ESNT_MESH or ESNT_ANIMATED_MESH), we pass the base geometry as well. Instead, we could also pass a simpler mesh or the bounding box. But we will use a time based method, where the occlusion query renders to the frame buffer and in case of success (occlusion), the mesh is not drawn for several frames. */ driver->addOcclusionQuery(node, ((scene::IMeshSceneNode*)node)->getMesh()); /* We have done everything, just a camera and draw it. We also write the current frames per second and the name of the driver to the caption of the window to examine the render speedup. We also store the time for measuring the time since the last occlusion query ran and store whether the node should be visible in the next frames. */ smgr->addCameraSceneNode(); int lastFPS = -1; u32 timeNow = device->getTimer()->getTime(); bool nodeVisible=true; while(device->run()) { plane->setVisible(!receiver.IsKeyDown(irr::KEY_SPACE)); driver->beginScene(video::ECBF_COLOR | video::ECBF_DEPTH, video::SColor(255,113,113,133)); /* First, we draw the scene, possibly without the occluded element. This is necessary because we need the occluder to be drawn first. You can also use several scene managers to collect a number of possible occluders in a separately rendered scene. */ node->setVisible(nodeVisible); smgr->drawAll(); smgr->getGUIEnvironment()->drawAll(); /* Once in a while, here every 100 ms, we check the visibility. We run the queries, update the pixel value, and query the result. Since we already rendered the node we render the query invisible. The update is made blocking, as we need the result immediately. If you don't need the result immediately, e.g. because you have other things to render, you can call the update non-blocking. This gives the GPU more time to pass back the results without flushing the render pipeline. If the update was called non-blocking, the result from getOcclusionQueryResult is either the previous value, or 0xffffffff if no value has been generated at all, yet. The result is taken immediately as visibility flag for the node. */ if (device->getTimer()->getTime()-timeNow>100) { driver->runAllOcclusionQueries(false); driver->updateAllOcclusionQueries(); nodeVisible=driver->getOcclusionQueryResult(node)>0; timeNow=device->getTimer()->getTime(); } driver->endScene(); int fps = driver->getFPS(); if (lastFPS != fps) { core::stringw tmp(L"OcclusionQuery Example ["); tmp += driver->getName(); tmp += L"] fps: "; tmp += fps; device->setWindowCaption(tmp.c_str()); lastFPS = fps; } } /* In the end, delete the Irrlicht device. */ device->drop(); return 0; }
int main() { sockets_init(); atexit(sockets_cleanup); /* Run unit tests */ if(ENABLE_TESTS) run_tests(); //return 0; //DEBUG /* Initialization */ srand(time(0)); g_viewing_range_nodes_mutex.Init(); assert(g_viewing_range_nodes_mutex.IsInitialized()); MyEventReceiver receiver; // create device and exit if creation failed /* Host selection */ char connect_name[100]; std::cout<<std::endl<<std::endl; std::cout<<"Address to connect to [empty = host a game]: "; std::cin.getline(connect_name, 100); bool hosting = false; if(connect_name[0] == 0){ snprintf(connect_name, 100, "127.0.0.1"); hosting = true; } std::cout<<"-> "<<connect_name<<std::endl; std::cout<<"Port [empty=30000]: "; char templine[100]; std::cin.getline(templine, 100); unsigned short port; if(templine[0] == 0) port = 30000; else port = atoi(templine); /* Resolution selection */ u16 screenW = 800; u16 screenH = 600; /* u16 resolutions[][2] = { {640,480}, {800,600}, {1024,768}, {1280,1024} }; u16 res_count = sizeof(resolutions)/sizeof(resolutions[0]); std::cout<<"Select window resolution " <<"(type a number and press enter):"<<std::endl; for(u16 i=0; i<res_count; i++) { std::cout<<(i+1)<<": "<<resolutions[i][0]<<"x" <<resolutions[i][1]<<std::endl; } u16 r0; std::cin>>r0; if(r0 > res_count || r0 == 0) r0 = 0; u16 screenW = resolutions[r0-1][0]; u16 screenH = resolutions[r0-1][1]; */ // video::E_DRIVER_TYPE driverType; #ifdef _WIN32 //driverType = video::EDT_DIRECT3D9; // Doesn't seem to work driverType = video::EDT_OPENGL; #else driverType = video::EDT_OPENGL; #endif IrrlichtDevice *device; device = createDevice(driverType, core::dimension2d<u32>(screenW, screenH), 16, false, false, false, &receiver); if (device == 0) return 1; // could not create selected driver. /* Run some speed tests */ //SpeedTests(device); /* Continue initialization */ video::IVideoDriver* driver = device->getVideoDriver(); // These make the textures not to show at all //driver->setTextureCreationFlag(video::ETCF_ALWAYS_16_BIT); //driver->setTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED ); scene::ISceneManager* smgr = device->getSceneManager(); gui::IGUIEnvironment* guienv = device->getGUIEnvironment(); gui::IGUISkin* skin = guienv->getSkin(); gui::IGUIFont* font = guienv->getFont("../data/fontlucida.png"); if(font) skin->setFont(font); //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255)); //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0)); //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0)); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0)); skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0)); const wchar_t *text = L"Loading..."; core::vector2d<s32> center(screenW/2, screenH/2); core::dimension2d<u32> textd = font->getDimension(text); std::cout<<"Text w="<<textd.Width<<" h="<<textd.Height<<std::endl; // Have to add a bit to disable the text from word wrapping //core::vector2d<s32> textsize(textd.Width+4, textd.Height); core::vector2d<s32> textsize(300, textd.Height); core::rect<s32> textrect(center - textsize/2, center + textsize/2); gui::IGUIStaticText *gui_loadingtext = guienv->addStaticText( text, textrect, false, false); gui_loadingtext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); driver->beginScene(true, true, video::SColor(255,0,0,0)); guienv->drawAll(); driver->endScene(); video::SMaterial materials[MATERIALS_COUNT]; for(u16 i=0; i<MATERIALS_COUNT; i++) { materials[i].Lighting = false; materials[i].BackfaceCulling = false; const char *filename = g_material_filenames[i]; if(filename != NULL){ video::ITexture *t = driver->getTexture(filename); if(t == NULL){ std::cout<<"Texture could not be loaded: \"" <<filename<<"\""<<std::endl; return 1; } materials[i].setTexture(0, driver->getTexture(filename)); } //materials[i].setFlag(video::EMF_TEXTURE_WRAP, video::ETC_REPEAT); materials[i].setFlag(video::EMF_BILINEAR_FILTER, false); //materials[i].setFlag(video::EMF_ANISOTROPIC_FILTER, false); } // Make a scope here for the client so that it gets removed // before the irrlicht device { std::cout<<"Creating server and client"<<std::endl; Server *server = NULL; if(hosting){ server = new Server(); server->start(port); } Client client(smgr, materials); Address connect_address(0,0,0,0, port); try{ connect_address.Resolve(connect_name); } catch(ResolveError &e) { std::cout<<"Couldn't resolve address"<<std::endl; return 0; } client.connect(connect_address); Player *player = client.getLocalPlayer(); /* Create the camera node */ scene::ICameraSceneNode* camera = smgr->addCameraSceneNode( 0, // Camera parent v3f(BS*100, BS*2, BS*100), // Look from v3f(BS*100+1, BS*2, BS*100), // Look to -1 // Camera ID ); if(camera == NULL) return 1; camera->setFOV(FOV_ANGLE); // Just so big a value that everything rendered is visible camera->setFarValue(BS*1000); f32 camera_yaw = 0; // "right/left" f32 camera_pitch = 0; // "up/down" // Random constants #define WALK_ACCELERATION (4.0 * BS) #define WALKSPEED_MAX (4.0 * BS) //#define WALKSPEED_MAX (20.0 * BS) f32 walk_acceleration = WALK_ACCELERATION; f32 walkspeed_max = WALKSPEED_MAX; /* The mouse cursor needs not be visible, so we hide it via the irr::IrrlichtDevice::ICursorControl. */ device->getCursorControl()->setVisible(false); gui_loadingtext->remove(); gui::IGUIStaticText *guitext = guienv->addStaticText( L"Minetest-c55", core::rect<s32>(5, 5, 5+300, 5+textsize.Y), false, false); /* Main loop */ bool first_loop_after_window_activation = true; s32 lastFPS = -1; // Time is in milliseconds u32 lasttime = device->getTimer()->getTime(); while(device->run()) { /* Time difference calculation */ u32 time = device->getTimer()->getTime(); f32 dtime; // in seconds if(time > lasttime) dtime = (time - lasttime) / 1000.0; else dtime = 0; lasttime = time; updateViewingRange(dtime); // Collected during the loop and displayed core::list< core::aabbox3d<f32> > hilightboxes; /* Special keys */ if(receiver.IsKeyDown(irr::KEY_ESCAPE)) { break; } /* Player speed control */ v3f move_direction = v3f(0,0,1); move_direction.rotateXZBy(camera_yaw); v3f speed = v3f(0,0,0); if(receiver.IsKeyDown(irr::KEY_KEY_W)) { speed += move_direction; } if(receiver.IsKeyDown(irr::KEY_KEY_S)) { speed -= move_direction; } if(receiver.IsKeyDown(irr::KEY_KEY_A)) { speed += move_direction.crossProduct(v3f(0,1,0)); } if(receiver.IsKeyDown(irr::KEY_KEY_D)) { speed += move_direction.crossProduct(v3f(0,-1,0)); } if(receiver.IsKeyDown(irr::KEY_SPACE)) { if(player->touching_ground){ //player_speed.Y = 30*BS; //player.speed.Y = 5*BS; player->speed.Y = 6.5*BS; } } // The speed of the player (Y is ignored) speed = speed.normalize() * walkspeed_max; f32 inc = walk_acceleration * BS * dtime; if(player->speed.X < speed.X - inc) player->speed.X += inc; else if(player->speed.X > speed.X + inc) player->speed.X -= inc; else if(player->speed.X < speed.X) player->speed.X = speed.X; else if(player->speed.X > speed.X) player->speed.X = speed.X; if(player->speed.Z < speed.Z - inc) player->speed.Z += inc; else if(player->speed.Z > speed.Z + inc) player->speed.Z -= inc; else if(player->speed.Z < speed.Z) player->speed.Z = speed.Z; else if(player->speed.Z > speed.Z) player->speed.Z = speed.Z; /* Process environment */ { //TimeTaker("client.step(dtime)", device); client.step(dtime); } if(server != NULL){ //TimeTaker("server->step(dtime)", device); server->step(dtime); } /* Mouse and camera control */ if(device->isWindowActive()) { if(first_loop_after_window_activation){ first_loop_after_window_activation = false; } else{ s32 dx = device->getCursorControl()->getPosition().X - 320; s32 dy = device->getCursorControl()->getPosition().Y - 240; camera_yaw -= dx*0.2; camera_pitch += dy*0.2; if(camera_pitch < -89.9) camera_pitch = -89.9; if(camera_pitch > 89.9) camera_pitch = 89.9; } device->getCursorControl()->setPosition(320, 240); } else{ first_loop_after_window_activation = true; } v3f camera_direction = v3f(0,0,1); camera_direction.rotateYZBy(camera_pitch); camera_direction.rotateXZBy(camera_yaw); v3f camera_position = player->getPosition() + v3f(0, BS+BS/2, 0); camera->setPosition(camera_position); camera->setTarget(camera_position + camera_direction); if(FIELD_OF_VIEW_TEST){ //client.m_env.getMap().updateCamera(v3f(0,0,0), v3f(0,0,1)); client.updateCamera(v3f(0,0,0), v3f(0,0,1)); } else{ //client.m_env.getMap().updateCamera(camera_position, camera_direction); client.updateCamera(camera_position, camera_direction); } /* Calculate what block is the crosshair pointing to */ //u32 t1 = device->getTimer()->getTime(); f32 d = 4; // max. distance core::line3d<f32> shootline(camera_position, camera_position + camera_direction * BS * (d+1)); bool nodefound = false; v3s16 nodepos; v3s16 neighbourpos; core::aabbox3d<f32> nodefacebox; f32 mindistance = BS * 1001; v3s16 pos_i = Map::floatToInt(player->getPosition()); s16 a = d; s16 ystart = pos_i.Y + 0 - (camera_direction.Y<0 ? a : 1); s16 zstart = pos_i.Z - (camera_direction.Z<0 ? a : 1); s16 xstart = pos_i.X - (camera_direction.X<0 ? a : 1); s16 yend = pos_i.Y + 1 + (camera_direction.Y>0 ? a : 1); s16 zend = pos_i.Z + (camera_direction.Z>0 ? a : 1); s16 xend = pos_i.X + (camera_direction.X>0 ? a : 1); for(s16 y = ystart; y <= yend; y++){ for(s16 z = zstart; z <= zend; z++){ for(s16 x = xstart; x <= xend; x++) { try{ //if(client.m_env.getMap().getNode(x,y,z).d == MATERIAL_AIR){ if(client.getNode(v3s16(x,y,z)).d == MATERIAL_AIR){ continue; } }catch(InvalidPositionException &e){ continue; } v3s16 np(x,y,z); v3f npf = Map::intToFloat(np); f32 d = 0.01; v3s16 directions[6] = { v3s16(0,0,1), // back v3s16(0,1,0), // top v3s16(1,0,0), // right v3s16(0,0,-1), v3s16(0,-1,0), v3s16(-1,0,0), }; for(u16 i=0; i<6; i++){ //{u16 i=3; v3f dir_f = v3f(directions[i].X, directions[i].Y, directions[i].Z); v3f centerpoint = npf + dir_f * BS/2; f32 distance = (centerpoint - camera_position).getLength(); if(distance < mindistance){ //std::cout<<"for centerpoint=("<<centerpoint.X<<","<<centerpoint.Y<<","<<centerpoint.Z<<"): distance < mindistance"<<std::endl; //std::cout<<"npf=("<<npf.X<<","<<npf.Y<<","<<npf.Z<<")"<<std::endl; core::CMatrix4<f32> m; m.buildRotateFromTo(v3f(0,0,1), dir_f); // This is the back face v3f corners[2] = { v3f(BS/2, BS/2, BS/2), v3f(-BS/2, -BS/2, BS/2+d) }; for(u16 j=0; j<2; j++){ m.rotateVect(corners[j]); corners[j] += npf; //std::cout<<"box corners["<<j<<"]: ("<<corners[j].X<<","<<corners[j].Y<<","<<corners[j].Z<<")"<<std::endl; } //core::aabbox3d<f32> facebox(corners[0],corners[1]); core::aabbox3d<f32> facebox(corners[0]); facebox.addInternalPoint(corners[1]); if(facebox.intersectsWithLine(shootline)){ nodefound = true; nodepos = np; neighbourpos = np + directions[i]; mindistance = distance; nodefacebox = facebox; } } } }}} if(nodefound){ //std::cout<<"nodefound == true"<<std::endl; //std::cout<<"nodepos=("<<nodepos.X<<","<<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl; //std::cout<<"neighbourpos=("<<neighbourpos.X<<","<<neighbourpos.Y<<","<<neighbourpos.Z<<")"<<std::endl; static v3s16 nodepos_old(-1,-1,-1); if(nodepos != nodepos_old){ std::cout<<"Pointing at ("<<nodepos.X<<"," <<nodepos.Y<<","<<nodepos.Z<<")"<<std::endl; nodepos_old = nodepos; /*wchar_t positiontext[20]; swprintf(positiontext, 20, L"(%i,%i,%i)", nodepos.X, nodepos.Y, nodepos.Z); positiontextgui->setText(positiontext);*/ } hilightboxes.push_back(nodefacebox); if(receiver.leftclicked){ std::cout<<"Removing block (MapNode)"<<std::endl; u32 time1 = device->getTimer()->getRealTime(); //client.m_env.getMap().removeNodeAndUpdate(nodepos); client.removeNode(nodepos); u32 time2 = device->getTimer()->getRealTime(); u32 dtime = time2 - time1; std::cout<<"Took "<<dtime<<"ms"<<std::endl; } if(receiver.rightclicked){ std::cout<<"Placing block (MapNode)"<<std::endl; u32 time1 = device->getTimer()->getRealTime(); /*f32 light = client.m_env.getMap().getNode(neighbourpos).light; MapNode n; n.d = g_selected_material; client.m_env.getMap().setNode(neighbourpos, n); client.m_env.getMap().nodeAddedUpdate(neighbourpos, light);*/ MapNode n; n.d = g_selected_material; client.addNode(neighbourpos, n); u32 time2 = device->getTimer()->getRealTime(); u32 dtime = time2 - time1; std::cout<<"Took "<<dtime<<"ms"<<std::endl; } } else{ //std::cout<<"nodefound == false"<<std::endl; //positiontextgui->setText(L""); } receiver.leftclicked = false; receiver.rightclicked = false; /* Update gui stuff */ static u8 old_selected_material = MATERIAL_AIR; if(g_selected_material != old_selected_material) { old_selected_material = g_selected_material; wchar_t temptext[50]; swprintf(temptext, 50, L"Minetest-c55 (F: material=%i)", g_selected_material); guitext->setText(temptext); } /* Drawing begins */ /* Background color is choosen based on whether the player is much beyond the initial ground level */ /*video::SColor bgcolor; v3s16 p0 = Map::floatToInt(player->position); s16 gy = client.m_env.getMap().getGroundHeight(v2s16(p0.X, p0.Z)); if(p0.Y > gy - MAP_BLOCKSIZE) bgcolor = video::SColor(255,90,140,200); else bgcolor = video::SColor(255,0,0,0);*/ video::SColor bgcolor = video::SColor(255,90,140,200); driver->beginScene(true, true, bgcolor); //std::cout<<"smgr->drawAll()"<<std::endl; smgr->drawAll(); core::vector2d<s32> displaycenter(screenW/2,screenH/2); driver->draw2DLine(displaycenter - core::vector2d<s32>(10,0), displaycenter + core::vector2d<s32>(10,0), video::SColor(255,255,255,255)); driver->draw2DLine(displaycenter - core::vector2d<s32>(0,10), displaycenter + core::vector2d<s32>(0,10), video::SColor(255,255,255,255)); video::SMaterial m; m.Thickness = 10; m.Lighting = false; driver->setMaterial(m); for(core::list< core::aabbox3d<f32> >::Iterator i=hilightboxes.begin(); i != hilightboxes.end(); i++){ driver->draw3DBox(*i, video::SColor(255,0,0,0)); } guienv->drawAll(); driver->endScene(); /* Drawing ends */ u16 fps = driver->getFPS(); if (lastFPS != fps) { core::stringw str = L"Minetest ["; str += driver->getName(); str += "] FPS:"; str += fps; device->setWindowCaption(str.c_str()); lastFPS = fps; } /*} else device->yield();*/ } if(server != NULL) delete server; } // client is deleted at this point /* In the end, delete the Irrlicht device. */ device->drop(); return 0; }
/* Now ask for the driver and create the Windows specific window. */ int main() { /* { int vertIndex = 0; for( int Row=0; Row<=16*8; Row++ ) { GuidVertex[vertIndex].x = 0; GuidVertex[vertIndex].y = 0; GuidVertex[vertIndex].z = Row * 2.0f; GuidVertex[vertIndex].VertexColor[0] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[1] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[2] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[3] = 1.0f; vertIndex++; GuidVertex[vertIndex].x = 2*8*16; GuidVertex[vertIndex].y = 0; GuidVertex[vertIndex].z = Row * 2.0f; GuidVertex[vertIndex].VertexColor[0] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[1] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[2] = (Row == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[3] = 1.0f; vertIndex++; } for( int Col=0; Col<=16*8; Col++ ) { GuidVertex[vertIndex].x = Col * 2.0f; GuidVertex[vertIndex].y = 0; GuidVertex[vertIndex].z = 0; GuidVertex[vertIndex].VertexColor[0] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[1] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[2] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[3] = 1.0f; vertIndex++; GuidVertex[vertIndex].x = Col * 2.0f; GuidVertex[vertIndex].y = 0; GuidVertex[vertIndex].z = 2*8*16; GuidVertex[vertIndex].VertexColor[0] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[1] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[2] = (Col == 0) ? 0 : 0.588f; GuidVertex[vertIndex].VertexColor[3] = 1.0f; vertIndex++; } } */ // create log ConsoleLogger logger( String("Hello World") ); logger.setLogLevel( ELL_DEBUG ); Logger::setCurrentLogger( &logger ); // create device MyEventReceiver receiver; SGPDevice* device = createDevice( SGPDT_OPENGL, 1024, 768, 32, false, false, false, true, &logger, &receiver); // could not create selected driver. if (device == NULL) { Logger::setCurrentLogger(nullptr); return 1; } device->setResizable(true); ISGPRenderDevice* renderdevice = device->getRenderDevice(); Random* globalrandom = device->getRandomizer(); // could not get render driver or globalrandom. if (!renderdevice || !globalrandom) { Logger::setCurrentLogger(nullptr); return 1; } // Setting Working Dir String WorkingDir = File::getSpecialLocation(File::currentExecutableFile).getParentDirectory().getParentDirectory().getParentDirectory().getFullPathName(); WorkingDir = WorkingDir + File::separatorString + String("Data"); renderdevice->setWorkingDirection(WorkingDir); // Camera renderdevice->setCameraMode(SGPCT_PERSPECTIVE); renderdevice->setNearFarClipPlane(1.0f, 1000.0f); renderdevice->setFov(45.0f); SViewPort viewarea; viewarea.Width = renderdevice->getScreenSize().Width; viewarea.Height = renderdevice->getScreenSize().Height; renderdevice->setViewPort(viewarea); g_pTestCamera.SetPos(10, 256, 10); g_pTestCamera.SetRotation(-float_Pi/5, 0, 0); // init Font// could not create selected font. if( !renderdevice->CreateFontInManager( "font1", String(L"Font\\YaHei_Consolas.ttf"), true, false, 16 ) ) { delete device; device = NULL; Logger::setCurrentLogger(nullptr); return 1; } renderdevice->PreCacheChar( String("FPSxyz") ); uint32 testDDSID7 = renderdevice->GetTextureManager()->registerTexture(String(L"Texture\\moss.tga"), true); // Init Guid SGPVertex_UPOS_VERTEXCOLOR AxisVertex[6]; renderdevice->GetParticleManager()->initParticleSystemEngine(device->getTimer()->getRealTime()); CSkeletonMeshInstance *ptestModel = new CSkeletonMeshInstance(renderdevice); ptestModel->changeModel( String(L"SkeletonMesh\\magician_male_10000.mf1") ); ptestModel->setScale(0.02f); ptestModel->setRotationY(90.0f * pi_over_180); ptestModel->playAnim(1.0f, 10, 58, true, true); // idle ptestModel->playUpperBodyAnim(1.0f, 75, 99, true, true); // run ptestModel->setEnableUpperBodyAnim(true); //ptestModel->addAttachment(SGPATTDEF_LEFTHAND, String(L"Avatar\\hammer.mf1")); #if 1 renderdevice->GetWorldSystemManager()->createWorldSun(); renderdevice->GetWorldSystemManager()->createSkydome( String(L"skydome\\skydome.mf1") ); renderdevice->GetWorldSystemManager()->setSkydomeTexture( String(L"skydome\\cloud001.dds"), String(L"skydome\\perturb001.dds") ); renderdevice->GetWorldSystemManager()->setWorldSunPosition(38.0f); CSGPWorldMap* pWorldMap = new CSGPWorldMap(); renderdevice->GetWorldSystemManager()->createNewWorld(pWorldMap, "newworld", SGPTS_SMALL, false, 70, String(L"Texture\\terrain\\dirt001.dds") ); #endif //renderdevice->GetWorldSystemManager()->loadWorldFromFile(WorkingDir, String(L"worldmap\\newworld.map")); #if 1 // addWaterChunk must be called before creating Quadtree renderdevice->GetWorldSystemManager()->createWater(40.0f, String(L"Texture\\water\\wavesbump.dds")); renderdevice->GetWorldSystemManager()->addWaterChunk(192); renderdevice->GetWorldSystemManager()->addWaterChunk(193); renderdevice->GetWorldSystemManager()->addWaterChunk(194); renderdevice->GetWorldSystemManager()->addWaterChunk(195); renderdevice->GetWorldSystemManager()->addWaterChunk(208); renderdevice->GetWorldSystemManager()->addWaterChunk(209); renderdevice->GetWorldSystemManager()->addWaterChunk(210); renderdevice->GetWorldSystemManager()->addWaterChunk(211); renderdevice->GetWorldSystemManager()->addWaterChunk(224); renderdevice->GetWorldSystemManager()->addWaterChunk(225); renderdevice->GetWorldSystemManager()->addWaterChunk(226); renderdevice->GetWorldSystemManager()->addWaterChunk(227); renderdevice->GetWorldSystemManager()->addWaterChunk(240); renderdevice->GetWorldSystemManager()->addWaterChunk(241); renderdevice->GetWorldSystemManager()->addWaterChunk(242); renderdevice->GetWorldSystemManager()->addWaterChunk(243); renderdevice->GetWorldSystemManager()->createGrass( String(L"Texture\\grasses.dds"), 2, 2 ); Vector3D terrainNorm; SGPGrassCluster tempGrassCluster; for( int i=0; i<10; i++ ) { for( int j=0; j<10; j++ ) { tempGrassCluster.fPositionX = 10.0f + globalrandom->nextInt(256) / 25.0f; tempGrassCluster.fPositionZ = 10.0f + globalrandom->nextInt(256) / 25.0f; tempGrassCluster.fPositionY = renderdevice->GetWorldSystemManager()->getRealTerrainHeight(tempGrassCluster.fPositionX, tempGrassCluster.fPositionZ); terrainNorm = renderdevice->GetWorldSystemManager()->getTerrainNormal(tempGrassCluster.fPositionX, tempGrassCluster.fPositionZ); tempGrassCluster.nPackedNormal = (uint32((terrainNorm.x * 0.5f + 0.5f) * 255) << 24) + (uint32((terrainNorm.y * 0.5f + 0.5f) * 255) << 16) + (uint32((terrainNorm.z * 0.5f + 0.5f) * 255) << 8); tempGrassCluster.nData = 0xFF000000 + (globalrandom->nextInt(256) << 8) + globalrandom->nextInt(256); renderdevice->GetWorldSystemManager()->setGrassCluster(tempGrassCluster.fPositionX, tempGrassCluster.fPositionZ, tempGrassCluster); } } CSGPWorldConfig::getInstance()->m_fGrassFarFadingStart = 32.0f; CSGPWorldConfig::getInstance()->m_fGrassFarFadingEnd = 80.0f; #endif renderdevice->GetWorldSystemManager()->initializeQuadTree(); #if 1 ISGPObject* pObj0 = renderdevice->GetWorldSystemManager()->createObject( String(L"StaticMesh\\jianzhu.mf1"), String(L"SceneObject01"), Vector3D(45.0f, 30.0f, 28.0f) ); pObj0->m_fScale = 1.5f; pObj0->m_fRotationXYZ[1] = 45.0f * pi_over_180; renderdevice->GetWorldSystemManager()->addSceneObject(pObj0); #endif ptestModel->setPosition(13.55f, renderdevice->GetWorldSystemManager()->getRealTerrainHeight(13.55f,3.55f), 3.55f); //ptestModel->setScale(5.0f); ptestModel->setVisible(true); // Create other render to frame buffer CSGPWorldConfig::getInstance()->m_bPostFog = true; renderdevice->createRenderToFrameBuffer( viewarea.Width, viewarea.Height, false ); // In order to do framerate independent movement, we have to know // how long it was since the last frame device->setWindowCaption(L"SGP Engine - Test Sample Demo"); uint32 LastXPos = receiver.getXPosition(); uint32 LastYPos = receiver.getYPosition(); double averageMS = 0; double averageFPS = 0; while(device->run() && renderdevice) { if(receiver.IsKeyDown(KEY_F1)) { static int mmmm = 0; if( mmmm == 0) { String WorldMapName = String(L"worldmap\\") + renderdevice->GetWorldSystemManager()->getWorldName() + String(L".map"); renderdevice->GetWorldSystemManager()->saveWorldToFile(WorkingDir, WorldMapName); mmmm++; } } if(receiver.IsKeyDown(KEY_F3)) { static int gg = 0; if( gg == 0 ) { renderdevice->GetWorldSystemManager()->setHeightMap(8, 119, 80); renderdevice->GetWorldSystemManager()->setHeightMap(8, 120, 80); uint32 chunks[4] = {224, 225, 240, 241}; renderdevice->GetWorldSystemManager()->flushTerrainHeight(chunks, 4); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_Diffuse1Texture, String(L"Texture\\terrain\\dirt004.dds")); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_Diffuse2Texture, String(L"Texture\\terrain\\dirt002.dds")); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_Diffuse3Texture, String(L"Texture\\terrain\\stone001.dds")); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_NormalMapTexture, String(L"Texture\\terrain\\normal001.dds")); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_DetailMapTexture, String(L"Texture\\terrain\\detailmap001.dds")); renderdevice->GetWorldSystemManager()->setTerrainChunkLayerTexture(240, eChunk_SlopeMapTexture, String(L"Texture\\terrain\\slope.dds")); gg++; } uint32* pRawAlphaData = renderdevice->GetWorldSystemManager()->getWorldMap()->m_WorldChunkAlphaTextureData; for( int i=0; i<SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION; i++ ) for( int j=15*SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION; j<16*SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION; j++ ) pRawAlphaData[j*16*SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION+i] = 0xFF800080; renderdevice->GetWorldSystemManager()->editTerrainChunkBlendTexture(0, 15*SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION, SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION, SGPTT_TILENUM * SGPTBD_BLENDTEXTURE_DIMISION, pRawAlphaData); } if(receiver.IsKeyDown(KEY_F4)) { static int hhhh = 0; if( hhhh == 0) { uint32 chunks[4] = {224, 225, 240, 241}; renderdevice->GetWorldSystemManager()->flushTerrainNormal(chunks, 4); renderdevice->GetWorldSystemManager()->flushTerrainChunkColorMinimapTexture(chunks, 1); renderdevice->GetWorldSystemManager()->initializeQuadTree(); hhhh++; } } if(receiver.IsKeyDown(KEY_F5)) { static int aaaa = 0; if( aaaa == 0) { ISGPLightObject *pLight02 = renderdevice->GetWorldSystemManager()->createLightObject( String(L"LightGreen"), SGPLT_Point, Vector3D(45.0f, 38.0f, 21.0f), Vector3D(0.0f, -1.0f, 0.0f), 0.3f, 30.0f, Colour(0, 255, 0) ); renderdevice->GetWorldSystemManager()->addLightObject(pLight02); renderdevice->GetWorldSystemManager()->initializeCollisionSet(); float fProgress = 0; renderdevice->GetWorldSystemManager()->updateSceneObjectLightmapTexture(fProgress, pObj0, 512, 512, globalrandom); //renderdevice->GetWorldSystemManager()->updateTerrainLightmapTexture(fProgress, globalrandom); delete pLight02; pLight02 = NULL; aaaa++; } } if(receiver.IsKeyDown(KEY_F6)) { pObj0->m_fPosition[0] += 0.001f; pObj0->m_fPosition[1] += 0.001f; CStaticMeshInstance* pInst = renderdevice->GetWorldSystemManager()->getMeshInstanceBySceneID(pObj0->getSceneObjectID()); pInst->setPosition(pObj0->m_fPosition[0], pObj0->m_fPosition[1], pObj0->m_fPosition[2]); renderdevice->GetWorldSystemManager()->flushSceneObject(pObj0, 1, false); renderdevice->GetWorldSystemManager()->initializeQuadTree(); } if(receiver.IsKeyDown(KEY_F7)) { static int llll = 0; if( llll == 0) { ptestModel->setEnableUpperBodyAnim(false); ptestModel->playAnimCrossFade(0.1f, 105, 131, true, 3.0f); // attack llll++; } } if(receiver.IsKeyDown(KEY_KEY_1)) { static float pp = 0; if( g_iEffectInstanceID == 0xFFFFFFFF ) { g_iEffectInstanceID = renderdevice->GetEffectInstanceManager()->createEffectInstance(String(L"effect\\hammer.mf1")); CEffectInstance* pEffectInst = renderdevice->GetEffectInstanceManager()->getEffectInstanceByID(g_iEffectInstanceID); int32 BoneID = ptestModel->getBoneIDByName("Bip01 Spine1"); Vector3D BonePos = ptestModel->getBoneWorldPositionByID(BoneID); pEffectInst->setPosition( BonePos.x, BonePos.y, BonePos.z ); pEffectInst->playAnim(1.0f, true); pEffectInst->setScale(0.2f); } else { CEffectInstance* pEffectInst = renderdevice->GetEffectInstanceManager()->getEffectInstanceByID(g_iEffectInstanceID); int32 BoneID = ptestModel->getBoneIDByName("Bip01 Spine1"); Vector3D BonePos = ptestModel->getBoneWorldPositionByID(BoneID); pp += 0.005f; pEffectInst->setPosition( BonePos.x + pp, BonePos.y, BonePos.z ); } } // Work out a frame delta time. const double frameDeltaTime = device->getTimer()->GetElapsedTime() / 1000.0; // Time in seconds renderdevice->setRenderDeviceTime(device->getTimer()->getTime(), frameDeltaTime); // Sync with other working Thread renderdevice->GetMTResourceLoader()->syncRenderResource(); if( receiver.bMButtonDown ) { g_pTestCamera.SetPanX( (float(receiver.getXPosition()) - float(LastXPos)) * -0.01f ); g_pTestCamera.SetPanY( (float(receiver.getYPosition()) - float(LastYPos)) * 0.01f ); } else { g_pTestCamera.SetPanX( 0 ); g_pTestCamera.SetPanY( 0 ); } if( receiver.bRButtonDown ) { g_pTestCamera.SetRotationSpeedX((float(receiver.getYPosition()) - float(LastYPos)) * -0.5f); g_pTestCamera.SetRotationSpeedY((float(receiver.getXPosition()) - float(LastXPos)) * 0.5f); } else { g_pTestCamera.SetRotationSpeedX(0); g_pTestCamera.SetRotationSpeedY(0); } LastXPos = receiver.getXPosition(); LastYPos = receiver.getYPosition(); if( receiver.IsKeyDown(KEY_KEY_W) ) { g_pTestCamera.SetZoom(0.2f); } else if( receiver.IsKeyDown(KEY_KEY_S) ) { g_pTestCamera.SetZoom(-0.2f); } else if( receiver.IsKeyDown(KEY_KEY_A) ) { g_pTestCamera.SetPanX(-0.2f); } else if( receiver.IsKeyDown(KEY_KEY_D) ) { g_pTestCamera.SetPanX(0.2f); } else if( receiver.IsKeyDown(KEY_KEY_Z) ) { Vector4D CameraPos = g_pTestCamera.GetPos(); g_pTestCamera.SetPos(CameraPos.x, 3.0f+renderdevice->GetWorldSystemManager()->getTerrainHeight(CameraPos.x,CameraPos.z), CameraPos.z); } g_pTestCamera.Update( (float)frameDeltaTime ); // DeltaTime in seconds g_pTestCamera.SetZoom(0); // update Camera position renderdevice->setViewMatrix3D( g_pTestCamera.GetRight(), g_pTestCamera.GetUp(), g_pTestCamera.GetDir(), g_pTestCamera.GetPos() ); if( receiver.IsKeyDown(KEY_LEFT) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fInscatteringMultiplier -= 0.01f; } if( receiver.IsKeyDown(KEY_RIGHT) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fInscatteringMultiplier += 0.01f; } if( receiver.IsKeyDown(KEY_PRIOR) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fBetaMieMultiplier -= 0.00001f; } if( receiver.IsKeyDown(KEY_NEXT) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fBetaMieMultiplier += 0.00001f; } if( receiver.IsKeyDown(KEY_INSERT) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fBetaRayMultiplier -= 0.2f; } if( receiver.IsKeyDown(KEY_DELETE) ) { CSGPSkyDome* pSkyDome = const_cast<CSGPSkyDome*>(renderdevice->GetWorldSystemManager()->getSkydome()); pSkyDome->GetScatter().m_fBetaRayMultiplier += 0.2f; } renderdevice->GetWorldSystemManager()->updateWorld( (float)frameDeltaTime ); ptestModel->update( (float)frameDeltaTime ); renderdevice->GetEffectInstanceManager()->updateAllEffectInstance( (float)frameDeltaTime ); averageMS += (frameDeltaTime*1000.0 - averageMS) * 0.1; averageFPS = 1000.0 / averageMS; if(receiver.IsKeyDown(KEY_ESCAPE)) { device->closeDevice(); } // Set render to other frame buffer renderdevice->setRenderToFrameBuffer(); renderdevice->setClearColor(0.2f, 0.2f, 0.2f, 1.0f); renderdevice->beginScene(true, true, false); renderdevice->GetWorldSystemManager()->renderWorld(); ptestModel->render(); renderdevice->GetEffectInstanceManager()->renderAllEffectInstance(); renderdevice->GetVertexCacheManager()->RenderSphere( Vector3D(45.0f, 38.0f, 24.0f), 30.0f, Colour(0,255,0) ); renderdevice->GetVertexCacheManager()->RenderDetailSphere( Vector3D(45.0f, 38.0f, 24.0f), 0.3f, 5, 5, Colour(0,255,0) ); renderdevice->FlushRenderBatch(); //renderdevice->GetVertexCacheManager()->RenderLines( (16*8+1)*2*2, GuidVertex, false ); //renderdevice->FlushEditorLinesRenderBatch(false); // reset back to default back buffer // NOTE: After this function, Scene Depth will not be valid!!! renderdevice->renderBackToMainBuffer(); // Below render context will not use depth, For example, no-depth lines, post process and 2D text etc. // Render Coordinate Axis RenderCoordinateAxis(renderdevice, AxisVertex); renderdevice->FlushEditorLinesRenderBatch(true); { // screen coordinate system is Top-left (0,0) Bottom-Right(width, height) renderdevice->BeginRenderText(); // Render Coordinate Lables RenderLableXYZ( renderdevice, AxisVertex[1].x, AxisVertex[1].y, AxisVertex[1].z, AxisVertex[3].x, AxisVertex[3].y, AxisVertex[3].z, AxisVertex[5].x, AxisVertex[5].y, AxisVertex[5].z ); renderdevice->DrawTextInPos( 10, 10, SGPFDL_SHADOW, 16, 200, 200, 200, L"äÖȾ֡ÊýFPS = %f ", averageFPS ); renderdevice->DrawTextInPos( 10, 30, SGPFDL_DEFAULT, 16, 200, 200, 200, L"Very detailed Chunk Num = %d ", static_cast<COpenGLRenderDevice*>(renderdevice)->getOpenGLTerrainRenderer()->getVeryDetailedChunkNumber() ); renderdevice->DrawTextInPos( 10, 50, SGPFDL_DEFAULT, 16, 200, 200, 200, L"LOD0 Chunk Num = %d ", static_cast<COpenGLRenderDevice*>(renderdevice)->getOpenGLTerrainRenderer()->getLOD0ChunkNumber() ); renderdevice->DrawTextInPos( 10, 70, SGPFDL_DEFAULT, 16, 200, 200, 200, L"LOD1 Chunk Num = %d ", static_cast<COpenGLRenderDevice*>(renderdevice)->getOpenGLTerrainRenderer()->getLOD1ChunkNumber() ); renderdevice->DrawTextInPos( 10, 90, SGPFDL_DEFAULT, 16, 200, 200, 200, L"Blend LOD Chunk Num = %d ", static_cast<COpenGLRenderDevice*>(renderdevice)->getOpenGLTerrainRenderer()->getLODBlendChunkNumber() ); renderdevice->EndRenderText(); } renderdevice->endScene(); } renderdevice->deleteRenderToFrameBuffer(); ptestModel->destroyModel(); delete ptestModel; ptestModel = NULL; #if 1 delete pObj0; pObj0 = NULL; #endif renderdevice->GetWorldSystemManager()->shutdownWorld(); renderdevice->GetEffectInstanceManager()->clearAllEffectInstance(); #if 1 renderdevice->GetWorldSystemManager()->getWorldMap()->Release(); delete pWorldMap; pWorldMap = NULL; #endif if( testDDSID7 != 0 ) renderdevice->GetTextureManager()->unRegisterTextureByID(testDDSID7); delete device; device = NULL; Logger::setCurrentLogger(nullptr); return 0; }
int main(int argc, char **argv) { // Help? if (argv[1] && argv[1][0] == '-') die(helpmsg); putenv((char *) "vblank_mode=0"); // No vsync for us, thanks. MyEventReceiver *r = new MyEventReceiver(); IrrlichtDevice *dev = createDevice(EDT_OPENGL, core::dimension2d<u32>(1024,768), 32, false, false, false, r); if (!dev) die("Can't initialize Irrlicht"); IVideoDriver *drv = dev->getVideoDriver(); ISceneManager *smgr = dev->getSceneManager(); IGPUProgrammingServices *gpu = drv->getGPUProgrammingServices(); ICameraSceneNode *cam = NULL; ITexture *pic = NULL; IMeshSceneNode *ball = NULL; bool showpic = false; IReadFile *areamap = createMemoryReadFile(AreaMap33, sizeof(AreaMap33), "AreaMap33", false); if (!areamap) die("Failed to load areamap"); ITexture *areamaptex = drv->getTexture(areamap); areamap->drop(); // If there's an argument, assume it is a pic to load; otherwise, draw a sphere if (argv[1] && access(argv[1], R_OK) == 0) { showpic = true; pic = drv->getTexture(argv[1]); if (!pic) die("Can't load image"); cam = smgr->addCameraSceneNode(); } else { cam = smgr->addCameraSceneNodeMaya(); cam->setTarget(vector3df(0, 0, 0)); ball = smgr->addSphereSceneNode(40, 8); int ballshader = gpu->addHighLevelShaderMaterial(rnd,0,EVST_VS_1_1,0); ball->setMaterialType((E_MATERIAL_TYPE) ballshader); ISceneNodeAnimator *cool = smgr->createRotationAnimator(vector3df(-0.1, 0.1, -0.1)); ball->addAnimator(cool); cool->drop(); } // Set up static defines, RTTs, quads dimension2d<u32> screensize = drv->getScreenSize(); char defines[128]; snprintf(defines, 128, "#define PIXEL_SIZE vec2(1.0f / %u.0, 1.0f / %u.0)\n" "#define MAX_SEARCH_STEPS 8.0\n#define MAX_DISTANCE 33.0\n", screensize.Width, screensize.Height); ITexture *rt1 = drv->addRenderTargetTexture(screensize, "rt1", ECF_A8R8G8B8); ITexture *rt2 = drv->addRenderTargetTexture(screensize, "rt2", ECF_A8R8G8B8); ITexture *rt3 = drv->addRenderTargetTexture(screensize, "rt3", ECF_A8R8G8B8); if (!rt1 || !rt2 || !rt3) die("No RTT"); ScreenQuad *def = new ScreenQuad(drv); ScreenQuad *sq = new ScreenQuad(drv); ScreenQuad *sq2 = new ScreenQuad(drv); ScreenQuad *sq3 = new ScreenQuad(drv); ScreenQuad *norm = new ScreenQuad(drv); if (showpic) def->SetTexture(pic); sq->SetTexture(rt1); sq->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false); norm->SetTexture(rt1); norm->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false); sq2->SetTexture(rt2); sq2->SetTexture(rt2, 1); sq2->SetTexture(areamaptex, 2); sq2->GetMaterial().TextureLayer[2].BilinearFilter = false; sq3->SetTexture(rt3); sq3->GetMaterial().setFlag(EMF_BILINEAR_FILTER, false); sq3->SetTexture(rt1,1); state_t state = MLAA_OFF; stringc tmp1, tmp2; tmp1 = defines; tmp1 += offsetvs; tmp2 = defines; tmp2 += color1fs; // Load shaders int edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str()); sq->SetMaterialType((E_MATERIAL_TYPE) edge); tmp2 = defines; tmp2 += blend2fs; blendcb *bcb = new blendcb(); edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str(),0,EPST_PS_1_1,bcb); sq2->SetMaterialType((E_MATERIAL_TYPE) edge); tmp2 = defines; tmp2 += neigh3fs; neighcb *ncb = new neighcb(); edge = gpu->addHighLevelShaderMaterial(tmp1.c_str(),0,EVST_VS_1_1,tmp2.c_str(),0,EPST_PS_1_1,ncb); sq3->SetMaterialType((E_MATERIAL_TYPE) edge); // Record start time int lastfps = -1, minfps = 10000; unsigned long long total_frames = 0, fxtimer = 0, tmplong, onframes = 0; struct timeval starttime, tick1, tick2; float glsltime = 0; gettimeofday(&starttime, NULL); wchar_t cap[20]; glEnable(GL_STENCIL_TEST); unsigned char firstrun = 1; // To avoid the glsl compiler in the timing // Main loop while (dev->run()) { gettimeofday(&tick1, NULL); drv->beginScene(); switch (state) { case MLAA_OFF: if (showpic) def->Render(false); else smgr->drawAll(); break; case MLAA_ON: if (showpic) def->Render(rt1); else { drv->setRenderTarget(rt1); smgr->drawAll(); } glClear(GL_STENCIL_BUFFER_BIT); glStencilFunc(GL_ALWAYS, 1, ~0); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); sq->Render(rt2); glStencilFunc(GL_EQUAL, 1, ~0); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); sq2->Render(rt3); drv->setRenderTarget(rt1, false, false); // Overlay the smoothed edges on the initial image sq3->Render(false); // Blit the final image to the framebuffer glStencilFunc(GL_ALWAYS, 1, ~0); norm->Render(); break; } drv->endScene(); if (state == MLAA_ON) { gettimeofday(&tick2, NULL); if (!firstrun) { tmplong = (tick2.tv_sec - tick1.tv_sec) * 10000; tmplong += (tick2.tv_usec - tick1.tv_usec) / 100; fxtimer += tmplong; onframes++; } else { firstrun = 0; glsltime = tick2.tv_sec - tick1.tv_sec; glsltime += (tick2.tv_usec - tick1.tv_usec) / 1000000.0; } } int fps = drv->getFPS(); if (minfps > fps) minfps = fps; if (lastfps != fps) { swprintf(cap, 20, L"%d fps, MLAA %s", fps, state == MLAA_ON ? "on" : "off"); dev->setWindowCaption(cap); lastfps = fps; } if (r->IsKeyDown(KEY_KEY_M)) { if (state == MLAA_ON) state = MLAA_OFF; else state = MLAA_ON; lastfps++; } usleep(1); // 16? total_frames++; } dev->drop(); delete ncb; delete bcb; delete def; delete sq; delete sq2; delete sq3; delete norm; delete r; struct timeval endtime; gettimeofday(&endtime, NULL); float sec = endtime.tv_sec - starttime.tv_sec; sec += ((float) endtime.tv_usec - starttime.tv_usec) / 1000000; printf("\nRan %.3fs, ", sec); sec -= glsltime; printf("average fps %.2f, min %d\n", (float) total_frames/sec, minfps); if (onframes) { printf("\nAverage on fps %.2f, average off fps %.2f\n\n", (float) onframes/(fxtimer/10000.0), (float) (total_frames - onframes)/(sec - (fxtimer/10000.0))); // printf("MLAA took on average %.1fms\n", (float) (fxtimer / onframes) / 10.0); } return 0; }
int main() { MyEventReceiver receiver; IrrlichtDevice *device = createDevice( video::EDT_OPENGL, dimension2d<u32>(1280, 800), 16, false, false, false, &receiver); if (!device) return 1; IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); IGUIEnvironment* guienv = device->getGUIEnvironment(); scene::ISceneNode* o = smgr->addSphereSceneNode(20); //o->setMaterialFlag(video::EMF_LIGHTING, false); o->setPosition(core::vector3df(0,0,0)); SMaterial &m = o->getMaterial(0); m.EmissiveColor = SColor(255, 255, 0, 0); vector3df sssPos(0, 60, 0); scene::ISceneNode* sss = smgr->addCubeSceneNode(30); sss->setMaterialFlag(video::EMF_LIGHTING, true); //sss->setMaterialTexture(0, driver->getTexture("wall.bmp")); sss->setPosition(sssPos); SMaterial &sssm = sss->getMaterial(0); sssm.EmissiveColor = SColor(100, 255, 255, 255); scene::ISceneNode* hp = smgr->addSphereSceneNode(10); SMaterial &hpm = hp->getMaterial(0); hpm.EmissiveColor = SColor(255, 0, 0, 255); scene::ISceneNode* hd = smgr->addSphereSceneNode(10); SMaterial &hdm = hd->getMaterial(0); hdm.EmissiveColor = SColor(255, 0, 0, 100); scene::ISceneNode* node[10]; for (int i = 0; i < 10; ++i) { node[i] = smgr->addSphereSceneNode(5); //node[i]->setMaterialFlag(video::EMF_LIGHTING, false); node[i]->setVisible(false); SMaterial &m = node[i]->getMaterial(0); m.EmissiveColor = SColor(255, 255, 0, 0); } scene::ICameraSceneNode* cam = smgr->addCameraSceneNodeFPS(); vector3df camPos(0,0,200); vector3df camshift(0,0,0); cam->setPosition(camPos); cam->setTarget(core::vector3df(0,0,0)); u32 then = device->getTimer()->getTime(); const f32 MOVEMENT_SPEED = 50.f; irr::video::S3DVertex m_cPlaneVertices[4]; irr::u16 m_iPlaneIndices[6]; m_cPlaneVertices[0] = irr::video::S3DVertex(-100.0f, -100.0f, -100.0f,1,1,0, irr::video::SColor(255,255,255,255), 0.0f, 0.0f); m_cPlaneVertices[1] = irr::video::S3DVertex(-100.0f, 100.0f, -100.0f,1,1,0, irr::video::SColor(255,255,255,255), 0.0f, 1.0f); m_cPlaneVertices[2] = irr::video::S3DVertex( 100.0f, 100.0f, -100.0f,1,1,0, irr::video::SColor(255,255,255,255), 1.0f, 1.0f); m_cPlaneVertices[3] = irr::video::S3DVertex( 100.0f, -100.0f, -100.0f,1,1,0, irr::video::SColor(255,255,255,255), 1.0f, 0.0f); m_iPlaneIndices[0] = 0; m_iPlaneIndices[1] = 2; m_iPlaneIndices[2] = 1; m_iPlaneIndices[3] = 0; m_iPlaneIndices[4] = 3; m_iPlaneIndices[5] = 2; SMaterial m_cRenderMaterial; m_cRenderMaterial.Wireframe = false; m_cRenderMaterial.Lighting = false; m_cRenderMaterial.TextureLayer[0].TextureWrapU = irr::video::ETC_CLAMP; m_cRenderMaterial.TextureLayer[0].TextureWrapV = irr::video::ETC_CLAMP; ITexture *m_pRenderTexture = 0; CvCapture *capture; IplImage *frame; char AviFileName[]="Accel World.mp4"; capture = cvCaptureFromAVI(AviFileName); if (driver->queryFeature(irr::video::EVDF_RENDER_TO_TARGET)) { m_pRenderTexture = driver->addRenderTargetTexture(irr::core::dimension2d<irr::u32>((irr::u32)(720), (irr::u32)(480))); m_cRenderMaterial.setTexture(0, m_pRenderTexture); } // m_pRenderTexture = driver->getTexture("wall.bmp"); // m_cRenderMaterial.setTexture(0, m_pRenderTexture); while(device->run()) { const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; // Time in seconds then = now; if(receiver.IsKeyDown(irr::KEY_KEY_W)) camshift.Z -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_S)) camshift.Z += MOVEMENT_SPEED * frameDeltaTime; if(receiver.IsKeyDown(irr::KEY_KEY_A)) camshift.X -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_KEY_D)) camshift.X += MOVEMENT_SPEED * frameDeltaTime; if(receiver.IsKeyDown(irr::KEY_KEY_X)) camshift.Y -= MOVEMENT_SPEED * frameDeltaTime; else if(receiver.IsKeyDown(irr::KEY_SPACE)) camshift.Y += MOVEMENT_SPEED * frameDeltaTime; cam->setPosition(camPos + camshift); driver->beginScene(true, true, SColor(255,0,0,0)); driver->setRenderTarget(m_pRenderTexture, true, true, irr::video::SColor(0,0,0,0)); if(cvGrabFrame(capture)) { frame=cvRetrieveFrame(capture); void* pBits = m_pRenderTexture->lock(); u32 Pitch = m_pRenderTexture->getPitch(); int wmin= Pitch; // for(int h=0; h< 100; h++) // memcpy((char*)pBits+((h)*wmin),(char*)frame->imageDataOrigin + h * wmin, wmin); char* tmp = new char[frame->imageSize + 720 * 480]; for (int i = 0; i < 480; ++i) { for (int j = 0; j < 720; ++j) { tmp[(i * 720 + j) * 4] = frame->imageDataOrigin[(i * 720 + j) * 3]; tmp[(i * 720 + j) * 4 + 1] = frame->imageDataOrigin[(i * 720 + j) * 3 + 1]; tmp[(i * 720 + j) * 4 + 2] = frame->imageDataOrigin[(i * 720 + j) * 3 + 2]; tmp[(i * 720 + j) * 4 + 3] = 255; } } memcpy(pBits,tmp, frame->imageSize + 720 * 480); delete []tmp; m_pRenderTexture->unlock(); } driver->setRenderTarget(0, false, false, irr::video::SColor(0,100,100,100)); //driver->setTransform(video::ETS_VIEW, core::matrix4()); driver->setTransform(video::ETS_WORLD, core::matrix4()); //driver->setTransform(video::ETS_PROJECTION, core::matrix4()); driver->setMaterial(m_cRenderMaterial); driver->drawIndexedTriangleList(m_cPlaneVertices, 4, m_iPlaneIndices, 2); smgr->drawAll(); driver->endScene(); } //controller.removeListener(listener); device->drop(); return 0; }
int main(int argc, const char** argv) { /* - deviceType: Type of the device. This can currently be the Null-device, one of the two software renderers, D3D8, D3D9, or OpenGL. In this example we use EDT_SOFTWARE, but to try out, you might want to change it to EDT_BURNINGSVIDEO, EDT_NULL, EDT_DIRECT3D8, EDT_DIRECT3D9, or EDT_OPENGL. */ MyEventReceiver receiver; ISoundEngine* music = createIrrKlangDevice(); IrrlichtDevice *device = createDevice( EDT_DIRECT3D9, dimension2d<u32>(640, 480), 32, false, false, false, &receiver); music->play2D("../media/MUSIC/Dark Impetus.mp3",true,false,true); IVideoDriver* driver = device->getVideoDriver(); ISceneManager* smgr = device->getSceneManager(); IGUIEnvironment* guienv = device->getGUIEnvironment(); ICameraSceneNode *camera = smgr->addCameraSceneNode(); IGUIFont* font = device->getGUIEnvironment()->getFont("../media/fonthaettenschweiler.bmp"); camera->setFarValue(900); IAnimatedMesh* map = smgr->getMesh(DC_01); IAnimatedMeshSceneNode* mapnode = smgr->addAnimatedMeshSceneNode(map); mapnode->setMaterialFlag(EMF_LIGHTING,false); IAnimatedMesh* player1 = smgr->getMesh(SORA); IAnimatedMeshSceneNode* p1node = smgr->addAnimatedMeshSceneNode(player1); p1node->setMaterialFlag(EMF_LIGHTING, false); p1node->setScale(SORA_VECTOR3D); IAnimatedMesh* player2 = smgr->getMesh(AQUA); IAnimatedMeshSceneNode* p2node = smgr->addAnimatedMeshSceneNode(player2); p2node->setMaterialFlag(EMF_LIGHTING, false); p2node->setScale(NORMAL_VECTOR3D); vector3df Position = p1node->getPosition(); vector3df P2Pos = p2node->getPosition(); vector3df PosCam = p1node->getPosition(); vector3df Rotate = p1node->getPosition(); int CurrentHP = 300; int MaxHP = 400; int HeartP = 10; bool LockOn = false; bool LockCheck = false; stringw CoorCheck; while(device->run()) { CoorCheck +=L"Your position\nX:"; CoorCheck +=Position.X; CoorCheck +=L"\nY:"; CoorCheck +=Position.Y; CoorCheck +=L"\nZ:"; CoorCheck +=Position.Z; CoorCheck +=L"\n\nTarget Position:"; CoorCheck +=P2Pos.X; if(LockCheck != true){ if(receiver.IsKeyDown(KEY_KEY_J)){LockOn = true; LockCheck = true;}} else{ if(receiver.IsKeyDown(KEY_KEY_J)){LockOn = false;LockCheck = false;}} //3D Rendering. MaximizeKey(receiver,device); GetCaption(driver,device); driver->beginScene(true, true, SColor(255,100,101,140)); p1node->setPosition(Position); camera->setPosition(vector3df(PosCam.X,PosCam.Y+2,PosCam.Z+3)); if(LockOn != false){camera->setTarget(P2Pos);} else{camera->setTarget(Position);} smgr->drawAll(); //2D Rendering. if(CurrentHP<=0){font->draw(L"You are dead!!!",rect<s32>(120,140,250,210),SColor(255,255,255,255));} else{if(receiver.IsKeyDown(KEY_KEY_L)){--CurrentHP;}} if(CurrentHP>=MaxHP){}else{if(receiver.IsKeyDown(KEY_KEY_K)){++CurrentHP;}} if(receiver.IsKeyDown(KEY_KEY_N)){++MaxHP;} if(receiver.IsKeyDown(KEY_KEY_M) && CurrentHP<MaxHP){--MaxHP;} if(HeartP>=86){}else{ if(receiver.IsKeyDown(KEY_KEY_F)){++HeartP;}} font->draw (L"Press O for full screen.\nPress Up-Down-Left-right to move.\nPress L to hurt the character.\nPress K to heal the character.\nPress N to increase Max HP.\nPress M to decrease Max HP.\nPress F to fill the Heart gauge.",rect<s32>(20,40,150,110),SColor(255,0,0,0)); font->draw(CoorCheck,rect<s32>(20,140,150,110),SColor(255,0,0,0)); //Button detection. if(receiver.IsKeyDown(KEY_UP)){ Position.Z -= 0.1f; PosCam.Z = Position.Z; p1node->setRotation(vector3df(Rotate.X,Rotate.Y = 0,Rotate.Z)); p1node->setPosition(Position);} if(receiver.IsKeyDown(KEY_DOWN)){ Position.Z += 0.1f; PosCam.Z = Position.Z; p1node->setRotation(vector3df(Rotate.X,Rotate.Y -180,Rotate.Z)); p1node->setPosition(Position);} if(receiver.IsKeyDown(KEY_LEFT)){ Position.X += 0.1f; PosCam.X = Position.X; p1node->setRotation(vector3df(Rotate.X,Rotate.Y -90,Rotate.Z)); p1node->setPosition(Position);} if(receiver.IsKeyDown(KEY_RIGHT)){ Position.X -= 0.1f; PosCam.X = Position.X; p1node->setRotation(vector3df(Rotate.X,Rotate.Y +90,Rotate.Z)); p1node->setPosition(Position);} HUD_Display(device,driver,receiver,font,CurrentHP,MaxHP,HeartP); guienv->drawAll(); CoorCheck = L""; driver->endScene(); } music->drop(); device->drop(); return 0; }
int main() { // Initialization of Device, Video Driver and Scene Manager video::E_DRIVER_TYPE driverType=video::EDT_OPENGL; MyEventReceiver receiver; IrrlichtDevice* device = createDevice(driverType, core::dimension2d<u32>(960, 720), 16, false, false, false, &receiver); if (device == 0) return 1; video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); // Building the scene. // open level file ifstream infile; infile.open("enigma3d.app/Contents/Resources/field.lvl"); if (infile.fail()) error("Could not open level file\n"); // checking the file starts with "Enigma-3D" string line; infile >> line; if (line!="Enigma-3D") error("Illegal Level file: "+line+"\n"); // Playground is a two-dimensional array of pointers to fields: Field * playground[dimx][dimy]; // now reading from level file one number for each field // and creating a wall or floor of the appropriate sub-class for(int j=0; j<dimy; j++){ for(int i=0; i<dimx; i++){ // determine filed type int fieldtype; infile >> fieldtype; playground[i][j]=makefield(fieldtype,smgr,driver,i,j,playground); } } // the level file may contain additional requests for introducing // some fields to each other: while ((infile >> line), line!="end"){ // must have the form "introduce x1 y1 to x1 y2" if (line!="introduce") error("Level File: mistake in introduce lines"); int x1,x2,y1,y2; infile >> x1 >> y1 >> line >> x2 >> y2; if ( (x1 < 0) || x1>=dimx || (x2 < 0) || x2>=dimx || (y1 < 0) || y1>=dimy || (y2 < 0) || y2>=dimy || line !="to" ) error("Level File: mistake in introduce lines"); // call the introduceTo method of field x1 y1: playground[x1][y1]->introduceTo(*(playground[x2][y2])); } infile.close(); Sphere *sphere=new Sphere(smgr,driver); scene::ICameraSceneNode* camera=smgr->addCameraSceneNode(NULL,core::vector3df(offsety+50.f,100.f,offsetx), core::vector3df(offsety,0.f,offsetx)); // to change the camera position use: // camera->setPosition(core::vector3df(...)); // see docmentation of ICameraSceneNode for more (like setting target, rotation, aspect) // hide the mouse cursor device->getCursorControl()->setVisible(false); // for time measurement: get an initial time reference u32 then = device->getTimer()->getTime(); // for mouse-move measurement: get an initial mouse position core::position2di RefPosition=receiver.Position; // compute the field number where the sphere is and notify that field int fieldx=getFieldx(sphere->getPosition()); int fieldy=getFieldy(sphere->getPosition()); playground[fieldx][fieldy]->sphereEnter(*sphere); // Running function introduceSphere for every wall/floor ONCE for(int j=0; j<dimy; j++) for(int i=0; i<dimx; i++) playground[i][j]-> introduceSphere(*sphere); while(device->run()) { if(receiver.IsKeyDown(irr::KEY_KEY_Q)) exit(0); // quit game on key Q // Adapt speed by the difference in mouse position core::position2di mousemove; mousemove.X=(receiver.Position.X-RefPosition.X); mousemove.Y=(receiver.Position.Y-RefPosition.Y); // eliminating too rapid movements of the mouse if (fabs((float)mousemove.X)>10) mousemove.X=0; if (fabs((float)mousemove.Y)>10) mousemove.Y = 0; // remember current mouse position RefPosition=receiver.Position; // Measure the time that has passed since last round const u32 now = device->getTimer()->getTime(); const f32 frameDeltaTime = (f32)(now - then) / 1000.f; then = now; /* The field that the sphere is currently on is now in control to decide how the sphere moves within the time frameDeltaTime. This will typically NOT include collision detection with surrounding walls---that will be done later. */ playground[fieldx][fieldy]->handleSphere(*sphere,mousemove,frameDeltaTime); // tell also all other fields that time has passed: for(int j=0; j<dimy; j++) for(int i=0; i<dimx; i++) if (i!=fieldx || j!=fieldy) playground[i][j]->timeProgress(frameDeltaTime); /* Now we turn to collision detection: - compute what field the sphere is on now - compute overlap with adjacent fields - notify all fields where overlap is non-zero */ core::vector3df spherePosition = sphere->getPosition(); int new_fieldx=getFieldx(spherePosition); int new_fieldy=getFieldy(spherePosition); f32 xoE=getOverlapx(spherePosition,new_fieldx+1); f32 xoW=getOverlapx(spherePosition,new_fieldx-1); f32 yoN=getOverlapy(spherePosition,new_fieldy+1); f32 yoS=getOverlapy(spherePosition,new_fieldy-1); // E = east, W = west... if (xoE) playground[new_fieldx+1][new_fieldy]->sphereOverlap(*sphere,xoE,0.f); if (xoW) playground[new_fieldx-1][new_fieldy]->sphereOverlap(*sphere,xoW,0.f); if (yoN) playground[new_fieldx][new_fieldy+1]->sphereOverlap(*sphere,0.f,yoN); if (yoS) playground[new_fieldx][new_fieldy-1]->sphereOverlap(*sphere,0.f,yoS); /* if (spherePosition==sphere->getPosition()){ // if there was no collision with E,W,N, or S, check for overlaps with diagonal fields if (xoE && yoN) playground[new_fieldx+1][new_fieldy+1]->sphereOverlap(*sphere,xoE/4,yoN/4); if (xoE && yoS) playground[new_fieldx+1][new_fieldy-1]->sphereOverlap(*sphere,xoE/4,yoS/4); if (xoW && yoN) playground[new_fieldx-1][new_fieldy+1]->sphereOverlap(*sphere,xoW/4,yoN/4); if (xoW && yoS) playground[new_fieldx-1][new_fieldy-1]->sphereOverlap(*sphere,xoW/4,yoS/4); } */ // If all the movements and collisions have changed the field the sphere is on, notify both // the field it leaves and the field it enters: if (new_fieldx!=fieldx || new_fieldy!=fieldy){ playground[fieldx][fieldy]->sphereExit(*sphere); fieldx=new_fieldx; fieldy=new_fieldy; playground[fieldx][fieldy]->sphereEnter(*sphere); } // Draw the picture anew and go to a next round driver->beginScene(true, true, video::SColor(255,113,113,133)); smgr->drawAll(); driver->endScene(); } device->drop(); return 0; }
int main() { scene::IMesh* testMesh; scene::IMeshSceneNode* testNode; scene::ITriangleSelector* selector; core::matrix4 matrix = core::matrix4(); scene::ICameraSceneNode* camera; core::vector3df cameraOffset = core::vector3df( 0.0f, 2.0f, 0.0f ); MyEventReceiver receiver; IrrlichtDevice* device = createDevice( video::EDT_OPENGL, core::dimension2du( 800, 600 ), 32, false, true, false, &receiver ); if ( device == 0 ) exit( 1 ); video::IVideoDriver* driver = device->getVideoDriver(); scene::ISceneManager* smgr = device->getSceneManager(); scene::IMeshManipulator* meshManipulator = smgr->getMeshManipulator(); scene::ISceneCollisionManager* colliman = smgr->getSceneCollisionManager(); // load, scale and place mesh driver->setTransform( video::ETS_WORLD, core::matrix4() ); testMesh = meshManipulator->createMeshCopy( smgr->getMesh( "just_a_mesh.3ds" ) ); matrix.setScale( core::vector3df( 200.0f + 0.001f, 200.0f, 200.0f + 0.001f ) ); matrix.setTranslation( core::vector3df( 99 * 400.0f + 200.0f, 0.0f, 99 * 400.0f + 200.0f ) ); meshManipulator->transform( testMesh, matrix ); meshManipulator->recalculateNormals( testMesh, true ); // setHardwareMappingHint for ( register u32 i = 0; i < testMesh->getMeshBufferCount(); ++i ) { scene::IMeshBuffer* buffer = testMesh->getMeshBuffer( i ); buffer->setHardwareMappingHint( scene::EHM_STATIC ); buffer->setDirty(); buffer->recalculateBoundingBox(); } // create node from mesh testNode = smgr->addMeshSceneNode( testMesh ); testMesh->drop(); // set material testNode->setMaterialTexture( 0, driver->getTexture( "just_a_texture.jpg" ) ); testNode->setMaterialType( video::EMT_SOLID ); testNode->setMaterialFlag( video::EMF_LIGHTING, false ); testNode->setVisible( true ); // add node to collision detection selector = smgr->createOctreeTriangleSelector( testNode->getMesh(), testNode, 900 ); testNode->setTriangleSelector( selector ); selector->drop(); // add a camera camera = smgr->addCameraSceneNodeFPS( 0, 360.0f, 0.01f ); camera->setPosition( core::vector3df(39936.0f, 0.0f, 39755.0f) ); camera->setTarget( camera->getPosition() + core::vector3df( 1.0f, 0.0f, 1.0f ) ); camera->updateAbsolutePosition(); camera->setFarValue( 300.0f ); camera->setNearValue( 0.1f ); camera->setFOV( 1.25f ); camera->setAspectRatio( 4.0f / 3.0f ); camera->setInputReceiverEnabled( true ); smgr->setActiveCamera( camera ); device->getCursorControl()->setVisible( false ); while( device->run() ) { if ( !device->isWindowActive() ) device->yield(); if ( receiver.IsKeyDown( irr::KEY_ESCAPE ) ) device->closeDevice(); core::vector3df pos = camera->getPosition() - cameraOffset; pos.Y = getHeight( pos.X, pos.Z, colliman, testNode ); if ( pos.Y > 999.0f ) printf( "gap at x=%f, z=%f!\n", pos.X, pos.Z ); camera->setPosition( pos + cameraOffset ); driver->beginScene( true, true ); smgr->drawAll(); driver->endScene(); } device->drop(); return 0; }