Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: sandbox/src/libraries/core/Game.cc @ 5782

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

Applied changes to the real sandbox this time.

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