Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/libraries/src/core/Game.cc @ 5637

Last change on this file since 5637 was 5637, checked in by landauf, 15 years ago

Applied retos patch for Game.cc and Game.h (thanks)

+2 small changes in Core.cc and GSClient.cc

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