Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource/src/core/Game.cc @ 3355

Last change on this file since 3355 was 3355, checked in by rgrieder, 15 years ago

Loading and unloading graphics automatically: As soon as a GameState requires graphics (defined at the GameState declaration with a bool) it gets loaded. And vice versa.

  • Property svn:eol-style set to native
File size: 21.0 KB
RevLine 
[2805]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>
[3196]38#include <boost/weak_ptr.hpp>
[2805]39
40#include "util/Debug.h"
41#include "util/Exception.h"
[3304]42#include "util/Sleep.h"
[2850]43#include "util/SubString.h"
[2844]44#include "Clock.h"
45#include "CommandLine.h"
46#include "ConsoleCommand.h"
47#include "Core.h"
48#include "CoreIncludes.h"
49#include "ConfigValueIncludes.h"
[3355]50#include "GameMode.h"
[2844]51#include "GameState.h"
[2805]52
53namespace orxonox
54{
[3196]55    using boost::shared_ptr;
56    using boost::weak_ptr;
57
[2845]58    static void stop_game()
59        { Game::getInstance().stop(); }
60    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
[2805]61
[3355]62    std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
[3280]63    Game* Game::singletonRef_s = 0;
64
65
66    /**
67    @brief
68        Represents one node of the game state tree.
69    */
70    struct GameStateTreeNode
[2844]71    {
[3196]72        GameState* state_;
73        weak_ptr<GameStateTreeNode> parent_;
74        std::vector<shared_ptr<GameStateTreeNode> > children_;
[2844]75    };
76
[2805]77
78    /**
79    @brief
[3280]80        Another helper class for the Game singleton: we cannot derive
81        Game from OrxonoxClass because we need to handle the Identifier
82        destruction in the Core destructor.
83    */
84    class GameConfiguration : public OrxonoxClass
85    {
86    public:
87        GameConfiguration()
88        {
89            RegisterRootObject(GameConfiguration);
90            this->setConfigValues();
91        }
92
93        void setConfigValues()
94        {
95            SetConfigValue(statisticsRefreshCycle_, 250000)
96                .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
97            SetConfigValue(statisticsAvgLength_, 1000000)
98                .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
[3304]99            SetConfigValue(fpsLimit_, 50)
100                .description("Sets the desired framerate (0 for no limit).");
[3280]101        }
102
103        unsigned int statisticsRefreshCycle_;
104        unsigned int statisticsAvgLength_;
[3304]105        unsigned int fpsLimit_;
[3280]106    };
107
108
109    /**
110    @brief
[2805]111        Non-initialising constructor.
112    */
[3323]113    Game::Game(const std::string& cmdLine)
[2805]114    {
[3280]115        if (singletonRef_s != 0)
116        {
117            COUT(0) << "Error: The Game singleton cannot be recreated! Shutting down." << std::endl;
118            abort();
119        }
[2805]120        singletonRef_s = this;
121
[3280]122        this->bAbort_ = false;
123        bChangingState_ = false;
[2805]124
[3352]125#ifdef ORXONOX_PLATFORM_WINDOWS
126        minimumSleepTime_ = 1000/*us*/;
127#else
128        minimumSleepTime_ = 0/*us*/;
129#endif
130
[3280]131        // Create an empty root state
[3352]132        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
[3280]133
[2846]134        // Set up a basic clock to keep time
135        this->gameClock_ = new Clock();
136
[3280]137        // Create the Core
[3323]138        this->core_ = new Core(cmdLine);
[2817]139
[3280]140        // After the core has been created, we can safely instantiate the GameStates
141        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
142            it != gameStateDeclarations_s.end(); ++it)
143        {
144            // Only create the states appropriate for the game mode
145            //if (GameMode::showsGraphics || !it->second.bGraphicsMode)
[3355]146            gameStates_[getLowercase(it->second.stateName)] = GameStateFactory::fabricate(it->second);
[3280]147        }
148
149        // The empty root state is ALWAYS loaded!
150        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
151        this->rootStateNode_->state_ = getState("emptyRootGameState");
152        this->activeStateNode_ = this->rootStateNode_;
153        this->activeStates_.push_back(this->rootStateNode_->state_);
154
155        // Do this after the Core creation!
156        this->configuration_ = new GameConfiguration();
[2805]157    }
158
159    /**
160    @brief
161    */
162    Game::~Game()
163    {
[3280]164        // Destroy the configuration helper class instance
165        delete this->configuration_;
166
167        // Destroy the GameStates (note that the nodes still point to them, but doesn't matter)
168        for (std::map<std::string, GameState*>::const_iterator it = gameStates_.begin();
169            it != gameStates_.end(); ++it)
170            delete it->second;
171
172        // Destroy the Core and with it almost everything
[2805]173        delete this->core_;
[2846]174        delete this->gameClock_;
175
[3280]176        // Take care of the GameStateFactories
177        GameStateFactory::destroyFactories();
[2805]178
[3280]179        // Don't assign singletonRef_s with NULL! Recreation is not supported
[2817]180    }
181
[2805]182    /**
183    @brief
184        Main loop of the orxonox game.
185    @note
186        We use the Ogre::Timer to measure time since it uses the most precise
187        method an any platform (however the windows timer lacks time when under
188        heavy kernel load!).
189    */
190    void Game::run()
191    {
[3280]192        if (this->requestedStateNodes_.empty())
193            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
[2805]194
[3352]195        // reset statistics
196        this->statisticsStartTime_ = 0;
197        this->statisticsTickTimes_.clear();
198        this->periodTickTime_ = 0;
199        this->periodTime_ = 0;
200        this->avgFPS_ = 0.0f;
201        this->avgTickTime_ = 0.0f;
202        this->excessSleepTime_ = 0;
203
[2845]204        // START GAME
[3304]205        // first delta time should be about 0 seconds
206        this->gameClock_->capture();
207        // A first item is required for the fps limiter
208        StatisticsTickInfo tickInfo = {0, 0};
209        statisticsTickTimes_.push_back(tickInfo);
[3280]210        while (!this->bAbort_ && (!this->activeStates_.empty() || this->requestedStateNodes_.size() > 0))
[2805]211        {
[3352]212            // Generate the dt
[2807]213            this->gameClock_->capture();
[2805]214
[3352]215            // Statistics init
216            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
[2817]217            statisticsTickTimes_.push_back(tickInfo);
218            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
219
[3352]220            // Update the GameState stack if required
221            this->updateGameStateStack();
222
223            // Core preUpdate (doesn't throw)
224            if (!this->core_->preUpdate(*this->gameClock_))
[2844]225            {
[3352]226                this->stop();
227                break;
[2844]228            }
[2805]229
[3352]230            // Update the GameStates bottom up in the stack
231            this->updateGameStates();
232
233            // Core postUpdate (doesn't throw)
234            if (!this->core_->postUpdate(*this->gameClock_))
[3280]235            {
236                this->stop();
237                break;
238            }
239
[3352]240            // Evaluate statistics
241            this->updateStatistics();
242
243            // Limit framerate
244            this->updateFPSLimiter();
245        }
246
247        // UNLOAD all remaining states
248        while (this->activeStates_.size() > 1)
249            this->unloadState(this->activeStates_.back());
250        this->activeStateNode_ = this->rootStateNode_;
251        this->requestedStateNodes_.clear();
252    }
253
254    void Game::updateGameStateStack()
255    {
256        while (this->requestedStateNodes_.size() > 0)
257        {
258            shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
259            assert(this->activeStateNode_);
260            if (!this->activeStateNode_->parent_.expired() && requestedStateNode == this->activeStateNode_->parent_.lock())
261                this->unloadState(this->activeStateNode_->state_);
262            else // has to be child
[3084]263            {
[3280]264                try
265                {
[3352]266                    this->loadState(requestedStateNode->state_);
[3280]267                }
268                catch (const std::exception& ex)
269                {
[3352]270                    COUT(1) << "Error: Loading GameState '" << requestedStateNode->state_->getName() << "' failed: " << ex.what() << std::endl;
271                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
272                    if (this->requestedStateNodes_.size() > 1)
273                        COUT(1) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
274                    this->requestedStateNodes_.clear();
[3280]275                    break;
276                }
[3084]277            }
[3352]278            this->activeStateNode_ = requestedStateNode;
279            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
280        }
281    }
[3084]282
[3352]283    void Game::updateGameStates()
284    {
285        // Note: The first element is the empty root state, which doesn't need ticking
286        for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin() + 1;
287            it != this->activeStates_.end(); ++it)
288        {
289            std::string exceptionMessage;
290            try
[3349]291            {
[3352]292                // Add tick time for most of the states
293                uint64_t timeBeforeTick;
[3355]294                if ((*it)->getInfo().bIgnoreTickTime)
[3352]295                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
296                (*it)->update(*this->gameClock_);
[3355]297                if ((*it)->getInfo().bIgnoreTickTime)
[3352]298                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
299            }
300            catch (const std::exception& ex)
301            { exceptionMessage = ex.what(); }
302            catch (...)
303            { exceptionMessage = "Unknown exception"; }
304            if (!exceptionMessage.empty())
305            {
306                COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << exceptionMessage << std::endl;
307                COUT(1) << "This should really never happen!" << std::endl;
308                COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
309                if ((*it)->getParent() != NULL)
310                    this->requestState((*it)->getParent()->getName());
311                else
312                    this->stop();
[3349]313                break;
314            }
[3352]315        }
316    }
[3349]317
[3352]318    void Game::updateStatistics()
319    {
320        // Add the tick time of this frame (rendering time has already been subtracted)
321        uint64_t currentTime = gameClock_->getMicroseconds();
322        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
323        this->statisticsTickTimes_.back().tickLength += currentRealTime - currentTime;
324        this->periodTickTime_ += currentRealTime - currentTime;
325        if (this->periodTime_ > this->configuration_->statisticsRefreshCycle_)
326        {
327            std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
328            assert(it != this->statisticsTickTimes_.end());
329            int64_t lastTime = currentTime - this->configuration_->statisticsAvgLength_;
330            if (static_cast<int64_t>(it->tickTime) < lastTime)
[2817]331            {
[3352]332                do
[2817]333                {
[3352]334                    assert(this->periodTickTime_ >= it->tickLength);
335                    this->periodTickTime_ -= it->tickLength;
336                    ++it;
337                    assert(it != this->statisticsTickTimes_.end());
338                } while (static_cast<int64_t>(it->tickTime) < lastTime);
339                this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
340            }
[2817]341
[3352]342            uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
343            this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
344            this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
[2817]345
[3352]346            this->periodTime_ -= this->configuration_->statisticsRefreshCycle_;
[2805]347        }
[3352]348    }
[2805]349
[3352]350    void Game::updateFPSLimiter()
351    {
352        // Why configuration_->fpsLimit_ - 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too high
353        uint32_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / (configuration_->fpsLimit_ - 1));
354        uint64_t currentRealTime = gameClock_->getRealMicroseconds();
355        while (currentRealTime < nextTime - minimumSleepTime_)
356        {
357            usleep(nextTime - currentRealTime);
358            currentRealTime = gameClock_->getRealMicroseconds();
359        }
360        // Integrate excess to avoid steady state error
361        excessSleepTime_ = currentRealTime - nextTime;
362        // Anti windup
363        if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long
364            excessSleepTime_ = 50000;
[2805]365    }
366
367    void Game::stop()
368    {
[3280]369        this->bAbort_ = true;
[2805]370    }
[2817]371
[3349]372    void Game::subtractTickTime(int32_t length)
[2817]373    {
374        assert(!this->statisticsTickTimes_.empty());
[3349]375        this->statisticsTickTimes_.back().tickLength -= length;
376        this->periodTickTime_ -= length;
[2817]377    }
[2844]378
379
380    /***** GameState related *****/
381
382    void Game::requestState(const std::string& name)
383    {
384        GameState* state = this->getState(name);
[3280]385        if (state == NULL)
[2844]386            return;
387
[3280]388        //if (this->bChangingState_)
389        //{
390        //    COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
391        //    return;
392        //}
[2844]393
[3280]394        shared_ptr<GameStateTreeNode> lastRequestedNode;
395        if (this->requestedStateNodes_.empty())
396            lastRequestedNode = this->activeStateNode_;
397        else
398            lastRequestedNode = this->requestedStateNodes_.back();
[2844]399        if (state == lastRequestedNode->state_)
400        {
401            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
402            return;
403        }
404
405        // Check children first
[3280]406        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
[2844]407        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
408        {
409            if (lastRequestedNode->children_[i]->state_ == state)
410            {
[3280]411                requestedNodes.push_back(lastRequestedNode->children_[i]);
[2844]412                break;
413            }
414        }
415
[3280]416        if (requestedNodes.empty())
[2844]417        {
[3280]418            // Check parent and all its grand parents
419            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
420            while (currentNode != NULL)
421            {
422                if (currentNode->state_ == state)
423                    break;
424                currentNode = currentNode->parent_.lock();
425                requestedNodes.push_back(currentNode);
426            }
[2844]427        }
428
[3280]429        if (requestedNodes.empty())
[2844]430            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
431        else
[3280]432            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
[2844]433    }
434
[2850]435    void Game::requestStates(const std::string& names)
436    {
437        SubString tokens(names, ",;", " ");
438        for (unsigned int i = 0; i < tokens.size(); ++i)
439            this->requestState(tokens[i]);
440    }
441
[2844]442    void Game::popState()
443    {
[3280]444        shared_ptr<GameStateTreeNode> lastRequestedNode;
445        if (this->requestedStateNodes_.empty())
446            lastRequestedNode = this->activeStateNode_;
[2844]447        else
[3280]448            lastRequestedNode = this->requestedStateNodes_.back();
449        if (lastRequestedNode != this->rootStateNode_)
450            this->requestState(lastRequestedNode->parent_.lock()->state_->getName());
451        else
452            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
[2844]453    }
454
455    GameState* Game::getState(const std::string& name)
456    {
[3280]457        std::map<std::string, GameState*>::const_iterator it = gameStates_.find(getLowercase(name));
458        if (it != gameStates_.end())
[2844]459            return it->second;
460        else
461        {
462            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
463            return 0;
464        }
465    }
466
467    void Game::setStateHierarchy(const std::string& str)
468    {
469        // Split string into pieces of the form whitespacesText
470        std::vector<std::pair<std::string, unsigned> > stateStrings;
471        size_t pos = 0;
472        size_t startPos = 0;
473        while (pos < str.size())
474        {
475            unsigned indentation = 0;
476            while(pos < str.size() && str[pos] == ' ')
477                ++indentation, ++pos;
478            startPos = pos;
479            while(pos < str.size() && str[pos] != ' ')
480                ++pos;
[3280]481            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
[2844]482        }
483        unsigned int currentLevel = 0;
[3280]484        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
[2844]485        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
486        {
487            std::string newStateName = it->first;
[3280]488            unsigned newLevel = it->second + 1; // empty root is 0
[2844]489            GameState* newState = this->getState(newStateName);
490            if (!newState)
[3280]491                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
492            if (newState == this->rootStateNode_->state_)
493                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
494            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
495            newNode->state_ = newState;
496
497            if (newLevel <= currentLevel)
[2844]498            {
[3280]499                do
500                    currentNode = currentNode->parent_.lock();
501                while (newLevel <= --currentLevel);
[2844]502            }
[3280]503            if (newLevel == currentLevel + 1)
[2844]504            {
[3280]505                // Add the child
506                newNode->parent_ = currentNode;
507                currentNode->children_.push_back(newNode);
508                currentNode->state_->addChild(newNode->state_);
[2844]509            }
510            else
[3280]511                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
512            currentNode = newNode;
513            currentLevel = newLevel;
[2844]514        }
515    }
516
517    /*** Internal ***/
518
[3355]519    void Game::loadGraphics()
520    {
521        if (!GameMode::bShowsGraphics_s)
522        {
523            core_->loadGraphics();
524            GameMode::bShowsGraphics_s = true;
525        }
526    }
527
528    void Game::unloadGraphics()
529    {
530        if (GameMode::bShowsGraphics_s)
531        {
532            core_->unloadGraphics();
533            GameMode::bShowsGraphics_s = false;
534        }
535    }
536
[2844]537    void Game::loadState(GameState* state)
538    {
[3280]539        this->bChangingState_ = true;
[3355]540        // If state requires graphics, load it
541        if (state->getInfo().bGraphicsMode)
542            this->loadGraphics();
[3280]543        state->activate();
[2850]544        if (!this->activeStates_.empty())
545            this->activeStates_.back()->activity_.topState = false;
[3280]546        this->activeStates_.push_back(state);
[2850]547        state->activity_.topState = true;
[3280]548        this->bChangingState_ = false;
[2844]549    }
550
551    void Game::unloadState(orxonox::GameState* state)
552    {
[3280]553        this->bChangingState_ = true;
[2850]554        state->activity_.topState = false;
[2844]555        this->activeStates_.pop_back();
[2850]556        if (!this->activeStates_.empty())
557            this->activeStates_.back()->activity_.topState = true;
[3280]558        try
559        {
560            state->deactivate();
[3355]561            // Check if graphis is still required
562            bool graphicsRequired = false;
563            for (unsigned i = 0; i < activeStates_.size(); ++i)
564                graphicsRequired |= activeStates_[i]->getInfo().bGraphicsMode;
565            if (!graphicsRequired)
566                this->unloadGraphics();
[3280]567        }
568        catch (const std::exception& ex)
569        {
570            COUT(2) << "Warning: Unloading GameState '" << state->getName() << "' threw an exception: " << ex.what() << std::endl;
571            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
572        }
573        this->bChangingState_ = false;
[2844]574    }
575
[3280]576    std::map<std::string, Game::GameStateFactory*> Game::GameStateFactory::factories_s;
577
[3355]578    /*static*/ GameState* Game::GameStateFactory::fabricate(const GameStateInfo& info)
[2844]579    {
[3355]580        std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.find(info.className);
[3280]581        assert(it != factories_s.end());
[3355]582        return it->second->fabricateInternal(info);
[2844]583    }
[2927]584
[3280]585    /*static*/ void Game::GameStateFactory::destroyFactories()
[2927]586    {
[3280]587        for (std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.begin(); it != factories_s.end(); ++it)
[2927]588            delete it->second;
[3280]589        factories_s.clear();
[2927]590    }
[2805]591}
Note: See TracBrowser for help on using the repository browser.