Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/orxonox/Orxonox.cc @ 1491

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

enet is not threadsafe (catched that now); some first step towards dedicated server

File size: 13.8 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
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:
23 *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30 @file
31 @brief Orxonox Main Class
32 */
33
34// Precompiled Headers
35#include "OrxonoxStableHeaders.h"
36#include "Orxonox.h"
37
38//****** STD *******
39#include <deque>
40
41//****** OGRE ******
42#include <OgreFrameListener.h>
43#include <OgreOverlay.h>
44#include <OgreOverlayManager.h>
45#include <OgreRoot.h>
46#include <OgreTimer.h>
47#include <OgreWindowEventUtilities.h>
48
49//***** ORXONOX ****
50// util
51//#include "util/Sleep.h"
52#include "util/ArgReader.h"
53
54// core
55#include "core/ConfigFileManager.h"
56#include "core/ConsoleCommand.h"
57#include "core/Debug.h"
58#include "core/Loader.h"
59#include "core/Tickable.h"
60#include "core/InputManager.h"
61#include "core/TclBind.h"
62
63// audio
64#include "audio/AudioManager.h"
65
66// network
67#include "network/Server.h"
68#include "network/Client.h"
69
70// objects and tools
71#include "hud/HUD.h"
72#include <Ogre.h>
73
74#include "GraphicsEngine.h"
75
76// FIXME: is this really file scope?
77// globals for the server or client
78network::Client *client_g;
79network::Server *server_g;
80
81namespace orxonox
82{
83  SetConsoleCommandShortcut(Orxonox, exit).setKeybindMode(KeybindMode::OnPress);
84  SetConsoleCommandShortcut(Orxonox, slomo).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0).setAxisParamIndex(0).setIsAxisRelative(false);
85  SetConsoleCommandShortcut(Orxonox, setTimeFactor).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0);
86
87  /**
88    @brief Reference to the only instance of the class.
89  */
90  Orxonox *Orxonox::singletonRef_s = 0;
91
92  /**
93   * Create a new instance of Orxonox. Avoid doing any actual work here.
94   */
95  Orxonox::Orxonox() :
96    ogre_(0),
97    //auMan_(0),
98    timer_(0),
99    // turn on frame smoothing by setting a value different from 0
100    frameSmoothingTime_(0.0f),
101    orxonoxHUD_(0),
102    bAbort_(false),
103    timefactor_(1.0f),
104    mode_(STANDALONE),
105    serverIp_(""),
106    serverPort_(NETWORK_PORT)
107  {
108  }
109
110  /**
111   * Destruct Orxonox.
112   */
113  Orxonox::~Orxonox()
114  {
115    // keep in mind: the order of deletion is very important!
116//    if (this->orxonoxHUD_)
117//      delete this->orxonoxHUD_;
118    Loader::close();
119    InputManager::destroy();
120    //if (this->auMan_)
121    //  delete this->auMan_;
122    if (this->timer_)
123      delete this->timer_;
124    GraphicsEngine::getSingleton().destroy();
125
126    if (network::Client::getSingleton())
127      network::Client::destroySingleton();
128    if (server_g)
129      delete server_g;
130  }
131
132
133  /**
134    Asks the mainloop nicely to abort.
135  */
136  void Orxonox::abortRequest()
137  {
138    COUT(3) << "Orxonox: Abort requested." << std::endl;
139    bAbort_ = true;
140  }
141
142  /**
143   * @return singleton reference
144   */
145  Orxonox* Orxonox::getSingleton()
146  {
147    if (!singletonRef_s)
148      singletonRef_s = new Orxonox();
149    return singletonRef_s;
150  }
151
152  /**
153    @brief Destroys the Orxonox singleton.
154  */
155  void Orxonox::destroySingleton()
156  {
157    if (singletonRef_s)
158      delete singletonRef_s;
159    singletonRef_s = 0;
160  }
161
162  /**
163   * initialization of Orxonox object
164   * @param argc argument counter
165   * @param argv list of argumenst
166   * @param path path to config (in home dir or something)
167   */
168  bool Orxonox::init(int argc, char **argv, std::string path)
169  {
170    //TODO: find config file (assuming executable directory)
171    //TODO: read config file
172    //TODO: give config file to Ogre
173    std::string mode;
174    std::string dataPath;
175
176    ArgReader ar(argc, argv);
177    ar.checkArgument("mode", mode, false);
178    ar.checkArgument("data", dataPath, false);
179    ar.checkArgument("ip", serverIp_, false);
180    ar.checkArgument("port", serverPort_, false);
181    if(ar.errorHandling())
182      return false;
183
184    if (mode == "client")
185      mode_ = CLIENT;
186    else if (mode == "server")
187      mode_ = SERVER;
188    else if (mode == "dedicated")
189      mode_= DEDICATED;
190    else
191    {
192      mode = "standalone";
193      mode_ = STANDALONE;
194    }
195    COUT(3) << "Orxonox: Mode is " << mode << "." << std::endl;
196
197    //if (mode_ == DEDICATED)
198      // TODO: decide what to do here
199    //else
200
201    // for playable server, client and standalone, the startup
202    // procedure until the GUI is identical
203
204    ConfigFileManager::getSingleton()->setFile(CFT_Settings, "orxonox.ini");
205    Factory::createClassHierarchy();
206
207    ogre_ = &GraphicsEngine::getSingleton();
208    if (!ogre_->setup(path))       // creates ogre root and other essentials
209      return false;
210
211    return true;
212  }
213
214  /**
215   * start modules
216   */
217  bool Orxonox::start()
218  {
219    //if (mode_ == DEDICATED)
220    // do something else
221    //else
222
223    if (!ogre_->loadRenderer())    // creates the render window
224      return false;
225
226    // Calls the InputManager which sets up the input devices.
227    // The render window width and height are used to set up the mouse movement.
228    if (!InputManager::initialise(ogre_->getWindowHandle(),
229          ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true))
230      return false;
231
232    // TODO: Spread this so that this call only initialises things needed for the GUI
233    if (!ogre_->initialiseResources())
234      return false;
235
236    // TOOD: load the GUI here
237    // set InputManager to GUI mode
238    InputManager::setInputState(InputManager::IS_GUI);
239    // TODO: run GUI here
240
241    // The following lines depend very much on the GUI output, so they're probably misplaced here..
242
243    InputManager::setInputState(InputManager::IS_NONE);
244
245    if (!loadPlayground())
246      return false;
247
248    switch (mode_)
249    {
250    case SERVER:
251      if (!serverLoad())
252        return false;
253      break;
254    case CLIENT:
255      if (!clientLoad())
256        return false;
257      break;
258    default:
259      if (!standaloneLoad())
260        return false;
261    }
262
263    InputManager::setInputState(InputManager::IS_NORMAL);
264
265    return startRenderLoop();
266  }
267
268  /**
269   * Loads everything in the scene except for the actual objects.
270   * This includes HUD, Console..
271   */
272  bool Orxonox::loadPlayground()
273  {
274    ogre_->createNewScene();
275
276          // Init audio
277    //auMan_ = new audio::AudioManager();
278    //auMan_->ambientAdd("a1");
279    //auMan_->ambientAdd("a2");
280    //auMan_->ambientAdd("a3");
281    //auMan->ambientAdd("ambient1");
282    //auMan_->ambientStart();
283
284    // Load the HUD
285    COUT(3) << "Orxonox: Loading HUD..." << std::endl;
286    orxonoxHUD_ = &HUD::getSingleton();
287    return true;
288  }
289
290  /**
291   * Level loading method for server mode.
292   */
293  bool Orxonox::serverLoad()
294  {
295    COUT(2) << "Loading level in server mode" << std::endl;
296
297    server_g = new network::Server(serverPort_);
298
299    if (!loadScene())
300      return false;
301
302    server_g->open();
303
304    return true;
305  }
306
307  /**
308   * Level loading method for client mode.
309   */
310  bool Orxonox::clientLoad()
311  {
312    COUT(2) << "Loading level in client mode" << std::endl;\
313
314    if (serverIp_.compare("") == 0)
315      client_g = network::Client::createSingleton();
316    else
317
318      client_g = network::Client::createSingleton(serverIp_, serverPort_);
319
320    if(!client_g->establishConnection())
321      return false;
322    client_g->tick(0);
323
324    return true;
325  }
326
327  /**
328   * Level loading method for standalone mode.
329   */
330  bool Orxonox::standaloneLoad()
331  {
332    COUT(2) << "Loading level in standalone mode" << std::endl;
333
334    if (!loadScene())
335      return false;
336
337    return true;
338  }
339
340  /**
341   * Helper method to load a level.
342   */
343  bool Orxonox::loadScene()
344  {
345    Level* startlevel = new Level("levels/sample.oxw");
346    Loader::open(startlevel);
347   
348
349    Ogre::SceneManager* mSceneMgr = GraphicsEngine::getSingleton().getSceneManager();
350    mSceneMgr->setAmbientLight(ColourValue(0.4,0.4,0.4));
351    Ogre::Light* dirlight = mSceneMgr->createLight("Light1");
352
353       dirlight->setType(Ogre::Light::LT_DIRECTIONAL);
354       dirlight->setDirection(Vector3( 0, 1, 5 ));
355       dirlight->setDiffuseColour(ColourValue(0.6, 0.6, 0.4));
356       dirlight->setSpecularColour(ColourValue(1.0, 1.0, 1.0));
357   
358    return true;
359  }
360
361
362  /**
363    Main loop of the orxonox game.
364    About the loop: The design is almost exactly like the one in ogre, so that
365    if any part of ogre registers a framelisteners, it will still behave
366    correctly. Furthermore the time smoothing feature from ogre has been
367    implemented too. If turned on (see orxonox constructor), it will calculate
368    the dt_n by means of the recent most dt_n-1, dt_n-2, etc.
369  */
370  bool Orxonox::startRenderLoop()
371  {
372    // first check whether ogre root object has been created
373    if (Ogre::Root::getSingletonPtr() == 0)
374    {
375      COUT(2) << "Orxonox Error: Could not start rendering. No Ogre root object found" << std::endl;
376      return false;
377    }
378    Ogre::Root& ogreRoot = Ogre::Root::getSingleton();
379
380
381    // Contains the times of recently fired events
382    // eventTimes[4] is the list for the times required for the fps counter
383    std::deque<unsigned long> eventTimes[3];
384    // Clear event times
385    for (int i = 0; i < 3; ++i)
386      eventTimes[i].clear();
387
388    // use the ogre timer class to measure time.
389    if (!timer_)
390      timer_ = new Ogre::Timer();
391    timer_->reset();
392
393    float renderTime = 0.0f;
394    float frameTime = 0.0f;
395    clock_t time = 0;
396
397    //Ogre::SceneManager* mSceneMgr = GraphicsEngine::getSingleton().getSceneManager();
398    //Ogre::Viewport* mViewport = mSceneMgr->getCurrentViewport();
399   
400    //Ogre::CompositorManager::getSingleton().addCompositor(mViewport, "Bloom");
401    //Ogre::CompositorManager::getSingleton().addCompositor(mViewport, "MotionBlur");
402
403    COUT(3) << "Orxonox: Starting the main loop." << std::endl;
404          while (!bAbort_)
405          {
406                  // Pump messages in all registered RenderWindows
407      // This calls the WindowEventListener objects.
408      Ogre::WindowEventUtilities::messagePump();
409
410      // get current time
411      unsigned long now = timer_->getMilliseconds();
412
413      // create an event to pass to the frameStarted method in ogre
414      Ogre::FrameEvent evt;
415      evt.timeSinceLastEvent = calculateEventTime(now, eventTimes[0]);
416      evt.timeSinceLastFrame = calculateEventTime(now, eventTimes[1]);
417      frameTime += evt.timeSinceLastFrame;
418
419      // show the current time in the HUD
420      // HUD::getSingleton().setTime(now);
421      if (frameTime > 0.4f)
422      {
423        HUD::getSingleton().setRenderTimeRatio(renderTime / frameTime);
424        frameTime = 0.0f;
425        renderTime = 0.0f;
426      }
427
428      // Call those objects that need the real time
429      for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
430        it->tick((float)evt.timeSinceLastFrame);
431      // Call the scene objects
432      for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
433        it->tick((float)evt.timeSinceLastFrame * this->timefactor_);
434
435      // don't forget to call _fireFrameStarted in ogre to make sure
436      // everything goes smoothly
437      if(mode_!=DEDICATED)
438        ogreRoot._fireFrameStarted(evt);
439
440      // get current time
441      now = timer_->getMilliseconds();
442      calculateEventTime(now, eventTimes[2]);
443
444      if(mode_!=DEDICATED)
445        ogreRoot._updateAllRenderTargets(); // only render in non-server mode
446
447      // get current time
448      now = timer_->getMilliseconds();
449
450      // create an event to pass to the frameEnded method in ogre
451      evt.timeSinceLastEvent = calculateEventTime(now, eventTimes[0]);
452      renderTime += calculateEventTime(now, eventTimes[2]);
453
454      // again, just to be sure ogre works fine
455      if(mode_!=DEDICATED)
456        ogreRoot._fireFrameEnded(evt);
457          }
458
459    if (mode_==CLIENT)
460      network::Client::getSingleton()->closeConnection();
461    else if (mode_==SERVER)
462      server_g->close();
463
464    return true;
465  }
466
467  /**
468    Method for calculating the average time between recently fired events.
469    Code directly taken from OgreRoot.cc
470    @param now The current time in ms.
471    @param type The type of event to be considered.
472  */
473  float Orxonox::calculateEventTime(unsigned long now, std::deque<unsigned long> &times)
474  {
475    // Calculate the average time passed between events of the given type
476    // during the last frameSmoothingTime_ seconds.
477
478    times.push_back(now);
479
480    if(times.size() == 1)
481      return 0;
482
483    // Times up to frameSmoothingTime_ seconds old should be kept
484    unsigned long discardThreshold = (unsigned long)(frameSmoothingTime_ * 1000.0f);
485
486    // Find the oldest time to keep
487    std::deque<unsigned long>::iterator it  = times.begin();
488    // We need at least two times
489    std::deque<unsigned long>::iterator end = times.end() - 2;
490
491    while(it != end)
492    {
493      if (now - *it > discardThreshold)
494        ++it;
495      else
496        break;
497    }
498
499    // Remove old times
500    times.erase(times.begin(), it);
501
502    return (float)(times.back() - times.front()) / ((times.size() - 1) * 1000);
503  }
504}
Note: See TracBrowser for help on using the repository browser.