Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gui/src/orxonox/Orxonox.cc @ 1651

Last change on this file since 1651 was 1646, checked in by rgrieder, 17 years ago
  • privatised InputState c'tors
  • added destruction code for GUIManager
  • fixed some issues and bugs
  • found 2400 memory leaks ;)
  • haven't done anything about it
  • converted GUIManager to Ogre Singleton
  • added NULL checkers in Loader
  • Property svn:eol-style set to native
File size: 16.1 KB
RevLine 
[1038]1/*
[1293]2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1056]3 *                    > www.orxonox.net <
[1038]4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
[1535]23 *      Reto Grieder
[1638]24 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
[1535]25 *   Co-authors:
[1638]26 *      ...
[1038]27 *
28 */
29
30/**
31 @file
32 @brief Orxonox Main Class
33 */
34
35// Precompiled Headers
36#include "OrxonoxStableHeaders.h"
[1039]37#include "Orxonox.h"
[1038]38
39//****** STD *******
40#include <deque>
[1638]41#include <cassert>
[1038]42
43//****** OGRE ******
44#include <OgreFrameListener.h>
45#include <OgreOverlay.h>
46#include <OgreOverlayManager.h>
47#include <OgreRoot.h>
48#include <OgreTimer.h>
49#include <OgreWindowEventUtilities.h>
50
51//***** ORXONOX ****
52// util
53//#include "util/Sleep.h"
54
[1293]55// core
[1054]56#include "core/ConfigFileManager.h"
[1638]57#include "core/ConfigValueIncludes.h"
[1293]58#include "core/ConsoleCommand.h"
[1038]59#include "core/Debug.h"
60#include "core/Loader.h"
[1638]61#include "core/Exception.h"
[1535]62#include "core/input/InputManager.h"
[1638]63#include "core/input/SimpleInputState.h"
64#include "core/input/KeyBinder.h"
[1293]65#include "core/TclBind.h"
[1535]66#include "core/Core.h"
[1038]67
68// audio
69#include "audio/AudioManager.h"
70
71// network
72#include "network/Server.h"
73#include "network/Client.h"
74
75// objects and tools
[1625]76#include "overlays/console/InGameConsole.h"
[1535]77#include "objects/Tickable.h"
[1608]78#include "objects/Backlight.h"
[1563]79#include "tools/ParticleInterface.h"
[1638]80#include "gui/GUIManager.h"
[1038]81
[1502]82#include "GraphicsEngine.h"
[1535]83#include "Settings.h"
[1625]84#include "Radar.h"
[1502]85
[1038]86// globals for the server or client
[1577]87static network::Client *client_g = 0;
88static network::Server *server_g = 0;
[1038]89
90namespace orxonox
[1293]91{
[1638]92  SetConsoleCommand(Orxonox, exit, true).setKeybindMode(KeybindMode::OnPress);
93  SetConsoleCommand(Orxonox, slomo, true).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0).setAxisParamIndex(0).setIsAxisRelative(false);
94  SetConsoleCommand(Orxonox, setTimeFactor, true).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0);
95  SetConsoleCommand(Orxonox, loadGame, true).setAccessLevel(AccessLevel::User).setDefaultValue(0, "standalone");
[1505]96
[1038]97  /**
98    @brief Reference to the only instance of the class.
99  */
100  Orxonox *Orxonox::singletonRef_s = 0;
101
102  /**
[1293]103   * Create a new instance of Orxonox. Avoid doing any actual work here.
[1038]104   */
[1625]105  Orxonox::Orxonox()
[1642]106    : startLevel_(0)
[1625]107    , hud_(0)
108    //, auMan_(0)
109    , timer_(0)
110    , bAbort_(false)
111    , timefactor_(1.0f)
[1638]112    , mode_(GameMode::GM_Unspecified)
113    , debugRefreshTime_(0.0f)
[1642]114    , ogre_(0)
115    , inputManager_(0)
116    , radar_(0)
[1646]117    , console_(0)
118    , guiManager_(0)
[1038]119  {
[1638]120    RegisterRootObject(Orxonox);
121
[1642]122    //assert(singletonRef_s == 0);
123    OrxAssert(singletonRef_s == 0, "asdfasdfasdfasdfblahblah");
[1638]124    singletonRef_s = this;
[1038]125  }
126
127  /**
[1293]128   * Destruct Orxonox.
[1038]129   */
130  Orxonox::~Orxonox()
131  {
132    // keep in mind: the order of deletion is very important!
[1642]133    if (this->timer_)
134      delete this->timer_;
135
136    Loader::unload(startLevel_);
[1625]137    if (this->startLevel_)
138      delete this->startLevel_;
139
140    Loader::unload(hud_);
141    if (this->hud_)
142      delete this->hud_;
143
144    if (this->radar_)
145      delete this->radar_;
146
[1646]147    if (this->guiManager_)
148      delete guiManager_;
149
[1293]150    //if (this->auMan_)
151    //  delete this->auMan_;
[1038]152
[1642]153    if (this->console_)
154      delete this->console_;
155
156    if (inputManager_)
157      delete inputManager_;
158
[1638]159    if (this->ogre_)
160      delete ogre_;
161
[1293]162    if (network::Client::getSingleton())
163      network::Client::destroySingleton();
[1038]164    if (server_g)
[1534]165      delete network::Server::getSingleton();
[1638]166
[1642]167    // this call will delete every BaseObject!
168    // But currently this will call methods of objects that exist no more
169    // The only 'memory leak' is the ParticleSpawer. They would be deleted here
170    // and call a sceneNode method that has already been destroy by the corresponding space ship.
171    //Loader::close();
172
[1638]173    singletonRef_s = 0;
[1038]174  }
175
[1638]176  void Orxonox::setConfigValues()
177  {
178    SetConfigValue(debugRefreshTime_, 0.2).description("Sets the time interval at which average fps, etc. get updated.");
179  }
[1038]180
[1638]181
[1038]182  /**
183    Asks the mainloop nicely to abort.
184  */
185  void Orxonox::abortRequest()
186  {
[1293]187    COUT(3) << "Orxonox: Abort requested." << std::endl;
[1038]188    bAbort_ = true;
189  }
190
191  /**
[1293]192   * @return singleton reference
[1038]193   */
[1638]194  Orxonox& Orxonox::getSingleton()
[1038]195  {
[1638]196    assert(singletonRef_s);
197    return *singletonRef_s;
[1038]198  }
199
200  /**
[1563]201    @brief Changes the speed of Orxonox
202  */
203  void Orxonox::setTimeFactor(float factor)
204  {
[1638]205    float change = factor / Orxonox::getSingleton().getTimeFactor();
206    Orxonox::getSingleton().timefactor_ = factor;
[1563]207    for (Iterator<ParticleInterface> it = ObjectList<ParticleInterface>::begin(); it; ++it)
208        it->setSpeedFactor(it->getSpeedFactor() * change);
[1608]209
210    for (Iterator<Backlight> it = ObjectList<Backlight>::begin(); it; ++it)
[1638]211        it->setTimeFactor(Orxonox::getSingleton().getTimeFactor());
[1563]212  }
213
[1638]214
[1563]215  /**
[1638]216   * Starts the whole Game.
[1038]217   * @param path path to config (in home dir or something)
218   */
[1638]219  void Orxonox::start()
[1038]220  {
[1535]221#ifdef _DEBUG
222    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox_d.ini");
223#else
224    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox.ini");
225#endif
226    Factory::createClassHierarchy();
227
[1638]228    setConfigValues();
[1038]229
[1638]230    const Settings::CommandLineArgument* mode = Settings::getCommandLineArgument("mode");
231    assert(mode);
232    if (!mode->bHasDefaultValue_)
[1535]233    {
[1638]234      Settings::setGameMode(mode->value_);
235      this->mode_ = Settings::getGameMode();
[1535]236    }
[1638]237    COUT(3) << "Orxonox: Game mode is " << mode_.name << "." << std::endl;
[1293]238
[1638]239    const Settings::CommandLineArgument* dataPath = Settings::getCommandLineArgument("dataPath");
240    assert(dataPath);
241    if (!dataPath->bHasDefaultValue_)
[1293]242    {
[1638]243      if (*dataPath->value_.getString().end() != '/' && *dataPath->value_.getString().end() != '\\')
244        Settings::tsetDataPath(dataPath->value_.getString() + "/");
245      else
246        Settings::tsetDataPath(dataPath->value_.getString());
[1038]247    }
248
[1638]249    try
[1535]250    {
[1638]251        // initialise TCL
252        TclBind::getInstance().setDataPath(Settings::getDataPath());
[1535]253
[1638]254        ogre_ = new GraphicsEngine();
255        ogre_->setup();       // creates ogre root and other essentials
[1535]256
[1638]257        if (mode_.showsGraphics)
258        {
259          ogre_->loadRenderer();    // creates the render window
[1052]260
[1638]261          // TODO: Spread this so that this call only initialises things needed for the Console and GUI
262          ogre_->initialiseResources();
[1052]263
[1638]264          // Calls the InputManager which sets up the input devices.
265          // The render window width and height are used to set up the mouse movement.
[1642]266          inputManager_ = new InputManager();
267          inputManager_->initialise(ogre_->getWindowHandle(),
[1638]268                ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true);
269          KeyBinder* keyBinder = new KeyBinder();
[1640]270          keyBinder->loadBindings();
[1642]271          inputManager_->createSimpleInputState("game", 20)->setHandler(keyBinder);
[1052]272
[1638]273          // Load the InGameConsole
[1642]274          console_ = new InGameConsole();
275          console_->initialise();
[1052]276
[1638]277          // load the CEGUI interface
[1646]278          guiManager_ = new GUIManager();
279          guiManager_->initialise();
[1638]280        }
281
282        bool showGUI = true;
283        if (mode_.mode != GameMode::Unspecified)
284        {
285          showGUI = false;
286          // a game mode was specified with the command line
287          // we therefore load the game and level directly
288
289          if (!loadLevel(this->mode_))
290          {
291            COUT(1) << "Loading with predefined mode failed. Showing main menu." << std::endl;
292            showGUI = true;
293            mode_ = GameMode::GM_Unspecified;
294          }
295        }
296       
297        if (showGUI)
298        {
299          // show main menu
[1640]300          GUIManager::getInstance().showGUI("MainMenu", 0);
301          GraphicsEngine::getSingleton().getViewport()->setCamera(GUIManager::getInstance().getCamera());
[1638]302        }
303    }
304    catch (std::exception& ex)
[1502]305    {
[1638]306      COUT(1) << ex.what() << std::endl;
307      COUT(1) << "Loading sequence aborted." << std::endl;
308      return;
[1502]309    }
[1293]310
[1638]311    modeRequest_ = mode_;
312    // here happens the game
313    startRenderLoop();
[1577]314
[1638]315    if (mode_.mode == GameMode::Client)
316      network::Client::getSingleton()->closeConnection();
[1577]317
[1638]318    if (mode_.hasServer)
319      server_g->close();
320  }
[1293]321
[1641]322  /*static*/ void Orxonox::loadGame(const std::string& name)
[1638]323  {
324      const GameMode& mode = Settings::getGameMode(name);
325      if (mode.mode == GameMode::None)
326          return;
[1293]327
[1638]328      getSingleton().modeRequest_ = mode;
329  }
[1293]330
[1638]331  bool Orxonox::loadLevel(const GameMode& mode)
332  {
333      bool success = true;
[1293]334
[1638]335      if (mode.showsGraphics)
336      {
337        // create Ogre SceneManager for the level
338        ogre_->createNewScene();
[1293]339
[1638]340        if (!loadPlayground())
341            return false;
342      }
[1293]343
[1638]344      switch (mode.mode)
345      {
346      case GameMode::Server:
347        success &= serverLoad();
348        break;
349      case GameMode::Client:
350        success &= clientLoad();
351        break;
352      case GameMode::Dedicated:
353        success &= serverLoad();
354        break;
355      case GameMode::Standalone:
356        success &= standaloneLoad();
357        break;
358      default: // never happens
359          assert(false);
360      }
361     
362      if (success)
[1640]363      {
[1642]364        InputManager::getInstance().requestEnterState("game");
[1640]365        this->mode_ = mode;
366      }
[1293]367
[1638]368      return success;
[1038]369  }
[1052]370
[1293]371  /**
372   * Loads everything in the scene except for the actual objects.
[1577]373   * This includes HUD, audio..
[1293]374   */
375  bool Orxonox::loadPlayground()
376  {
[1638]377    // Start the Radar
378    this->radar_ = new Radar();
[1052]379
[1293]380    // Load the HUD
[1625]381    COUT(3) << "Orxonox: Loading HUD" << std::endl;
382    hud_ = new Level(Settings::getDataPath() + "overlay/hud.oxo");
[1638]383    return Loader::load(hud_);
384  }
[1577]385
[1638]386  /**
387   * Helper method to load a level.
388   */
389  bool Orxonox::loadScene()
390  {
391    COUT(0) << "Loading level..." << std::endl;
392    startLevel_ = new Level(Settings::getDataPath() + "levels/sample.oxw");
393    return Loader::open(startLevel_);
[1293]394  }
[1052]395
[1293]396  /**
397   * Level loading method for server mode.
398   */
399  bool Orxonox::serverLoad()
400  {
[1577]401    COUT(0) << "Loading level in server mode" << std::endl;
[1052]402
[1638]403    assert(Settings::getCommandLineArgument("port"));
404    int serverPort = Settings::getCommandLineArgument("port")->value_;
[1534]405    //server_g = new network::Server(serverPort_);
[1638]406    server_g = network::Server::createSingleton(serverPort);
[1052]407
[1293]408    if (!loadScene())
409      return false;
[1052]410
[1038]411    server_g->open();
[1052]412
[1293]413    return true;
[1038]414  }
[1052]415
[1293]416  /**
417   * Level loading method for client mode.
418   */
419  bool Orxonox::clientLoad()
420  {
[1577]421    COUT(0) << "Loading level in client mode" << std::endl;\
[1052]422
[1638]423    assert(Settings::getCommandLineArgument("port"));
424    assert(Settings::getCommandLineArgument("ip"));
425    int serverPort = Settings::getCommandLineArgument("port")->value_;
426    std::string serverIP = Settings::getCommandLineArgument("ip")->value_;
427
428    if (serverIP.compare("") == 0)
[1293]429      client_g = network::Client::createSingleton();
430    else
[1638]431      client_g = network::Client::createSingleton(serverIP, serverPort);
[1293]432
[1502]433    if(!client_g->establishConnection())
434      return false;
[1293]435    client_g->tick(0);
436
437    return true;
[1038]438  }
439
[1293]440  /**
441   * Level loading method for standalone mode.
442   */
443  bool Orxonox::standaloneLoad()
[1038]444  {
[1577]445    COUT(0) << "Loading level in standalone mode" << std::endl;
[1038]446
[1293]447    if (!loadScene())
448      return false;
[1038]449
[1293]450    return true;
[1038]451  }
452
453  /**
454    Main loop of the orxonox game.
[1638]455    We use the Ogre::Timer to measure time since it uses the most precise
456    method an a platform (however the windows timer lacks time when under
457    heavy kernel load!).
458    There is a simple mechanism to measure the average time spent in our
459    ticks as it may indicate performance issues.
460    A note about the Ogre::FrameListener: Even though we don't use them,
461    they still get called. However, the delta times are not correct (except
462    for timeSinceLastFrame, which is the most important). A little research
463    as shown that there is probably only one FrameListener that doesn't even
464    need the time. So we shouldn't run into problems.
[1038]465  */
[1638]466  void Orxonox::startRenderLoop()
[1038]467  {
[1120]468    Ogre::Root& ogreRoot = Ogre::Root::getSingleton();
[1038]469
470    // use the ogre timer class to measure time.
471    if (!timer_)
472      timer_ = new Ogre::Timer();
473
[1625]474    unsigned long frameCount = 0;
475   
[1645]476    const unsigned long refreshTime = (unsigned long)(debugRefreshTime_ * 1000000.0f);
[1625]477    unsigned long refreshStartTime = 0;
478    unsigned long tickTime = 0;
479    unsigned long oldFrameCount = 0;
[1502]480
[1625]481    unsigned long timeBeforeTick = 0;
482    unsigned long timeBeforeTickOld = 0;
483    unsigned long timeAfterTick = 0;
[1563]484
[1638]485    // TODO: Update time in seconds every 7 seconds to avoid any overflow (7 secs is very tight)
486
[1625]487    COUT(3) << "Orxonox: Starting the main loop." << std::endl;
[1502]488
[1638]489    try
490    {
[1625]491    timer_->reset();
[1502]492    while (!bAbort_)
493    {
[1638]494        // get current time
495        timeBeforeTickOld = timeBeforeTick;
496        timeBeforeTick    = timer_->getMicroseconds();
497        float dt = (timeBeforeTick - timeBeforeTickOld) / 1000000.0;
[1038]498
[1638]499        // check whether we have to load a game
500        if (mode_.mode != modeRequest_.mode && mode_.mode == GameMode::Unspecified)
501        {
502            this->loadLevel(modeRequest_);
503            this->modeRequest_ = GameMode::GM_None;
504        }
[1038]505
506
[1638]507        // tick the core (needs real time for input and tcl thread management)
508        Core::tick(dt);
[1625]509
[1638]510        // Call those objects that need the real time
511        for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
512          it->tick(dt);
513        // Call the scene objects
514        for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
515          it->tick(dt * this->timefactor_);
[1038]516
[1638]517        // call server/client with normal dt
518        if (client_g)
519          client_g->tick(dt * this->timefactor_);
520        if (server_g)
521          server_g->tick(dt * this->timefactor_);
[1625]522
523
[1638]524        // get current time once again
525        timeAfterTick = timer_->getMicroseconds();
[1625]526
[1638]527        tickTime += timeAfterTick - timeBeforeTick;
528        if (timeAfterTick > refreshStartTime + refreshTime)
529        {
530          GraphicsEngine::getSingleton().setAverageTickTime(
531              (float)tickTime * 0.001 / (frameCount - oldFrameCount));
532          float avgFPS = (float)(frameCount - oldFrameCount) / (timeAfterTick - refreshStartTime) * 1000000.0;
533          GraphicsEngine::getSingleton().setAverageFramesPerSecond(avgFPS);
[1625]534
[1638]535          oldFrameCount = frameCount;
536          tickTime = 0;
537          refreshStartTime = timeAfterTick;
538        }
[1502]539
[1638]540        // don't forget to call _fireFrameStarted in ogre to make sure
541        // everything goes smoothly
542        Ogre::FrameEvent evt;
543        evt.timeSinceLastFrame = dt;
544        evt.timeSinceLastEvent = dt; // note: same time, but shouldn't matter anyway
545        ogreRoot._fireFrameStarted(evt);
[1293]546
[1638]547        if (mode_.showsGraphics)
548        {
549          // Pump messages in all registered RenderWindows
550          // This calls the WindowEventListener objects.
551          Ogre::WindowEventUtilities::messagePump();
552          // make sure the window stays active even when not focused
553          // (probably only necessary on windows)
554          GraphicsEngine::getSingleton().setWindowActivity(true);
[1502]555
[1638]556          // tick CEGUI
557          GUIManager::getInstance().tick(dt);
558
559          // render
560          ogreRoot._updateAllRenderTargets();
561        }
562
563        // again, just to be sure ogre works fine
564        ogreRoot._fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
565
566        ++frameCount;
567    }
568    }
569    catch (std::exception& ex)
570    {
571      // something went wrong.
572      COUT(1) << ex.what() << std::endl;
573      COUT(1) << "Main loop was stopped by an unhandled exception. Shutting down." << std::endl;
574    }
[1038]575  }
576}
Note: See TracBrowser for help on using the repository browser.