Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Build fix (again a problem with temporaries and references, but different).

  • Property svn:eol-style set to native
File size: 23.2 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        // Destroy factories before the Core!
113        : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
114    {
115        this->bAbort_ = false;
116        bChangingState_ = false;
117
118#ifdef ORXONOX_PLATFORM_WINDOWS
119        minimumSleepTime_ = 1000/*us*/;
120#else
121        minimumSleepTime_ = 0/*us*/;
122#endif
123
124        // Create an empty root state
125        this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false);
126
127        // Set up a basic clock to keep time
128        this->gameClock_.reset(new Clock());
129
130        // Create the Core
131        this->core_.reset(new Core(cmdLine));
132
133        // After the core has been created, we can safely instantiate the GameStates that don't require graphics
134        for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
135            it != gameStateDeclarations_s.end(); ++it)
136        {
137            if (!it->second.bGraphicsMode)
138                constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second);
139        }
140
141        // The empty root state is ALWAYS loaded!
142        this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode());
143        this->rootStateNode_->name_ = "emptyRootGameState";
144        this->loadedTopStateNode_ = this->rootStateNode_;
145        this->loadedStates_.push_back(this->getState(rootStateNode_->name_));
146
147        // Do this after the Core creation!
148        this->configuration_.reset(new GameConfiguration());
149    }
150
151    /**
152    @brief
153        All destruction code is handled by scoped_ptrs and SimpleScopeGuards.
154    */
155    Game::~Game()
156    {
157    }
158
159    /**
160    @brief
161        Main loop of the orxonox game.
162    @note
163        We use the Ogre::Timer to measure time since it uses the most precise
164        method an any platform (however the windows timer lacks time when under
165        heavy kernel load!).
166    */
167    void Game::run()
168    {
169        if (this->requestedStateNodes_.empty())
170            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
171
172        // reset statistics
173        this->statisticsStartTime_ = 0;
174        this->statisticsTickTimes_.clear();
175        this->periodTickTime_ = 0;
176        this->periodTime_ = 0;
177        this->avgFPS_ = 0.0f;
178        this->avgTickTime_ = 0.0f;
179        this->excessSleepTime_ = 0;
180
181        // START GAME
182        // first delta time should be about 0 seconds
183        this->gameClock_->capture();
184        // A first item is required for the fps limiter
185        StatisticsTickInfo tickInfo = {0, 0};
186        statisticsTickTimes_.push_back(tickInfo);
187        while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0))
188        {
189            // Generate the dt
190            this->gameClock_->capture();
191
192            // Statistics init
193            StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0};
194            statisticsTickTimes_.push_back(tickInfo);
195            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
196
197            // Update the GameState stack if required
198            this->updateGameStateStack();
199
200            // Core preUpdate (doesn't throw)
201            try
202                { this->core_->preUpdate(*this->gameClock_); }
203            catch (...)
204            {
205                COUT(0) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << std::endl;
206                COUT(0) << "This should really never happen! Closing the program." << std::endl;
207                this->stop();
208                break;
209            }
210
211            // Update the GameStates bottom up in the stack
212            this->updateGameStates();
213
214            // Core postUpdate (doesn't throw)
215            try
216                { this->core_->postUpdate(*this->gameClock_); }
217            catch (...)
218            {
219                COUT(0) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << std::endl;
220                COUT(0) << "This should really never happen! Closing the program." << std::endl;
221                this->stop();
222                break;
223            }
224
225            // Evaluate statistics
226            this->updateStatistics();
227
228            // Limit framerate
229            this->updateFPSLimiter();
230        }
231
232        // UNLOAD all remaining states
233        while (this->loadedStates_.size() > 1)
234            this->unloadState(this->loadedStates_.back()->getName());
235        this->loadedTopStateNode_ = this->rootStateNode_;
236        this->requestedStateNodes_.clear();
237    }
238
239    void Game::updateGameStateStack()
240    {
241        while (this->requestedStateNodes_.size() > 0)
242        {
243            shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
244            assert(this->loadedTopStateNode_);
245            if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock())
246                this->unloadState(loadedTopStateNode_->name_);
247            else // has to be child
248            {
249                try
250                {
251                    this->loadState(requestedStateNode->name_);
252                }
253                catch (...)
254                {
255                    COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << std::endl;
256                    // All scheduled operations have now been rendered inert --> flush them and issue a warning
257                    if (this->requestedStateNodes_.size() > 1)
258                        COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
259                    this->requestedStateNodes_.clear();
260                    break;
261                }
262            }
263            this->loadedTopStateNode_ = requestedStateNode;
264            this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
265        }
266    }
267
268    void Game::updateGameStates()
269    {
270        // Note: The first element is the empty root state, which doesn't need ticking
271        for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1;
272            it != this->loadedStates_.end(); ++it)
273        {
274            try
275            {
276                // Add tick time for most of the states
277                uint64_t timeBeforeTick = 0;
278                if ((*it)->getInfo().bIgnoreTickTime)
279                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
280                (*it)->update(*this->gameClock_);
281                if ((*it)->getInfo().bIgnoreTickTime)
282                    this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
283            }
284            catch (...)
285            {
286                COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Exception::handleMessage() << 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            if (currentNode == NULL)
413                requestedNodes.clear();
414        }
415
416        if (requestedNodes.empty())
417            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
418        else
419            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
420    }
421
422    void Game::requestStates(const std::string& names)
423    {
424        SubString tokens(names, ",;", " ");
425        for (unsigned int i = 0; i < tokens.size(); ++i)
426            this->requestState(tokens[i]);
427    }
428
429    void Game::popState()
430    {
431        shared_ptr<GameStateTreeNode> lastRequestedNode;
432        if (this->requestedStateNodes_.empty())
433            lastRequestedNode = this->loadedTopStateNode_;
434        else
435            lastRequestedNode = this->requestedStateNodes_.back();
436        if (lastRequestedNode != this->rootStateNode_)
437            this->requestState(lastRequestedNode->parent_.lock()->name_);
438        else
439            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
440    }
441
442    shared_ptr<GameState> Game::getState(const std::string& name)
443    {
444        GameStateMap::const_iterator it = constructedStates_.find(name);
445        if (it != constructedStates_.end())
446            return it->second;
447        else
448        {
449            std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
450            if (it != gameStateDeclarations_s.end())
451                COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl;
452            else
453                COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl;
454            return shared_ptr<GameState>();
455        }
456    }
457
458    void Game::setStateHierarchy(const std::string& str)
459    {
460        // Split string into pieces of the form whitespacesText
461        std::vector<std::pair<std::string, int> > stateStrings;
462        size_t pos = 0;
463        size_t startPos = 0;
464        while (pos < str.size())
465        {
466            int indentation = 0;
467            while(pos < str.size() && str[pos] == ' ')
468                ++indentation, ++pos;
469            startPos = pos;
470            while(pos < str.size() && str[pos] != ' ')
471                ++pos;
472            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
473        }
474        if (stateStrings.empty())
475            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
476        // Add element with large identation to detect the last with just an iterator
477        stateStrings.push_back(std::make_pair("", -1));
478
479        // Parse elements recursively
480        std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
481        parseStates(begin, this->rootStateNode_);
482    }
483
484    /*** Internal ***/
485
486    void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
487    {
488        SubString tokens(it->first, ",");
489        std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
490
491        for (unsigned int i = 0; i < tokens.size(); ++i)
492        {
493            it = startIt; // Reset iterator to the beginning of the sub tree
494            if (!this->checkState(tokens[i]))
495                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
496            if (tokens[i] == this->rootStateNode_->name_)
497                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
498            shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
499            node->name_ = tokens[i];
500            node->parent_ = currentNode;
501            currentNode->children_.push_back(node);
502
503            int currentLevel = it->second;
504            ++it;
505            while (it->second != -1)
506            {
507                if (it->second <= currentLevel)
508                    break;
509                else if (it->second == currentLevel + 1)
510                    parseStates(it, node);
511                else
512                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
513            }
514        }
515    }
516
517    void Game::loadGraphics()
518    {
519        if (!GameMode::bShowsGraphics_s)
520        {
521            core_->loadGraphics();
522            Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
523            GameMode::bShowsGraphics_s = true;
524
525            // Construct all the GameStates that require graphics
526            for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin();
527                it != gameStateDeclarations_s.end(); ++it)
528            {
529                if (it->second.bGraphicsMode)
530                {
531                    // Game state loading failure is serious --> don't catch
532                    shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second);
533                    if (!constructedStates_.insert(std::make_pair(
534                        it->second.stateName, gameState)).second)
535                        assert(false); // GameState was already created!
536                }
537            }
538            graphicsUnloader.Dismiss();
539        }
540    }
541
542    void Game::unloadGraphics()
543    {
544        if (GameMode::bShowsGraphics_s)
545        {
546            // Destroy all the GameStates that require graphics
547            for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();)
548            {
549                if (it->second->getInfo().bGraphicsMode)
550                    constructedStates_.erase(it++);
551                else
552                    ++it;
553            }
554
555            core_->unloadGraphics();
556            GameMode::bShowsGraphics_s = false;
557        }
558    }
559
560    bool Game::checkState(const std::string& name) const
561    {
562        std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name);
563        if (it == gameStateDeclarations_s.end())
564            return false;
565        else
566            return true;
567    }
568
569    void Game::loadState(const std::string& name)
570    {
571        this->bChangingState_ = true;
572        LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState);
573
574        // If state requires graphics, load it
575        Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
576        if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics())
577            this->loadGraphics();
578        else
579            graphicsUnloader.Dismiss();
580
581        shared_ptr<GameState> state = this->getState(name);
582        state->activate();
583        if (!this->loadedStates_.empty())
584            this->loadedStates_.back()->activity_.topState = false;
585        this->loadedStates_.push_back(state);
586        state->activity_.topState = true;
587
588        graphicsUnloader.Dismiss();
589    }
590
591    void Game::unloadState(const std::string& name)
592    {
593        this->bChangingState_ = true;
594        try
595        {
596            shared_ptr<GameState> state = this->getState(name);
597            state->activity_.topState = false;
598            this->loadedStates_.pop_back();
599            if (!this->loadedStates_.empty())
600                this->loadedStates_.back()->activity_.topState = true;
601            state->deactivate();
602        }
603        catch (...)
604        {
605            COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << std::endl;
606            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
607        }
608        // Check if graphics is still required
609        if (!bAbort_)
610        {
611            bool graphicsRequired = false;
612            for (unsigned i = 0; i < loadedStates_.size(); ++i)
613                graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode;
614            if (!graphicsRequired)
615                this->unloadGraphics();
616        }
617        this->bChangingState_ = false;
618    }
619
620    std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
621
622    /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
623    {
624        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = factories_s.find(info.className);
625        assert(it != factories_s.end());
626        return it->second->fabricateInternal(info);
627    }
628}
Note: See TracBrowser for help on using the repository browser.