Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/core/Game.cc @ 3238

Last change on this file since 3238 was 3238, checked in by rgrieder, 16 years ago

Improved exception-safety in the Game class and fixed some issues and bugs resulting from the changes.

  • Property svn:eol-style set to native
File size: 16.8 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/SubString.h"
43#include "Clock.h"
44#include "CommandLine.h"
45#include "ConsoleCommand.h"
46#include "Core.h"
47#include "CoreIncludes.h"
48#include "ConfigValueIncludes.h"
49#include "GameState.h"
50
51namespace orxonox
52{
53    using boost::shared_ptr;
54    using boost::weak_ptr;
55
56    std::map<std::string, GameState*> Game::allStates_s;
57    Game* Game::singletonRef_s = 0;
58
59    static void stop_game()
60        { Game::getInstance().stop(); }
61    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
62    // Add an empty gamestate that serves as internal root state
63    AddGameState(GameState, "emptyRootGameState");
64
65    struct _CoreExport GameStateTreeNode
66    {
67        GameState* state_;
68        weak_ptr<GameStateTreeNode> parent_;
69        std::vector<shared_ptr<GameStateTreeNode> > children_;
70    };
71
72    /**
73    @brief
74        Non-initialising constructor.
75    */
76    Game::Game(int argc, char** argv)
77    {
78        assert(singletonRef_s == 0);
79        singletonRef_s = this;
80
81        this->bAbort_ = false;
82        bChangingState_ = false;
83        // The empty root state is ALWAYS loaded!
84        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
85        this->rootStateNode_->state_ = getState("emptyRootGameState");
86        this->activeStateNode_ = this->rootStateNode_;
87        this->activeStates_.push_back(this->rootStateNode_->state_);
88
89        // reset statistics
90        this->statisticsStartTime_ = 0;
91        this->statisticsTickTimes_.clear();
92        this->periodTickTime_ = 0;
93        this->periodTime_ = 0;
94        this->avgFPS_ = 0.0f;
95        this->avgTickTime_ = 0.0f;
96
97        // Set up a basic clock to keep time
98        this->gameClock_ = new Clock();
99
100        this->core_ = new orxonox::Core();
101        this->core_->initialise(argc, argv);
102
103        RegisterRootObject(Game);
104        this->setConfigValues();
105    }
106
107    /**
108    @brief
109    */
110    Game::~Game()
111    {
112        // Destroy pretty much everyhting left
113        delete this->core_;
114
115        delete this->gameClock_;
116
117        assert(singletonRef_s);
118        singletonRef_s = 0;
119    }
120
121    void Game::setConfigValues()
122    {
123        SetConfigValue(statisticsRefreshCycle_, 250000)
124            .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
125        SetConfigValue(statisticsAvgLength_, 1000000)
126            .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
127        SetConfigValue(levelName_, "presentation_dm.oxw")
128            .description("Sets the preselection of the level in the main menu.");
129    }
130
131    void Game::setLevel(std::string levelName)
132    {
133        ModifyConfigValue(levelName_, set, levelName);
134    }
135
136    std::string Game::getLevel()
137    {
138        std::string levelName;
139        CommandLine::getValue("level", &levelName);
140        if (levelName == "")
141            return levelName_;
142        else
143            return levelName;
144    }
145
146    /**
147    @brief
148        Main loop of the orxonox game.
149    @note
150        We use the Ogre::Timer to measure time since it uses the most precise
151        method an any platform (however the windows timer lacks time when under
152        heavy kernel load!).
153    */
154    void Game::run()
155    {
156        if (this->requestedStateNodes_.empty())
157            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
158
159        // START GAME
160        this->gameClock_->capture(); // first delta time should be about 0 seconds
161        while (!this->bAbort_ && (!this->activeStates_.empty() || this->requestedStateNodes_.size() > 0))
162        {
163            this->gameClock_->capture();
164            uint64_t currentTime = this->gameClock_->getMicroseconds();
165
166            // STATISTICS
167            statisticsTickInfo tickInfo = {currentTime, 0};
168            statisticsTickTimes_.push_back(tickInfo);
169            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
170
171            // UPDATE STATE STACK
172            while (this->requestedStateNodes_.size() > 0)
173            {
174                shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
175                assert(this->activeStateNode_);
176                if (!this->activeStateNode_->parent_.expired() && requestedStateNode == this->activeStateNode_->parent_.lock())
177                    this->unloadState(this->activeStateNode_->state_);
178                else // has to be child
179                {
180                    try
181                    {
182                        this->loadState(requestedStateNode->state_);
183                    }
184                    catch (const std::exception& ex)
185                    {
186                        COUT(1) << "Error: Loading GameState '" << requestedStateNode->state_->getName() << "' failed: " << ex.what() << std::endl;
187                        // All scheduled operations have now been rendered inert --> flush them and issue a warning
188                        if (this->requestedStateNodes_.size() > 1)
189                            COUT(1) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
190                        this->requestedStateNodes_.clear();
191                        break;
192                    }
193                }
194                this->activeStateNode_ = requestedStateNode;
195                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
196            }
197
198            // UPDATE, Core first
199            try
200            {
201                this->core_->update(*this->gameClock_);
202            }
203            catch (...)
204            {
205                COUT(0) << "An exception occured while ticking the Core. This should really never happen!" << std::endl;
206                COUT(0) << "Closing the program." << std::endl;
207                this->stop();
208                break;
209            }
210
211            // UPDATE, GameStates bottom to top in the stack
212            // Note: The first element is the empty root state, which doesn't need ticking
213            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin() + 1;
214                it != this->activeStates_.end(); ++it)
215            {
216                try
217                {
218                    // Add tick time for most of the states
219                    uint64_t timeBeforeTick;
220                    if (!(*it)->ignoreTickTime())
221                        timeBeforeTick = this->gameClock_->getRealMicroseconds();
222                    (*it)->update(*this->gameClock_);
223                    if (!(*it)->ignoreTickTime())
224                        this->addTickTime(static_cast<uint32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
225                }
226                catch (...)
227                {
228                    COUT(1) << "An exception occured while ticking GameState '" << (*it)->getName() << "'. This should really never happen!" << std::endl;
229                    COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
230                    if ((*it)->getParent() != NULL)
231                        this->requestState((*it)->getParent()->getName());
232                    else
233                        this->stop();
234                    break;
235                }
236
237            }
238
239            // STATISTICS
240            if (this->periodTime_ > statisticsRefreshCycle_)
241            {
242                std::list<statisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
243                assert(it != this->statisticsTickTimes_.end());
244                int64_t lastTime = currentTime - this->statisticsAvgLength_;
245                if ((int64_t)it->tickTime < lastTime)
246                {
247                    do
248                    {
249                        assert(this->periodTickTime_ >= it->tickLength);
250                        this->periodTickTime_ -= it->tickLength;
251                        ++it;
252                        assert(it != this->statisticsTickTimes_.end());
253                    } while ((int64_t)it->tickTime < lastTime);
254                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
255                }
256
257                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
258                this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
259                this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
260
261                this->periodTime_ -= this->statisticsRefreshCycle_;
262            }
263        }
264
265        // UNLOAD all remaining states
266        while (this->activeStates_.size() > 1)
267            this->unloadState(this->activeStates_.back());
268        this->activeStateNode_ = this->rootStateNode_;
269        this->requestedStateNodes_.clear();
270    }
271
272    void Game::stop()
273    {
274        this->bAbort_ = true;
275    }
276
277    void Game::addTickTime(uint32_t length)
278    {
279        assert(!this->statisticsTickTimes_.empty());
280        this->statisticsTickTimes_.back().tickLength += length;
281        this->periodTickTime_+=length;
282    }
283
284
285    /***** GameState related *****/
286
287    void Game::requestState(const std::string& name)
288    {
289        GameState* state = this->getState(name);
290        if (state == NULL)
291            return;
292
293        //if (this->bChangingState_)
294        //{
295        //    COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
296        //    return;
297        //}
298
299        shared_ptr<GameStateTreeNode> lastRequestedNode;
300        if (this->requestedStateNodes_.empty())
301            lastRequestedNode = this->activeStateNode_;
302        else
303            lastRequestedNode = this->requestedStateNodes_.back();
304        if (state == lastRequestedNode->state_)
305        {
306            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
307            return;
308        }
309
310        // Check children first
311        shared_ptr<GameStateTreeNode> requestedNode;
312        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
313        {
314            if (lastRequestedNode->children_[i]->state_ == state)
315            {
316                requestedNode = lastRequestedNode->children_[i];
317                break;
318            }
319        }
320
321        // Check parent and all its grand parents
322        shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
323        while (requestedNode == NULL && currentNode != NULL)
324        {
325            if (currentNode->state_ == state)
326                requestedNode = currentNode;
327            currentNode = currentNode->parent_.lock();
328        }
329
330        if (requestedNode == NULL)
331            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
332        else
333            this->requestedStateNodes_.push_back(requestedNode);
334    }
335
336    void Game::requestStates(const std::string& names)
337    {
338        SubString tokens(names, ",;", " ");
339        for (unsigned int i = 0; i < tokens.size(); ++i)
340            this->requestState(tokens[i]);
341    }
342
343    void Game::popState()
344    {
345        shared_ptr<GameStateTreeNode> lastRequestedNode;
346        if (this->requestedStateNodes_.empty())
347            lastRequestedNode = this->activeStateNode_;
348        else
349            lastRequestedNode = this->requestedStateNodes_.back();
350        if (lastRequestedNode != this->rootStateNode_)
351            this->requestState(lastRequestedNode->parent_.lock()->state_->getName());
352        else
353            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
354    }
355
356    GameState* Game::getState(const std::string& name)
357    {
358        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(name));
359        if (it != allStates_s.end())
360            return it->second;
361        else
362        {
363            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
364            return 0;
365        }
366    }
367
368    void Game::setStateHierarchy(const std::string& str)
369    {
370        // Split string into pieces of the form whitespacesText
371        std::vector<std::pair<std::string, unsigned> > stateStrings;
372        size_t pos = 0;
373        size_t startPos = 0;
374        while (pos < str.size())
375        {
376            unsigned indentation = 0;
377            while(pos < str.size() && str[pos] == ' ')
378                ++indentation, ++pos;
379            startPos = pos;
380            while(pos < str.size() && str[pos] != ' ')
381                ++pos;
382            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
383        }
384        unsigned int currentLevel = 0;
385        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
386        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
387        {
388            std::string newStateName = it->first;
389            unsigned newLevel = it->second + 1; // empty root is 0
390            GameState* newState = this->getState(newStateName);
391            if (!newState)
392                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
393            if (newState == this->rootStateNode_->state_)
394                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
395            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
396            newNode->state_ = newState;
397
398            if (newLevel <= currentLevel)
399            {
400                do
401                    currentNode = currentNode->parent_.lock();
402                while (newLevel <= --currentLevel);
403            }
404            if (newLevel == currentLevel + 1)
405            {
406                // Add the child
407                newNode->parent_ = currentNode;
408                currentNode->children_.push_back(newNode);
409                currentNode->state_->addChild(newNode->state_);
410            }
411            else
412                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
413            currentNode = newNode;
414            currentLevel = newLevel;
415        }
416    }
417
418    /*** Internal ***/
419
420    void Game::loadState(GameState* state)
421    {
422        this->bChangingState_ = true;
423        state->activate();
424        if (!this->activeStates_.empty())
425            this->activeStates_.back()->activity_.topState = false;
426        this->activeStates_.push_back(state);
427        state->activity_.topState = true;
428        this->bChangingState_ = false;
429    }
430
431    void Game::unloadState(orxonox::GameState* state)
432    {
433        this->bChangingState_ = true;
434        state->activity_.topState = false;
435        this->activeStates_.pop_back();
436        if (!this->activeStates_.empty())
437            this->activeStates_.back()->activity_.topState = true;
438        try
439        {
440            state->deactivate();
441        }
442        catch (const std::exception& ex)
443        {
444            COUT(2) << "Warning: Unloading GameState '" << state->getName() << "' threw an exception: " << ex.what() << std::endl;
445            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
446        }
447        this->bChangingState_ = false;
448    }
449
450    /*static*/ bool Game::addGameState(GameState* state)
451    {
452        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(state->getName()));
453        if (it == allStates_s.end())
454            allStates_s[getLowercase(state->getName())] = state;
455        else
456            ThrowException(GameState, "Cannot add two GameStates with the same name to 'Game'.");
457
458        // just a required dummy return value
459        return true;
460    }
461
462    /*static*/ void Game::destroyStates()
463    {
464        // Delete all GameStates created by the macros
465        for (std::map<std::string, GameState*>::const_iterator it = allStates_s.begin(); it != allStates_s.end(); ++it)
466            delete it->second;
467        allStates_s.clear();
468    }
469}
Note: See TracBrowser for help on using the repository browser.