Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Derived all singletons implemented in a usual manner from orxonox::Singleton<T>.
This resolves inconsistencies with the singletonPtr_s variable in case of exceptions (asserts were being triggered then).
And while at it replaced singletonRef_s with singletonPtr_s for it to be less misleading (as fabian has already pointed out).

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