Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/core/Game.cc @ 3313

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

Reverted TclThreadManager commits to make a tag (there's possibly still an unresolved issue with the TclThreadManager under linux when terminating the game (mutex assert)).

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