Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource2/src/core/Game.cc @ 5651

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

Added using declaration for boost::shared_ptr, weak_ptr and scoped_ptr to OrxonoxConfig.h

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