Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/FICN/src/orxonox/orxonox.cc @ 599

Last change on this file since 599 was 599, checked in by scheusso, 16 years ago

ip address with —ip=address

File size: 14.9 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *
4 *
5 *   License notice:
6 *
7 *   This program is free software; you can redistribute it and/or
8 *   modify it under the terms of the GNU General Public License
9 *   as published by the Free Software Foundation; either version 2
10 *   of the License, or (at your option) any later version.
11 *
12 *   This program is distributed in the hope that it will be useful,
13 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *   GNU General Public License for more details.
16 *
17 *   You should have received a copy of the GNU General Public License
18 *   along with this program; if not, write to the Free Software
19 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 *
21 *   Author:
22 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
23 *   Co-authors:
24 *      ...
25 *
26 */
27
28/**
29 @file  orxonox.cc
30 @brief Orxonox Main Class
31 */
32
33#include "orxonox.h"
34#include "graphicsEngine.h"
35
36//#include <Ogre.h>
37// 40% speed up: (instead of Ogre.h)
38#include <OgreSceneNode.h>
39#include <OgreSceneManager.h>
40#include <OgreRoot.h>
41#include <OgreFrameListener.h>
42#include <OgreConfigFile.h>
43#include <OgreTextureManager.h>
44#include <OgreEntity.h>
45#include <OgreRenderWindow.h>
46
47#include <OIS/OIS.h>
48//#include <CEGUI/CEGUI.h>
49//#include <OgreCEGUIRenderer.h>
50
51#include <string>
52#include <iostream>
53
54#include "objects/Tickable.h"
55#include "objects/Timer.h"
56#include "core/ArgReader.h"
57#include "core/Factory.h"
58#include "core/Debug.h"
59
60#include "../loader/LevelLoader.h"
61#include "../audio/AudioManager.h"
62
63#include "spaceship_steering.h"
64
65#include "particle/ParticleInterface.h"
66
67#include "hud/HUD.h"
68
69//network stuff
70#include "../network/Server.h"
71#include "../network/Client.h"
72#include "../network/NetworkFrameListener.h"
73
74#ifdef WIN32
75#include <windows.h>
76#define usleep(x) Sleep((x)/1000)
77#else
78#include <unistd.h>
79#endif
80
81namespace orxonox
82{
83  using namespace Ogre;
84
85   // put this in seperate Class or solve the problem in another fashion
86  class OrxListener : public FrameListener, public OIS::MouseListener
87  {
88    public:
89      OrxListener(OIS::Keyboard *keyboard, OIS::Mouse *mouse, audio::AudioManager*  auMan, SpaceshipSteering* steering)
90      : mKeyboard(keyboard), mMouse(mouse)
91      {
92
93
94
95        speed = 250;
96        loop = 100;
97        rotate = 10;
98        mouseX = 0;
99        mouseY = 0;
100        maxMouseX = 0;
101        minMouseX = 0;
102        moved = false;
103
104        steering_ = steering;
105
106        steering_->brakeRotate(rotate*10);
107        steering_->brakeLoop(loop);
108
109
110        mMouse->setEventCallback(this);
111        auMan_ = auMan;
112      }
113      bool frameStarted(const FrameEvent& evt)
114      {
115
116        auMan_->update();
117
118        mKeyboard->capture();
119        mMouse->capture();
120        if (mKeyboard->isKeyDown(OIS::KC_UP) || mKeyboard->isKeyDown(OIS::KC_W))
121          steering_->moveForward(speed);
122        else
123          steering_->moveForward(0);
124        if(mKeyboard->isKeyDown(OIS::KC_DOWN) || mKeyboard->isKeyDown(OIS::KC_S))
125          steering_->brakeForward(speed);
126        else
127          steering_->brakeForward(speed/10);
128        if (mKeyboard->isKeyDown(OIS::KC_RIGHT) || mKeyboard->isKeyDown(OIS::KC_D))
129          steering_->loopRight(loop);
130        else
131          steering_->loopRight(0);
132        if (mKeyboard->isKeyDown(OIS::KC_LEFT) || mKeyboard->isKeyDown(OIS::KC_A))
133          steering_->loopLeft(loop);
134        else
135          steering_->loopLeft(0);
136
137        if(moved) {
138          if (mouseY<=0)
139            steering_->rotateUp(-mouseY*rotate);
140          if (mouseY>0)
141            steering_->rotateDown(mouseY*rotate);
142          if (mouseX>0)
143            steering_->rotateRight(mouseX*rotate);
144          if (mouseX<=0)
145            steering_->rotateLeft(-mouseX*rotate);
146          mouseY = 0;
147          mouseX = 0;
148          moved = false;
149        }
150        else {
151          steering_->rotateUp(0);
152          steering_->rotateDown(0);
153          steering_->rotateRight(0);
154          steering_->rotateLeft(0);
155        }
156
157                steering_->tick(evt.timeSinceLastFrame);
158
159
160
161//      scenemanager->spacehip->tick(evt.timesincelastframe);
162        //if(mKeyboard->isKeyDown(OIS::KC_ESCAPE))
163          //cout << "maximal MouseX: " << maxMouseX << "\tminMouseX: " << minMouseX << endl;
164        usleep(10);
165        return !mKeyboard->isKeyDown(OIS::KC_ESCAPE);
166      }
167
168      bool mouseMoved(const OIS::MouseEvent &e)
169      {
170        mouseX += e.state.X.rel;
171        mouseY += e.state.Y.rel;
172        if(mouseX>maxMouseX) maxMouseX = mouseX;
173        if(mouseX<minMouseX) minMouseX = mouseX;
174        //cout << "mouseX: " << mouseX << "\tmouseY: " << mouseY << endl;
175        moved = true;
176        return true;
177      }
178
179      bool mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
180      bool mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
181
182    private:
183      float speed;
184      float rotate;
185      float loop;
186      float mouseY;
187      float mouseX;
188      float maxMouseX;
189      float minMouseX;
190      bool moved;
191      OIS::Keyboard *mKeyboard;
192      OIS::Mouse *mMouse;
193      audio::AudioManager*  auMan_;
194      SpaceshipSteering* steering_;
195  };
196  // init static singleton reference of Orxonox
197  Orxonox* Orxonox::singletonRef_ = NULL;
198
199  /**
200   * create a new instance of Orxonox
201   */
202  Orxonox::Orxonox()
203  {
204    ogre_ = new GraphicsEngine();
205    dataPath_ = "";
206  }
207
208  /**
209   * destruct Orxonox
210   */
211  Orxonox::~Orxonox()
212  {
213    // nothing to delete as for now
214  }
215
216  /**
217   * initialization of Orxonox object
218   * @param argc argument counter
219   * @param argv list of arguments
220   * @param path path to config (in home dir or something)
221   */
222  void Orxonox::init(int argc, char **argv, std::string path)
223  {
224    //TODO: find config file (assuming executable directory)
225    //TODO: read config file
226    //TODO: give config file to Ogre
227    std::string mode;
228//     if(argc>=2)
229//       mode = std::string(argv[1]);
230//     else
231//       mode = "";
232    ArgReader ar = ArgReader(argc, argv);
233    ar.checkArgument("mode", mode, false);
234    ar.checkArgument("data", this->dataPath_, false);
235    ar.checkArgument("ip", serverIp_, false);
236    if(ar.errorHandling()) die();
237
238    if(mode == std::string("server"))
239    {
240      serverInit(path);
241      mode_ = SERVER;
242    }
243    else if(mode == std::string("client"))
244    {
245      clientInit(path);
246      mode_ = CLIENT;
247    }
248    else if(mode == std::string("presentation"))
249    {
250      serverInit(path);
251      mode_ = PRESENTATION;
252    }
253    else{
254      standaloneInit(path);
255      mode_ = STANDALONE;
256    }
257  }
258
259  /**
260   * start modules
261   */
262  void Orxonox::start()
263  {
264    //TODO: start modules
265    ogre_->startRender();
266    //TODO: run engine
267    createScene();
268    setupScene();
269    setupInputSystem();
270    if(mode_!=CLIENT){ // remove this in future ---- presentation hack
271    }
272    else
273      std::cout << "client here" << std::endl;
274    createFrameListener();
275    Factory::createClassHierarchy();
276    switch(mode_){
277    case PRESENTATION:
278      server_g->open();
279      break;
280    case CLIENT:
281      client_g->establishConnection();
282      break;
283    case SERVER:
284    case STANDALONE:
285    default:
286      break;
287    }
288    startRenderLoop();
289  }
290
291  /**
292   * @return singleton object
293   */
294  Orxonox* Orxonox::getSingleton()
295  {
296    if (!singletonRef_)
297      singletonRef_ = new Orxonox();
298    return singletonRef_;
299  }
300
301  /**
302   * error kills orxonox
303   */
304  void Orxonox::die(/* some error code */)
305  {
306    //TODO: destroy and destruct everything and print nice error msg
307    delete this;
308  }
309
310  void Orxonox::standaloneInit(std::string path)
311  {
312    ogre_->setConfigPath(path);
313    ogre_->setup();
314    root_ = ogre_->getRoot();
315    if(!ogre_->load()) die(/* unable to load */);
316
317    //defineResources();
318    //setupRenderSystem();
319    //createRenderWindow();
320    //initializeResourceGroups();
321    /*createScene();
322    setupScene();
323    setupInputSystem();
324    createFrameListener();
325    Factory::createClassHierarchy();
326    startRenderLoop();*/
327  }
328
329  void Orxonox::playableServer(std::string path)
330  {
331    ogre_->setConfigPath(path);
332    ogre_->setup();
333    root_ = ogre_->getRoot();
334    defineResources();
335    setupRenderSystem();
336    createRenderWindow();
337    initializeResourceGroups();
338    createScene();
339    setupScene();
340    setupInputSystem();
341    Factory::createClassHierarchy();
342    createFrameListener();
343    try{
344      server_g = new network::Server(); // add port and bindadress
345      server_g->open(); // open server and create listener thread
346      if(ogre_ && ogre_->getRoot())
347        ogre_->getRoot()->addFrameListener(new network::ServerFrameListener()); // adds a framelistener for the server
348      COUT(3) << "Info: network framelistener added" << std::endl;
349    }
350    catch(exception &e)
351    {
352      COUT(1) << "Error: There was a problem initialising the server :(" << std::endl;
353    }
354    startRenderLoop();
355  }
356
357  void Orxonox::standalone(){
358
359
360
361  }
362
363  void Orxonox::serverInit(std::string path)
364  {
365    COUT(2) << "initialising server" << std::endl;
366    ogre_->setConfigPath(path);
367    ogre_->setup();
368    server_g = new network::Server(); // add some settings if wanted
369    if(!ogre_->load()) die(/* unable to load */);
370    // add network framelistener
371    ogre_->getRoot()->addFrameListener(new network::ServerFrameListener());
372  }
373
374  void Orxonox::clientInit(std::string path)
375  {
376    COUT(2) << "initialising client" << std::endl;
377    ogre_->setConfigPath(path);
378    ogre_->setup();
379    if(serverIp_.compare("")==0)
380      client_g = new network::Client();
381    else
382      client_g = new network::Client(serverIp_, 55556);
383    if(!ogre_->load()) die(/* unable to load */);
384    ogre_->getRoot()->addFrameListener(new network::ClientFrameListener());
385  }
386
387  void Orxonox::defineResources()
388  {
389    Ogre::String secName, typeName, archName;
390    Ogre::ConfigFile cf;
391#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
392    cf.load(macBundlePath() + "/Contents/Resources/resources.cfg");
393#else
394    cf.load(dataPath_ + "resources.cfg");
395#endif
396
397    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
398    while (seci.hasMoreElements())
399    {
400      secName = seci.peekNextKey();
401      Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
402      Ogre::ConfigFile::SettingsMultiMap::iterator i;
403      for (i = settings->begin(); i != settings->end(); ++i)
404      {
405        typeName = i->first;
406        archName = i->second;
407#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
408        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( String(macBundlePath() + "/" + archName), typeName, secName);
409#else
410        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName);
411#endif
412      }
413    }
414  }
415
416  void Orxonox::setupRenderSystem()
417  {
418    if (!root_->restoreConfig() && !root_->showConfigDialog())
419      throw Exception(52, "User canceled the config dialog!", "OrxApplication::setupRenderSystem()");
420  }
421
422  void Orxonox::createRenderWindow()
423  {
424    root_->initialise(true, "OrxonoxV2");
425  }
426
427  void Orxonox::initializeResourceGroups()
428  {
429    TextureManager::getSingleton().setDefaultNumMipmaps(5);
430    ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
431  }
432
433  /**
434   *
435   * @param
436   */
437  void Orxonox::createScene(void)
438  {
439        // Init audio
440    auMan_ = new audio::AudioManager();
441
442    // load this file from config
443    loader_ = new loader::LevelLoader("sample.oxw");
444    loader_->loadLevel();
445
446    Overlay* hudOverlay = OverlayManager::getSingleton().getByName("Orxonox/HUD1.2");
447    hud::HUD* orxonoxHud;
448    orxonoxHud = new hud::HUD();
449    orxonoxHud->setEnergyValue(20);
450    orxonoxHud->setEnergyDistr(20,20,60);
451    hudOverlay->show();
452
453
454        /*
455    auMan_->ambientAdd("a1");
456    auMan_->ambientAdd("a2");
457    auMan_->ambientAdd("a3");
458                                //auMan->ambientAdd("ambient1");
459    auMan_->ambientStart();*/
460  }
461
462
463  /**
464   *
465   */
466  void Orxonox::setupScene()
467  {
468    SceneManager *mgr = ogre_->getSceneManager();
469
470
471    SceneNode* node = (SceneNode*)mgr->getRootSceneNode()->getChild("OgreHeadNode");
472//     SceneNode *node = mgr->getRootSceneNode()->createChildSceneNode("OgreHeadNode", Vector3(0,0,0));
473
474
475    steering_ = new SpaceshipSteering(500, 200, 200, 200);
476    steering_->addNode(node);
477
478/*
479    particle::ParticleInterface *e = new particle::ParticleInterface(mgr,"engine","Orxonox/strahl");
480    e->particleSystem_->setParameter("local_space","true");
481    e->setPositionOfEmitter(0, Vector3(0,-10,0));
482    e->setDirection(Vector3(0,0,-1));
483    e->addToSceneNode(node);
484*/
485
486    particle::ParticleInterface *w = new particle::ParticleInterface(mgr,"schuss","Orxonox/schuss");
487    w->particleSystem_->setParameter("local_space","true");
488    w->newEmitter();
489    w->setDirection(Vector3(0,0,1));
490    w->setPositionOfEmitter(0, Vector3(10,10,0));
491    w->setPositionOfEmitter(1, Vector3(-10,10,0));
492    w->addToSceneNode(node);
493
494    particle::ParticleInterface *tt = new particle::ParticleInterface(mgr,"twinthruster","Orxonox/engineglow");
495    tt->particleSystem_->setParameter("local_space","true");
496    tt->newEmitter();
497    tt->setDirection(Vector3(0,0,-1));
498    tt->setPositionOfEmitter(0, Vector3(20,-1,-15));
499    tt->setPositionOfEmitter(1, Vector3(-20,-1,-15));
500    tt->addToSceneNode(node);
501
502  }
503
504
505  void Orxonox::setupInputSystem()
506  {
507    size_t windowHnd = 0;
508    std::ostringstream windowHndStr;
509    OIS::ParamList pl;
510    Ogre::RenderWindow *win = ogre_->getRoot()->getAutoCreatedWindow();
511
512    win->getCustomAttribute("WINDOW", &windowHnd);
513    windowHndStr << windowHnd;
514    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
515    inputManager_ = OIS::InputManager::createInputSystem(pl);
516
517    try
518    {
519      keyboard_ = static_cast<OIS::Keyboard*>(inputManager_->createInputObject(OIS::OISKeyboard, false));
520      mouse_ = static_cast<OIS::Mouse*>(inputManager_->createInputObject(OIS::OISMouse, true));
521    }
522    catch (const OIS::Exception &e)
523    {
524      throw new Ogre::Exception(42, e.eText, "OrxApplication::setupInputSystem");
525    }
526  }
527
528  // we actually want to do this differently...
529  void Orxonox::createFrameListener()
530  {
531    TickFrameListener* TickFL = new TickFrameListener();
532    ogre_->getRoot()->addFrameListener(TickFL);
533
534    TimerFrameListener* TimerFL = new TimerFrameListener();
535    ogre_->getRoot()->addFrameListener(TimerFL);
536
537    //if(mode_!=CLIENT) // just a hack ------- remove this in future
538      frameListener_ = new OrxListener(keyboard_, mouse_, auMan_, steering_);
539    ogre_->getRoot()->addFrameListener(frameListener_);
540  }
541
542  void Orxonox::startRenderLoop()
543  {
544    // this is a hack!!!
545    // the call to reset the mouse clipping size should probably be somewhere
546    // else, however this works for the moment.
547    unsigned int width, height, depth;
548    int left, top;
549    ogre_->getRoot()->getAutoCreatedWindow()->getMetrics(width, height, depth, left, top);
550
551    if(mode_!=CLIENT){
552      const OIS::MouseState &ms = mouse_->getMouseState();
553      ms.width = width;
554      ms.height = height;
555    }
556    ogre_->getRoot()->startRendering();
557  }
558}
Note: See TracBrowser for help on using the repository browser.