Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 604 was 604, checked in by dumenim, 16 years ago

fsdölkfjas

File size: 15.1 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, gameMode mode)
90      : mKeyboard(keyboard), mMouse(mouse)
91      {
92
93
94        mode_=mode;
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        if(mode_==PRESENTATION){
165          server_g->tick(evt.timeSinceLastFrame);
166          std::cout << "tick server" << std::endl;
167        }
168        usleep(10);
169        return !mKeyboard->isKeyDown(OIS::KC_ESCAPE);
170      }
171
172      bool mouseMoved(const OIS::MouseEvent &e)
173      {
174        mouseX += e.state.X.rel;
175        mouseY += e.state.Y.rel;
176        if(mouseX>maxMouseX) maxMouseX = mouseX;
177        if(mouseX<minMouseX) minMouseX = mouseX;
178        //cout << "mouseX: " << mouseX << "\tmouseY: " << mouseY << endl;
179        moved = true;
180        return true;
181      }
182
183      bool mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
184      bool mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id) { return true; }
185
186    private:
187      gameMode mode_;
188      float speed;
189      float rotate;
190      float loop;
191      float mouseY;
192      float mouseX;
193      float maxMouseX;
194      float minMouseX;
195      bool moved;
196      OIS::Keyboard *mKeyboard;
197      OIS::Mouse *mMouse;
198      audio::AudioManager*  auMan_;
199      SpaceshipSteering* steering_;
200  };
201  // init static singleton reference of Orxonox
202  Orxonox* Orxonox::singletonRef_ = NULL;
203
204  /**
205   * create a new instance of Orxonox
206   */
207  Orxonox::Orxonox()
208  {
209    ogre_ = new GraphicsEngine();
210    dataPath_ = "";
211  }
212
213  /**
214   * destruct Orxonox
215   */
216  Orxonox::~Orxonox()
217  {
218    // nothing to delete as for now
219  }
220
221  /**
222   * initialization of Orxonox object
223   * @param argc argument counter
224   * @param argv list of arguments
225   * @param path path to config (in home dir or something)
226   */
227  void Orxonox::init(int argc, char **argv, std::string path)
228  {
229    //TODO: find config file (assuming executable directory)
230    //TODO: read config file
231    //TODO: give config file to Ogre
232    std::string mode;
233//     if(argc>=2)
234//       mode = std::string(argv[1]);
235//     else
236//       mode = "";
237    ArgReader ar = ArgReader(argc, argv);
238    ar.checkArgument("mode", mode, false);
239    ar.checkArgument("data", this->dataPath_, false);
240    ar.checkArgument("ip", serverIp_, false);
241    if(ar.errorHandling()) die();
242
243    if(mode == std::string("server"))
244    {
245      serverInit(path);
246      mode_ = SERVER;
247    }
248    else if(mode == std::string("client"))
249    {
250      clientInit(path);
251      mode_ = CLIENT;
252    }
253    else if(mode == std::string("presentation"))
254    {
255      serverInit(path);
256      mode_ = PRESENTATION;
257    }
258    else{
259      standaloneInit(path);
260      mode_ = STANDALONE;
261    }
262  }
263
264  /**
265   * start modules
266   */
267  void Orxonox::start()
268  {
269    //TODO: start modules
270    ogre_->startRender();
271    //TODO: run engine
272    createScene();
273    setupScene();
274    setupInputSystem();
275    if(mode_!=CLIENT){ // remove this in future ---- presentation hack
276    }
277    else
278      std::cout << "client here" << std::endl;
279    createFrameListener();
280    Factory::createClassHierarchy();
281    switch(mode_){
282    case PRESENTATION:
283      //ogre_->getRoot()->addFrameListener(new network::ServerFrameListener());
284      //std::cout << "could not add framelistener" << std::endl;
285      server_g->open();
286      break;
287    case CLIENT:
288      client_g->establishConnection();
289      break;
290    case SERVER:
291    case STANDALONE:
292    default:
293      break;
294    }
295    startRenderLoop();
296  }
297
298  /**
299   * @return singleton object
300   */
301  Orxonox* Orxonox::getSingleton()
302  {
303    if (!singletonRef_)
304      singletonRef_ = new Orxonox();
305    return singletonRef_;
306  }
307
308  /**
309   * error kills orxonox
310   */
311  void Orxonox::die(/* some error code */)
312  {
313    //TODO: destroy and destruct everything and print nice error msg
314    delete this;
315  }
316
317  void Orxonox::standaloneInit(std::string path)
318  {
319    ogre_->setConfigPath(path);
320    ogre_->setup();
321    root_ = ogre_->getRoot();
322    if(!ogre_->load()) die(/* unable to load */);
323
324    //defineResources();
325    //setupRenderSystem();
326    //createRenderWindow();
327    //initializeResourceGroups();
328    /*createScene();
329    setupScene();
330    setupInputSystem();
331    createFrameListener();
332    Factory::createClassHierarchy();
333    startRenderLoop();*/
334  }
335
336  void Orxonox::playableServer(std::string path)
337  {
338    ogre_->setConfigPath(path);
339    ogre_->setup();
340    root_ = ogre_->getRoot();
341    defineResources();
342    setupRenderSystem();
343    createRenderWindow();
344    initializeResourceGroups();
345    createScene();
346    setupScene();
347    setupInputSystem();
348    Factory::createClassHierarchy();
349    createFrameListener();
350    try{
351      server_g = new network::Server(); // add port and bindadress
352      server_g->open(); // open server and create listener thread
353      if(ogre_ && ogre_->getRoot())
354        ogre_->getRoot()->addFrameListener(new network::ServerFrameListener()); // adds a framelistener for the server
355      COUT(3) << "Info: network framelistener added" << std::endl;
356    }
357    catch(exception &e)
358    {
359      COUT(1) << "Error: There was a problem initialising the server :(" << std::endl;
360    }
361    startRenderLoop();
362  }
363
364  void Orxonox::standalone(){
365
366
367
368  }
369
370  void Orxonox::serverInit(std::string path)
371  {
372    COUT(2) << "initialising server" << std::endl;
373    ogre_->setConfigPath(path);
374    ogre_->setup();
375    server_g = new network::Server(); // add some settings if wanted
376    if(!ogre_->load()) die(/* unable to load */);
377    // add network framelistener
378  }
379
380  void Orxonox::clientInit(std::string path)
381  {
382    COUT(2) << "initialising client" << std::endl;
383    ogre_->setConfigPath(path);
384    ogre_->setup();
385    if(serverIp_.compare("")==0)
386      client_g = new network::Client();
387    else
388      client_g = new network::Client(serverIp_, 55556);
389    if(!ogre_->load()) die(/* unable to load */);
390    ogre_->getRoot()->addFrameListener(new network::ClientFrameListener());
391  }
392
393  void Orxonox::defineResources()
394  {
395    Ogre::String secName, typeName, archName;
396    Ogre::ConfigFile cf;
397#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
398    cf.load(macBundlePath() + "/Contents/Resources/resources.cfg");
399#else
400    cf.load(dataPath_ + "resources.cfg");
401#endif
402
403    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
404    while (seci.hasMoreElements())
405    {
406      secName = seci.peekNextKey();
407      Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
408      Ogre::ConfigFile::SettingsMultiMap::iterator i;
409      for (i = settings->begin(); i != settings->end(); ++i)
410      {
411        typeName = i->first;
412        archName = i->second;
413#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
414        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( String(macBundlePath() + "/" + archName), typeName, secName);
415#else
416        Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName);
417#endif
418      }
419    }
420  }
421
422  void Orxonox::setupRenderSystem()
423  {
424    if (!root_->restoreConfig() && !root_->showConfigDialog())
425      throw Exception(52, "User canceled the config dialog!", "OrxApplication::setupRenderSystem()");
426  }
427
428  void Orxonox::createRenderWindow()
429  {
430    root_->initialise(true, "OrxonoxV2");
431  }
432
433  void Orxonox::initializeResourceGroups()
434  {
435    TextureManager::getSingleton().setDefaultNumMipmaps(5);
436    ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
437  }
438
439  /**
440   *
441   * @param
442   */
443  void Orxonox::createScene(void)
444  {
445        // Init audio
446    auMan_ = new audio::AudioManager();
447
448    // load this file from config
449    loader_ = new loader::LevelLoader("sample.oxw");
450    loader_->loadLevel();
451
452    Overlay* hudOverlay = OverlayManager::getSingleton().getByName("Orxonox/HUD1.2");
453    hud::HUD* orxonoxHud;
454    orxonoxHud = new hud::HUD();
455    orxonoxHud->setEnergyValue(20);
456    orxonoxHud->setEnergyDistr(20,20,60);
457    hudOverlay->show();
458
459
460        /*
461    auMan_->ambientAdd("a1");
462    auMan_->ambientAdd("a2");
463    auMan_->ambientAdd("a3");
464                                //auMan->ambientAdd("ambient1");
465    auMan_->ambientStart();*/
466  }
467
468
469  /**
470   *
471   */
472  void Orxonox::setupScene()
473  {
474    SceneManager *mgr = ogre_->getSceneManager();
475
476
477    SceneNode* node = (SceneNode*)mgr->getRootSceneNode()->getChild("OgreHeadNode");
478//     SceneNode *node = mgr->getRootSceneNode()->createChildSceneNode("OgreHeadNode", Vector3(0,0,0));
479
480
481    steering_ = new SpaceshipSteering(500, 200, 200, 200);
482    steering_->addNode(node);
483
484/*
485    particle::ParticleInterface *e = new particle::ParticleInterface(mgr,"engine","Orxonox/strahl");
486    e->particleSystem_->setParameter("local_space","true");
487    e->setPositionOfEmitter(0, Vector3(0,-10,0));
488    e->setDirection(Vector3(0,0,-1));
489    e->addToSceneNode(node);
490*/
491
492    particle::ParticleInterface *w = new particle::ParticleInterface(mgr,"schuss","Orxonox/schuss");
493    w->particleSystem_->setParameter("local_space","true");
494    w->newEmitter();
495    w->setDirection(Vector3(0,0,1));
496    w->setPositionOfEmitter(0, Vector3(10,10,0));
497    w->setPositionOfEmitter(1, Vector3(-10,10,0));
498    w->addToSceneNode(node);
499
500    particle::ParticleInterface *tt = new particle::ParticleInterface(mgr,"twinthruster","Orxonox/engineglow");
501    tt->particleSystem_->setParameter("local_space","true");
502    tt->newEmitter();
503    tt->setDirection(Vector3(0,0,-1));
504    tt->setPositionOfEmitter(0, Vector3(20,-1,-15));
505    tt->setPositionOfEmitter(1, Vector3(-20,-1,-15));
506    tt->addToSceneNode(node);
507
508  }
509
510
511  void Orxonox::setupInputSystem()
512  {
513    size_t windowHnd = 0;
514    std::ostringstream windowHndStr;
515    OIS::ParamList pl;
516    Ogre::RenderWindow *win = ogre_->getRoot()->getAutoCreatedWindow();
517
518    win->getCustomAttribute("WINDOW", &windowHnd);
519    windowHndStr << windowHnd;
520    pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
521    inputManager_ = OIS::InputManager::createInputSystem(pl);
522
523    try
524    {
525      keyboard_ = static_cast<OIS::Keyboard*>(inputManager_->createInputObject(OIS::OISKeyboard, false));
526      mouse_ = static_cast<OIS::Mouse*>(inputManager_->createInputObject(OIS::OISMouse, true));
527    }
528    catch (const OIS::Exception &e)
529    {
530      throw new Ogre::Exception(42, e.eText, "OrxApplication::setupInputSystem");
531    }
532  }
533
534  // we actually want to do this differently...
535  void Orxonox::createFrameListener()
536  {
537    TickFrameListener* TickFL = new TickFrameListener();
538    ogre_->getRoot()->addFrameListener(TickFL);
539
540    TimerFrameListener* TimerFL = new TimerFrameListener();
541    ogre_->getRoot()->addFrameListener(TimerFL);
542
543    //if(mode_!=CLIENT) // just a hack ------- remove this in future
544      frameListener_ = new OrxListener(keyboard_, mouse_, auMan_, steering_, mode_);
545    ogre_->getRoot()->addFrameListener(frameListener_);
546  }
547
548  void Orxonox::startRenderLoop()
549  {
550    // this is a hack!!!
551    // the call to reset the mouse clipping size should probably be somewhere
552    // else, however this works for the moment.
553    unsigned int width, height, depth;
554    int left, top;
555    ogre_->getRoot()->getAutoCreatedWindow()->getMetrics(width, height, depth, left, top);
556
557    if(mode_!=CLIENT){
558      const OIS::MouseState &ms = mouse_->getMouseState();
559      ms.width = width;
560      ms.height = height;
561    }
562    ogre_->getRoot()->startRendering();
563  }
564}
Note: See TracBrowser for help on using the repository browser.