Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 1645 was 1645, checked in by rgrieder, 17 years ago

It compiles now on tardis..

  • Property svn:eol-style set to native
File size: 16.0 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)
[1038]117  {
[1638]118    RegisterRootObject(Orxonox);
119
[1642]120    //assert(singletonRef_s == 0);
121    OrxAssert(singletonRef_s == 0, "asdfasdfasdfasdfblahblah");
[1638]122    singletonRef_s = this;
[1038]123  }
124
125  /**
[1293]126   * Destruct Orxonox.
[1038]127   */
128  Orxonox::~Orxonox()
129  {
130    // keep in mind: the order of deletion is very important!
[1642]131    if (this->timer_)
132      delete this->timer_;
133
134    Loader::unload(startLevel_);
[1625]135    if (this->startLevel_)
136      delete this->startLevel_;
137
138    Loader::unload(hud_);
139    if (this->hud_)
140      delete this->hud_;
141
142    if (this->radar_)
143      delete this->radar_;
144
[1293]145    //if (this->auMan_)
146    //  delete this->auMan_;
[1038]147
[1642]148    if (this->console_)
149      delete this->console_;
150
151    if (inputManager_)
152      delete inputManager_;
153
[1638]154    if (this->ogre_)
155      delete ogre_;
156
[1293]157    if (network::Client::getSingleton())
158      network::Client::destroySingleton();
[1038]159    if (server_g)
[1534]160      delete network::Server::getSingleton();
[1638]161
[1642]162    // this call will delete every BaseObject!
163    // But currently this will call methods of objects that exist no more
164    // The only 'memory leak' is the ParticleSpawer. They would be deleted here
165    // and call a sceneNode method that has already been destroy by the corresponding space ship.
166    //Loader::close();
167
[1638]168    singletonRef_s = 0;
[1038]169  }
170
[1638]171  void Orxonox::setConfigValues()
172  {
173    SetConfigValue(debugRefreshTime_, 0.2).description("Sets the time interval at which average fps, etc. get updated.");
174  }
[1038]175
[1638]176
[1038]177  /**
178    Asks the mainloop nicely to abort.
179  */
180  void Orxonox::abortRequest()
181  {
[1293]182    COUT(3) << "Orxonox: Abort requested." << std::endl;
[1038]183    bAbort_ = true;
184  }
185
186  /**
[1293]187   * @return singleton reference
[1038]188   */
[1638]189  Orxonox& Orxonox::getSingleton()
[1038]190  {
[1638]191    assert(singletonRef_s);
192    return *singletonRef_s;
[1038]193  }
194
195  /**
[1563]196    @brief Changes the speed of Orxonox
197  */
198  void Orxonox::setTimeFactor(float factor)
199  {
[1638]200    float change = factor / Orxonox::getSingleton().getTimeFactor();
201    Orxonox::getSingleton().timefactor_ = factor;
[1563]202    for (Iterator<ParticleInterface> it = ObjectList<ParticleInterface>::begin(); it; ++it)
203        it->setSpeedFactor(it->getSpeedFactor() * change);
[1608]204
205    for (Iterator<Backlight> it = ObjectList<Backlight>::begin(); it; ++it)
[1638]206        it->setTimeFactor(Orxonox::getSingleton().getTimeFactor());
[1563]207  }
208
[1638]209
[1563]210  /**
[1638]211   * Starts the whole Game.
[1038]212   * @param path path to config (in home dir or something)
213   */
[1638]214  void Orxonox::start()
[1038]215  {
[1535]216#ifdef _DEBUG
217    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox_d.ini");
218#else
219    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox.ini");
220#endif
221    Factory::createClassHierarchy();
222
[1638]223    setConfigValues();
[1038]224
[1638]225    const Settings::CommandLineArgument* mode = Settings::getCommandLineArgument("mode");
226    assert(mode);
227    if (!mode->bHasDefaultValue_)
[1535]228    {
[1638]229      Settings::setGameMode(mode->value_);
230      this->mode_ = Settings::getGameMode();
[1535]231    }
[1638]232    COUT(3) << "Orxonox: Game mode is " << mode_.name << "." << std::endl;
[1293]233
[1638]234    const Settings::CommandLineArgument* dataPath = Settings::getCommandLineArgument("dataPath");
235    assert(dataPath);
236    if (!dataPath->bHasDefaultValue_)
[1293]237    {
[1638]238      if (*dataPath->value_.getString().end() != '/' && *dataPath->value_.getString().end() != '\\')
239        Settings::tsetDataPath(dataPath->value_.getString() + "/");
240      else
241        Settings::tsetDataPath(dataPath->value_.getString());
[1038]242    }
243
[1638]244    try
[1535]245    {
[1638]246        // initialise TCL
247        TclBind::getInstance().setDataPath(Settings::getDataPath());
[1535]248
[1638]249        ogre_ = new GraphicsEngine();
250        ogre_->setup();       // creates ogre root and other essentials
[1535]251
[1638]252        if (mode_.showsGraphics)
253        {
254          ogre_->loadRenderer();    // creates the render window
[1052]255
[1638]256          // TODO: Spread this so that this call only initialises things needed for the Console and GUI
257          ogre_->initialiseResources();
[1052]258
[1638]259          // Calls the InputManager which sets up the input devices.
260          // The render window width and height are used to set up the mouse movement.
[1642]261          inputManager_ = new InputManager();
262          inputManager_->initialise(ogre_->getWindowHandle(),
[1638]263                ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true);
264          KeyBinder* keyBinder = new KeyBinder();
[1640]265          keyBinder->loadBindings();
[1642]266          inputManager_->createSimpleInputState("game", 20)->setHandler(keyBinder);
[1052]267
[1638]268          // Load the InGameConsole
[1642]269          console_ = new InGameConsole();
270          console_->initialise();
[1052]271
[1638]272          // load the CEGUI interface
273          GUIManager::getInstance().initialise();
274        }
275
276        bool showGUI = true;
277        if (mode_.mode != GameMode::Unspecified)
278        {
279          showGUI = false;
280          // a game mode was specified with the command line
281          // we therefore load the game and level directly
282
283          if (!loadLevel(this->mode_))
284          {
285            COUT(1) << "Loading with predefined mode failed. Showing main menu." << std::endl;
286            showGUI = true;
287            mode_ = GameMode::GM_Unspecified;
288          }
289        }
290       
291        if (showGUI)
292        {
293          // show main menu
[1640]294          GUIManager::getInstance().showGUI("MainMenu", 0);
295          GraphicsEngine::getSingleton().getViewport()->setCamera(GUIManager::getInstance().getCamera());
[1638]296        }
297    }
298    catch (std::exception& ex)
[1502]299    {
[1638]300      COUT(1) << ex.what() << std::endl;
301      COUT(1) << "Loading sequence aborted." << std::endl;
302      return;
[1502]303    }
[1293]304
[1638]305    modeRequest_ = mode_;
306    // here happens the game
307    startRenderLoop();
[1577]308
[1638]309    if (mode_.mode == GameMode::Client)
310      network::Client::getSingleton()->closeConnection();
[1577]311
[1638]312    if (mode_.hasServer)
313      server_g->close();
314  }
[1293]315
[1641]316  /*static*/ void Orxonox::loadGame(const std::string& name)
[1638]317  {
318      const GameMode& mode = Settings::getGameMode(name);
319      if (mode.mode == GameMode::None)
320          return;
[1293]321
[1638]322      getSingleton().modeRequest_ = mode;
323  }
[1293]324
[1638]325  bool Orxonox::loadLevel(const GameMode& mode)
326  {
327      bool success = true;
[1293]328
[1638]329      if (mode.showsGraphics)
330      {
331        // create Ogre SceneManager for the level
332        ogre_->createNewScene();
[1293]333
[1638]334        if (!loadPlayground())
335            return false;
336      }
[1293]337
[1638]338      switch (mode.mode)
339      {
340      case GameMode::Server:
341        success &= serverLoad();
342        break;
343      case GameMode::Client:
344        success &= clientLoad();
345        break;
346      case GameMode::Dedicated:
347        success &= serverLoad();
348        break;
349      case GameMode::Standalone:
350        success &= standaloneLoad();
351        break;
352      default: // never happens
353          assert(false);
354      }
355     
356      if (success)
[1640]357      {
[1642]358        InputManager::getInstance().requestEnterState("game");
[1640]359        this->mode_ = mode;
360      }
[1293]361
[1638]362      return success;
[1038]363  }
[1052]364
[1293]365  /**
366   * Loads everything in the scene except for the actual objects.
[1577]367   * This includes HUD, audio..
[1293]368   */
369  bool Orxonox::loadPlayground()
370  {
[1638]371    // Start the Radar
372    this->radar_ = new Radar();
[1052]373
[1293]374    // Load the HUD
[1625]375    COUT(3) << "Orxonox: Loading HUD" << std::endl;
376    hud_ = new Level(Settings::getDataPath() + "overlay/hud.oxo");
[1638]377    return Loader::load(hud_);
378  }
[1577]379
[1638]380  /**
381   * Helper method to load a level.
382   */
383  bool Orxonox::loadScene()
384  {
385    COUT(0) << "Loading level..." << std::endl;
386    startLevel_ = new Level(Settings::getDataPath() + "levels/sample.oxw");
387    return Loader::open(startLevel_);
[1293]388  }
[1052]389
[1293]390  /**
391   * Level loading method for server mode.
392   */
393  bool Orxonox::serverLoad()
394  {
[1577]395    COUT(0) << "Loading level in server mode" << std::endl;
[1052]396
[1638]397    assert(Settings::getCommandLineArgument("port"));
398    int serverPort = Settings::getCommandLineArgument("port")->value_;
[1534]399    //server_g = new network::Server(serverPort_);
[1638]400    server_g = network::Server::createSingleton(serverPort);
[1052]401
[1293]402    if (!loadScene())
403      return false;
[1052]404
[1038]405    server_g->open();
[1052]406
[1293]407    return true;
[1038]408  }
[1052]409
[1293]410  /**
411   * Level loading method for client mode.
412   */
413  bool Orxonox::clientLoad()
414  {
[1577]415    COUT(0) << "Loading level in client mode" << std::endl;\
[1052]416
[1638]417    assert(Settings::getCommandLineArgument("port"));
418    assert(Settings::getCommandLineArgument("ip"));
419    int serverPort = Settings::getCommandLineArgument("port")->value_;
420    std::string serverIP = Settings::getCommandLineArgument("ip")->value_;
421
422    if (serverIP.compare("") == 0)
[1293]423      client_g = network::Client::createSingleton();
424    else
[1638]425      client_g = network::Client::createSingleton(serverIP, serverPort);
[1293]426
[1502]427    if(!client_g->establishConnection())
428      return false;
[1293]429    client_g->tick(0);
430
431    return true;
[1038]432  }
433
[1293]434  /**
435   * Level loading method for standalone mode.
436   */
437  bool Orxonox::standaloneLoad()
[1038]438  {
[1577]439    COUT(0) << "Loading level in standalone mode" << std::endl;
[1038]440
[1293]441    if (!loadScene())
442      return false;
[1038]443
[1293]444    return true;
[1038]445  }
446
447  /**
448    Main loop of the orxonox game.
[1638]449    We use the Ogre::Timer to measure time since it uses the most precise
450    method an a platform (however the windows timer lacks time when under
451    heavy kernel load!).
452    There is a simple mechanism to measure the average time spent in our
453    ticks as it may indicate performance issues.
454    A note about the Ogre::FrameListener: Even though we don't use them,
455    they still get called. However, the delta times are not correct (except
456    for timeSinceLastFrame, which is the most important). A little research
457    as shown that there is probably only one FrameListener that doesn't even
458    need the time. So we shouldn't run into problems.
[1038]459  */
[1638]460  void Orxonox::startRenderLoop()
[1038]461  {
[1120]462    Ogre::Root& ogreRoot = Ogre::Root::getSingleton();
[1038]463
464    // use the ogre timer class to measure time.
465    if (!timer_)
466      timer_ = new Ogre::Timer();
467
[1625]468    unsigned long frameCount = 0;
469   
[1645]470    const unsigned long refreshTime = (unsigned long)(debugRefreshTime_ * 1000000.0f);
[1625]471    unsigned long refreshStartTime = 0;
472    unsigned long tickTime = 0;
473    unsigned long oldFrameCount = 0;
[1502]474
[1625]475    unsigned long timeBeforeTick = 0;
476    unsigned long timeBeforeTickOld = 0;
477    unsigned long timeAfterTick = 0;
[1563]478
[1638]479    // TODO: Update time in seconds every 7 seconds to avoid any overflow (7 secs is very tight)
480
[1625]481    COUT(3) << "Orxonox: Starting the main loop." << std::endl;
[1502]482
[1638]483    try
484    {
[1625]485    timer_->reset();
[1502]486    while (!bAbort_)
487    {
[1638]488        // get current time
489        timeBeforeTickOld = timeBeforeTick;
490        timeBeforeTick    = timer_->getMicroseconds();
491        float dt = (timeBeforeTick - timeBeforeTickOld) / 1000000.0;
[1038]492
[1638]493        // check whether we have to load a game
494        if (mode_.mode != modeRequest_.mode && mode_.mode == GameMode::Unspecified)
495        {
496            this->loadLevel(modeRequest_);
497            this->modeRequest_ = GameMode::GM_None;
498        }
[1038]499
500
[1638]501        // tick the core (needs real time for input and tcl thread management)
502        Core::tick(dt);
[1625]503
[1638]504        // Call those objects that need the real time
505        for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
506          it->tick(dt);
507        // Call the scene objects
508        for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
509          it->tick(dt * this->timefactor_);
[1038]510
[1638]511        // call server/client with normal dt
512        if (client_g)
513          client_g->tick(dt * this->timefactor_);
514        if (server_g)
515          server_g->tick(dt * this->timefactor_);
[1625]516
517
[1638]518        // get current time once again
519        timeAfterTick = timer_->getMicroseconds();
[1625]520
[1638]521        tickTime += timeAfterTick - timeBeforeTick;
522        if (timeAfterTick > refreshStartTime + refreshTime)
523        {
524          GraphicsEngine::getSingleton().setAverageTickTime(
525              (float)tickTime * 0.001 / (frameCount - oldFrameCount));
526          float avgFPS = (float)(frameCount - oldFrameCount) / (timeAfterTick - refreshStartTime) * 1000000.0;
527          GraphicsEngine::getSingleton().setAverageFramesPerSecond(avgFPS);
[1625]528
[1638]529          oldFrameCount = frameCount;
530          tickTime = 0;
531          refreshStartTime = timeAfterTick;
532        }
[1502]533
[1638]534        // don't forget to call _fireFrameStarted in ogre to make sure
535        // everything goes smoothly
536        Ogre::FrameEvent evt;
537        evt.timeSinceLastFrame = dt;
538        evt.timeSinceLastEvent = dt; // note: same time, but shouldn't matter anyway
539        ogreRoot._fireFrameStarted(evt);
[1293]540
[1638]541        if (mode_.showsGraphics)
542        {
543          // Pump messages in all registered RenderWindows
544          // This calls the WindowEventListener objects.
545          Ogre::WindowEventUtilities::messagePump();
546          // make sure the window stays active even when not focused
547          // (probably only necessary on windows)
548          GraphicsEngine::getSingleton().setWindowActivity(true);
[1502]549
[1638]550          // tick CEGUI
551          GUIManager::getInstance().tick(dt);
552
553          // render
554          ogreRoot._updateAllRenderTargets();
555        }
556
557        // again, just to be sure ogre works fine
558        ogreRoot._fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
559
560        ++frameCount;
561    }
562    }
563    catch (std::exception& ex)
564    {
565      // something went wrong.
566      COUT(1) << ex.what() << std::endl;
567      COUT(1) << "Main loop was stopped by an unhandled exception. Shutting down." << std::endl;
568    }
[1038]569  }
570}
Note: See TracBrowser for help on using the repository browser.