Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/core/Game.cc @ 10690

Last change on this file since 10690 was 10624, checked in by landauf, 9 years ago

merged branch core7 back to trunk

  • Property svn:eol-style set to native
File size: 24.7 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 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29/**
30@file
31@brief
32    Implementation of the Game class.
33*/
34
35#include "Game.h"
36
37#include <exception>
38#include <boost/weak_ptr.hpp>
39#include <loki/ScopeGuard.h>
40
41#include "util/Clock.h"
42#include "util/Output.h"
43#include "util/Exception.h"
44#include "util/Sleep.h"
45#include "util/SubString.h"
46#include "Core.h"
47#include "commandline/CommandLineParser.h"
48#include "GameConfig.h"
49#include "GameMode.h"
50#include "GameState.h"
51#include "GraphicsManager.h"
52#include "GUIManager.h"
53#include "command/ConsoleCommandIncludes.h"
54
55namespace orxonox
56{
57    static void stop_game()
58        { Game::getInstance().stop(); }
59    SetConsoleCommand("exit", &stop_game);
60    static void printFPS()
61        { orxout(message) << Game::getInstance().getAvgFPS() << endl; }
62    SetConsoleCommand("Stats", "printFPS", &printFPS);
63    static void printTickTime()
64        { orxout(message) << Game::getInstance().getAvgTickTime() << endl; }
65    SetConsoleCommand("Stats", "printTickTime", &printTickTime);
66
67    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
68    Game* Game::singletonPtr_s = 0;
69
70    //! Represents one node of the game state tree.
71    struct GameStateTreeNode
72    {
73        std::string name_;
74        weak_ptr<GameStateTreeNode> parent_;
75        std::vector<shared_ptr<GameStateTreeNode> > children_;
76    };
77
78    Game::Game(const std::string& cmdLine)
79        : gameClock_(NULL)
80        , core_(NULL)
81        , bChangingState_(false)
82        , bAbort_(false)
83        , config_(NULL)
84        , destructionHelper_(this)
85    {
86        orxout(internal_status) << "initializing Game object..." << endl;
87
88#ifdef ORXONOX_PLATFORM_WINDOWS
89        minimumSleepTime_ = 1000/*us*/;
90#else
91        minimumSleepTime_ = 0/*us*/;
92#endif
93
94        // reset statistics
95        this->statisticsStartTime_ = 0;
96        this->statisticsTickTimes_.clear();
97        this->periodTickTime_ = 0;
98        this->periodTime_ = 0;
99        this->avgFPS_ = 0.0f;
100        this->avgTickTime_ = 0.0f;
101        this->excessSleepTime_ = 0;
102
103        // Create an empty root state
104        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
105
106        // Set up a basic clock to keep time
107        this->gameClock_ = new Clock();
108
109        // Create the Core
110        orxout(internal_info) << "creating Core object:" << endl;
111        this->core_ = new Core(cmdLine);
112        this->core_->loadModules();
113
114        // Do this after the Core creation!
115        this->config_ = new GameConfig();
116
117        // After the core has been created, we can safely instantiate the GameStates that don't require graphics
118        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
119            it != gameStateDeclarations_s.end(); ++it)
120        {
121            if (!it->second.bGraphicsMode)
122                constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second);
123        }
124
125        // The empty root state is ALWAYS loaded!
126        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
127        this->rootStateNode_->name_ = "emptyRootGameState";
128        this->loadedTopStateNode_ = this->rootStateNode_;
129        this->loadedStates_.push_back(this->getState(rootStateNode_->name_));
130
131        orxout(internal_status) << "finished initializing Game object" << endl;
132    }
133
134    void Game::destroy()
135    {
136        orxout(internal_status) << "destroying Game object..." << endl;
137
138        assert(loadedStates_.size() <= 1); // Just empty root GameState
139        // Destroy all GameStates (shared_ptrs take care of actual destruction)
140        constructedStates_.clear();
141
142        GameStateFactory::getFactories().clear();
143        safeObjectDelete(&config_);
144        if (this->core_)
145            this->core_->unloadModules();
146        safeObjectDelete(&core_);
147        safeObjectDelete(&gameClock_);
148
149        orxout(internal_status) << "finished destroying Game object..." << endl;
150    }
151
152    /**
153    @brief
154        Main loop of the orxonox game.
155    @note
156        We use the Ogre::Timer to measure time since it uses the most precise
157        method an any platform (however the windows timer lacks time when under
158        heavy kernel load!).
159    */
160    void Game::run()
161    {
162        if (this->requestedStateNodes_.empty())
163            orxout(user_error) << "Starting game without requesting GameState. This automatically terminates the program." << endl;
164
165        // Update the GameState stack if required. We do this already here to have a properly initialized game before entering the main loop
166        this->updateGameStateStack();
167
168        orxout(user_status) << "Game loaded" << endl;
169        orxout(internal_status) << "-------------------- starting main loop --------------------" << endl;
170
171        // START GAME
172        // first delta time should be about 0 seconds
173        this->gameClock_->capture();
174        // A first item is required for the fps limiter
175        StatisticsTickInfo tickInfo = {0, 0};
176        statisticsTickTimes_.push_back(tickInfo);
177        while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
178        {
179            // Generate the dt
180            this->gameClock_->capture();
181
182            // Statistics init
183            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
184            statisticsTickTimes_.push_back(tickInfo);
185            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
186
187            // Update the GameState stack if required
188            this->updateGameStateStack();
189
190            // Core preUpdate
191            try
192                { this->core_->preUpdate(*this->gameClock_); }
193            catch (...)
194            {
195                orxout(user_error) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << endl;
196                orxout(user_error) << "This should really never happen! Closing the program." << endl;
197                this->stop();
198                break;
199            }
200
201            // Update the GameStates bottom up in the stack
202            this->updateGameStates();
203
204            // Core postUpdate
205            try
206                { this->core_->postUpdate(*this->gameClock_); }
207            catch (...)
208            {
209                orxout(user_error) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << endl;
210                orxout(user_error) << "This should really never happen! Closing the program." << endl;
211                this->stop();
212                break;
213            }
214
215            // Evaluate statistics
216            this->updateStatistics();
217
218            // Limit frame rate
219            static bool hasVSync = GameMode::showsGraphics() && GraphicsManager::getInstance().hasVSyncEnabled(); // can be static since changes of VSync currently require a restart
220            if (this->config_->getFpsLimit() > 0 && !hasVSync)
221                this->updateFPSLimiter();
222        }
223
224        orxout(internal_status) << "-------------------- finished main loop --------------------" << endl;
225
226        // UNLOAD all remaining states
227        while (this->loadedStates_.size() > 1)
228            this->unloadState(this->loadedStates_.back()->getName());
229        this->loadedTopStateNode_ = this->rootStateNode_;
230        this->requestedStateNodes_.clear();
231    }
232
233    void Game::updateGameStateStack()
234    {
235        while (this->requestedStateNodes_.size() > 0)
236        {
237            shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
238            assert(this->loadedTopStateNode_);
239            if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
240                this->unloadState(loadedTopStateNode_->name_);
241            else // has to be child
242            {
243                try
244                {
245                    this->loadState(requestedStateNode->name_);
246                }
247                catch (...)
248                {
249                    orxout(user_error) << "Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << endl;
250                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
251                    if (this->requestedStateNodes_.size() > 1)
252                        orxout(internal_info) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << endl;
253                    this->requestedStateNodes_.clear();
254                    break;
255                }
256            }
257            this->loadedTopStateNode_ = requestedStateNode;
258            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
259        }
260    }
261
262    void Game::updateGameStates()
263    {
264        // Note: The first element is the empty root state, which doesn't need ticking
265        for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1;
266            it != this->loadedStates_.end(); ++it)
267        {
268            try
269            {
270                // Add tick time for most of the states
271                uint64_t timeBeforeTick = 0;
272                if ((*it)->getInfo().bIgnoreTickTime)
273                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
274                (*it)->update(*this->gameClock_);
275                if ((*it)->getInfo().bIgnoreTickTime)
276                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
277            }
278            catch (...)
279            {
280                orxout(user_error) << "An exception occurred while updating '" << (*it)->getName() << "': " << Exception::handleMessage() << endl;
281                orxout(user_error) << "This should really never happen!" << endl;
282                orxout(user_error) << "Unloading all GameStates depending on the one that crashed." << endl;
283                shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_;
284                while (current->name_ != (*it)->getName() && current)
285                    current = current->parent_.lock();
286                if (current && current->parent_.lock())
287                    this->requestState(current->parent_.lock()->name_);
288                else
289                    this->stop();
290                break;
291            }
292        }
293    }
294
295    void Game::updateStatistics()
296    {
297        // Add the tick time of this frame (rendering time has already been subtracted)
298        uint64_t currentTime = gameClock_->getMicroseconds();
299        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
300        this->statisticsTickTimes_.back().tickLength += (uint32_t)(currentRealTime - currentTime);
301        this->periodTickTime_ += (uint32_t)(currentRealTime - currentTime);
302        if (this->periodTime_ > this->config_->getStatisticsRefreshCycle())
303        {
304            std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
305            assert(it != this->statisticsTickTimes_.end());
306            int64_t lastTime = currentTime - this->config_->getStatisticsAvgLength();
307            if (static_cast<int64_t>(it->tickTime) < lastTime)
308            {
309                do
310                {
311                    assert(this->periodTickTime_ >= it->tickLength);
312                    this->periodTickTime_ -= it->tickLength;
313                    ++it;
314                    assert(it != this->statisticsTickTimes_.end());
315                } while (static_cast<int64_t>(it->tickTime) < lastTime);
316                this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
317            }
318
319            uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
320            // Why minus 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too low
321            this->avgFPS_ = -1 + static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
322            this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
323
324            this->periodTime_ -= this->config_->getStatisticsRefreshCycle();
325        }
326    }
327
328    void Game::updateFPSLimiter()
329    {
330        uint64_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / this->config_->getFpsLimit());
331        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
332        while (currentRealTime < nextTime - minimumSleepTime_)
333        {
334            usleep((unsigned long)(nextTime - currentRealTime));
335            currentRealTime = gameClock_->getRealMicroseconds();
336        }
337        // Integrate excess to avoid steady state error
338        excessSleepTime_ = (int)(currentRealTime - nextTime);
339        // Anti windup
340        if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
341            excessSleepTime_ = 50000;
342    }
343
344    void Game::stop()
345    {
346        orxout(user_status) << "Exit" << endl;
347        this->bAbort_ = true;
348    }
349
350    void Game::subtractTickTime(int32_t length)
351    {
352        assert(!this->statisticsTickTimes_.empty());
353        this->statisticsTickTimes_.back().tickLength -= length;
354        this->periodTickTime_ -= length;
355    }
356
357
358    /***** GameState related *****/
359
360    void Game::requestState(const std::string& name)
361    {
362        if (!this->checkState(name))
363        {
364            orxout(user_warning) << "GameState named '" << name << "' doesn't exist!" << endl;
365            return;
366        }
367
368        if (this->bChangingState_)
369        {
370            orxout(user_warning) << "Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << endl;
371            return;
372        }
373
374        shared_ptr<GameStateTreeNode> lastRequestedNode;
375        if (this->requestedStateNodes_.empty())
376            lastRequestedNode = this->loadedTopStateNode_;
377        else
378            lastRequestedNode = this->requestedStateNodes_.back();
379        if (name == lastRequestedNode->name_)
380        {
381            orxout(user_warning) << "Requesting the currently active state! Ignoring." << endl;
382            return;
383        }
384
385        // Check children first
386        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
387        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
388        {
389            if (lastRequestedNode->children_[i]->name_ == name)
390            {
391                requestedNodes.push_back(lastRequestedNode->children_[i]);
392                break;
393            }
394        }
395
396        if (requestedNodes.empty())
397        {
398            // Check parent and all its grand parents
399            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
400            while (currentNode != NULL)
401            {
402                if (currentNode->name_ == name)
403                    break;
404                currentNode = currentNode->parent_.lock();
405                requestedNodes.push_back(currentNode);
406            }
407            if (currentNode == NULL)
408                requestedNodes.clear();
409        }
410
411        if (requestedNodes.empty())
412            orxout(user_error) << "Requested GameState transition is not allowed. Ignoring." << endl;
413        else
414            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
415    }
416
417    void Game::requestStates(const std::string& names)
418    {
419        SubString tokens(names, ",;", " ");
420        for (unsigned int i = 0; i < tokens.size(); ++i)
421            this->requestState(tokens[i]);
422    }
423
424    void Game::popState()
425    {
426        shared_ptr<GameStateTreeNode> lastRequestedNode;
427        if (this->requestedStateNodes_.empty())
428            lastRequestedNode = this->loadedTopStateNode_;
429        else
430            lastRequestedNode = this->requestedStateNodes_.back();
431        if (lastRequestedNode != this->rootStateNode_)
432            this->requestState(lastRequestedNode->parent_.lock()->name_);
433        else
434            orxout(internal_warning) << "Can't pop the internal dummy root GameState" << endl;
435    }
436
437    shared_ptr<GameState> Game::getState(const std::string& name)
438    {
439        GameStateMap::const_iterator it = constructedStates_.find(name);
440        if (it != constructedStates_.end())
441            return it->second;
442        else
443        {
444            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
445            if (it != gameStateDeclarations_s.end())
446                orxout(internal_error) << "GameState '" << name << "' has not yet been loaded." << endl;
447            else
448                orxout(internal_error) << "Could not find GameState '" << name << "'." << endl;
449            return shared_ptr<GameState>();
450        }
451    }
452
453    void Game::setStateHierarchy(const std::string& str)
454    {
455        // Split string into pieces of the form whitespacesText
456        std::vector<std::pair<std::string, int> > stateStrings;
457        size_t pos = 0;
458        size_t startPos = 0;
459        while (pos < str.size())
460        {
461            int indentation = 0;
462            while (pos < str.size() && str[pos] == ' ')
463                ++indentation, ++pos;
464            startPos = pos;
465            while (pos < str.size() && str[pos] != ' ')
466                ++pos;
467            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
468        }
469        if (stateStrings.empty())
470            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
471        // Add element with large identation to detect the last with just an iterator
472        stateStrings.push_back(std::make_pair(std::string(), -1));
473
474        // Parse elements recursively
475        std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
476        parseStates(begin, this->rootStateNode_);
477    }
478
479    /*** Internal ***/
480
481    void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
482    {
483        SubString tokens(it->first, ",");
484        std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
485
486        for (unsigned int i = 0; i < tokens.size(); ++i)
487        {
488            it = startIt; // Reset iterator to the beginning of the sub tree
489            if (!this->checkState(tokens[i]))
490                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
491            if (tokens[i] == this->rootStateNode_->name_)
492                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
493            shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
494            node->name_ = tokens[i];
495            node->parent_ = currentNode;
496            currentNode->children_.push_back(node);
497
498            int currentLevel = it->second;
499            ++it;
500            while (it->second != -1)
501            {
502                if (it->second <= currentLevel)
503                    break;
504                else if (it->second == currentLevel + 1)
505                    parseStates(it, node);
506                else
507                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
508            }
509        }
510    }
511
512    void Game::loadGraphics()
513    {
514        if (!GameMode::showsGraphics())
515        {
516            orxout(user_status) << "Loading graphics" << endl;
517            orxout(internal_info) << "loading graphics in Game" << endl;
518
519            core_->loadGraphics();
520            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true);
521
522            // Construct all the GameStates that require graphics
523            for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
524                it != gameStateDeclarations_s.end(); ++it)
525            {
526                if (it->second.bGraphicsMode)
527                {
528                    // Game state loading failure is serious --> don't catch
529                    shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second);
530                    if (!constructedStates_.insert(std::make_pair(
531                        it->second.stateName, gameState)).second)
532                        assert(false); // GameState was already created!
533                }
534            }
535            graphicsUnloader.Dismiss();
536
537            orxout(internal_info) << "finished loading graphics in Game" << endl;
538        }
539    }
540
541    void Game::unloadGraphics(bool loadGraphicsManagerWithoutRenderer)
542    {
543        if (GameMode::showsGraphics())
544        {
545            orxout(user_status) << "Unloading graphics" << endl;
546            orxout(internal_info) << "unloading graphics in Game" << endl;
547
548            // Destroy all the GameStates that require graphics
549            for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
550            {
551                if (it->second->getInfo().bGraphicsMode)
552                    constructedStates_.erase(it++);
553                else
554                    ++it;
555            }
556
557            core_->unloadGraphics(loadGraphicsManagerWithoutRenderer);
558        }
559    }
560
561    bool Game::checkState(const std::string& name) const
562    {
563        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
564        if (it == gameStateDeclarations_s.end())
565            return false;
566        else
567            return true;
568    }
569
570    void Game::loadState(const std::string& name)
571    {
572        orxout(internal_status) << "loading state '" << name << "'" << endl;
573
574        this->bChangingState_ = true;
575        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState); (void)LOKI_ANONYMOUS_VARIABLE(scopeGuard);
576
577        // If state requires graphics, load it
578        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics, true);
579        if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
580            this->loadGraphics();
581        else
582            graphicsUnloader.Dismiss();
583
584        shared_ptr<GameState> state = this->getState(name);
585        state->activateInternal();
586        if (!this->loadedStates_.empty())
587            this->loadedStates_.back()->activity_.topState = false;
588        this->loadedStates_.push_back(state);
589        state->activity_.topState = true;
590
591        graphicsUnloader.Dismiss();
592    }
593
594    void Game::unloadState(const std::string& name)
595    {
596        orxout(internal_status) << "unloading state '" << name << "'" << endl;
597
598        this->bChangingState_ = true;
599        try
600        {
601            shared_ptr<GameState> state = this->getState(name);
602            state->activity_.topState = false;
603            this->loadedStates_.pop_back();
604            if (!this->loadedStates_.empty())
605                this->loadedStates_.back()->activity_.topState = true;
606            state->deactivateInternal();
607        }
608        catch (...)
609        {
610            orxout(internal_warning) << "Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << endl;
611            orxout(internal_warning) << "There might be potential resource leaks involved! To avoid this, improve exception-safety." << endl;
612        }
613        // Check if graphics is still required
614        bool graphicsRequired = false;
615        for (unsigned i = 0; i < loadedStates_.size(); ++i)
616            graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
617        if (!graphicsRequired)
618            this->unloadGraphics(!this->bAbort_); // if abort is false, that means the game is still running while unloading graphics. in this case we load a graphics manager without renderer (to keep all necessary ogre instances alive)
619        this->bChangingState_ = false;
620    }
621
622    /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories()
623    {
624        static std::map<std::string, shared_ptr<GameStateFactory> > factories;
625        return factories;
626    }
627
628    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
629    {
630        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
631        assert(it != getFactories().end());
632        return it->second->fabricateInternal(info);
633    }
634}
Note: See TracBrowser for help on using the repository browser.