Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/resource/src/core/Game.cc @ 3349

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

Moved InputManager, GUIManager and GraphicsManager handling from GSGraphics to Core.

  • 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(const std::string& cmdLine)
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(cmdLine);
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 preUpdate (doesn't throw)
248            if (!this->core_->preUpdate(*this->gameClock_))
249            {
250                this->stop();
251                break;
252            }
253
254            // UPDATE, GameStates bottom to top in the stack
255            // Note: The first element is the empty root state, which doesn't need ticking
256            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin() + 1;
257                it != this->activeStates_.end(); ++it)
258            {
259                std::string exceptionMessage;
260                try
261                {
262                    // Add tick time for most of the states
263                    uint64_t timeBeforeTick;
264                    if ((*it)->ignoreTickTime())
265                        timeBeforeTick = this->gameClock_->getRealMicroseconds();
266                    (*it)->update(*this->gameClock_);
267                    if ((*it)->ignoreTickTime())
268                        this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
269                }
270                catch (const std::exception& ex)
271                { exceptionMessage = ex.what(); }
272                catch (...)
273                { exceptionMessage = "Unknown exception"; }
274                if (!exceptionMessage.empty())
275                {
276                    COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << exceptionMessage << std::endl;
277                    COUT(1) << "This should really never happen!" << std::endl;
278                    COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
279                    if ((*it)->getParent() != NULL)
280                        this->requestState((*it)->getParent()->getName());
281                    else
282                        this->stop();
283                    break;
284                }
285
286            }
287
288            // UPDATE, Core postUpdate (doesn't throw)
289            if (!this->core_->postUpdate(*this->gameClock_))
290            {
291                this->stop();
292                break;
293            }
294
295            // STATISTICS
296            if (this->periodTime_ > this->configuration_->statisticsRefreshCycle_)
297            {
298                std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
299                assert(it != this->statisticsTickTimes_.end());
300                int64_t lastTime = currentTime - this->configuration_->statisticsAvgLength_;
301                if (static_cast<int64_t>(it->tickTime) < lastTime)
302                {
303                    do
304                    {
305                        assert(this->periodTickTime_ >= it->tickLength);
306                        this->periodTickTime_ -= it->tickLength;
307                        ++it;
308                        assert(it != this->statisticsTickTimes_.end());
309                    } while (static_cast<int64_t>(it->tickTime) < lastTime);
310                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
311                }
312
313                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
314                this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
315                this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
316
317                this->periodTime_ -= this->configuration_->statisticsRefreshCycle_;
318            }
319        }
320
321        // UNLOAD all remaining states
322        while (this->activeStates_.size() > 1)
323            this->unloadState(this->activeStates_.back());
324        this->activeStateNode_ = this->rootStateNode_;
325        this->requestedStateNodes_.clear();
326    }
327
328    void Game::stop()
329    {
330        this->bAbort_ = true;
331    }
332
333    void Game::subtractTickTime(int32_t length)
334    {
335        assert(!this->statisticsTickTimes_.empty());
336        this->statisticsTickTimes_.back().tickLength -= length;
337        this->periodTickTime_ -= length;
338    }
339
340
341    /***** GameState related *****/
342
343    void Game::requestState(const std::string& name)
344    {
345        GameState* state = this->getState(name);
346        if (state == NULL)
347            return;
348
349        //if (this->bChangingState_)
350        //{
351        //    COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
352        //    return;
353        //}
354
355        shared_ptr<GameStateTreeNode> lastRequestedNode;
356        if (this->requestedStateNodes_.empty())
357            lastRequestedNode = this->activeStateNode_;
358        else
359            lastRequestedNode = this->requestedStateNodes_.back();
360        if (state == lastRequestedNode->state_)
361        {
362            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
363            return;
364        }
365
366        // Check children first
367        std::vector<shared_ptr<GameStateTreeNode> > requestedNodes;
368        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
369        {
370            if (lastRequestedNode->children_[i]->state_ == state)
371            {
372                requestedNodes.push_back(lastRequestedNode->children_[i]);
373                break;
374            }
375        }
376
377        if (requestedNodes.empty())
378        {
379            // Check parent and all its grand parents
380            shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
381            while (currentNode != NULL)
382            {
383                if (currentNode->state_ == state)
384                    break;
385                currentNode = currentNode->parent_.lock();
386                requestedNodes.push_back(currentNode);
387            }
388        }
389
390        if (requestedNodes.empty())
391            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
392        else
393            this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end());
394    }
395
396    void Game::requestStates(const std::string& names)
397    {
398        SubString tokens(names, ",;", " ");
399        for (unsigned int i = 0; i < tokens.size(); ++i)
400            this->requestState(tokens[i]);
401    }
402
403    void Game::popState()
404    {
405        shared_ptr<GameStateTreeNode> lastRequestedNode;
406        if (this->requestedStateNodes_.empty())
407            lastRequestedNode = this->activeStateNode_;
408        else
409            lastRequestedNode = this->requestedStateNodes_.back();
410        if (lastRequestedNode != this->rootStateNode_)
411            this->requestState(lastRequestedNode->parent_.lock()->state_->getName());
412        else
413            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
414    }
415
416    GameState* Game::getState(const std::string& name)
417    {
418        std::map<std::string, GameState*>::const_iterator it = gameStates_.find(getLowercase(name));
419        if (it != gameStates_.end())
420            return it->second;
421        else
422        {
423            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
424            return 0;
425        }
426    }
427
428    void Game::setStateHierarchy(const std::string& str)
429    {
430        // Split string into pieces of the form whitespacesText
431        std::vector<std::pair<std::string, unsigned> > stateStrings;
432        size_t pos = 0;
433        size_t startPos = 0;
434        while (pos < str.size())
435        {
436            unsigned indentation = 0;
437            while(pos < str.size() && str[pos] == ' ')
438                ++indentation, ++pos;
439            startPos = pos;
440            while(pos < str.size() && str[pos] != ' ')
441                ++pos;
442            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
443        }
444        unsigned int currentLevel = 0;
445        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
446        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
447        {
448            std::string newStateName = it->first;
449            unsigned newLevel = it->second + 1; // empty root is 0
450            GameState* newState = this->getState(newStateName);
451            if (!newState)
452                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
453            if (newState == this->rootStateNode_->state_)
454                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
455            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
456            newNode->state_ = newState;
457
458            if (newLevel <= currentLevel)
459            {
460                do
461                    currentNode = currentNode->parent_.lock();
462                while (newLevel <= --currentLevel);
463            }
464            if (newLevel == currentLevel + 1)
465            {
466                // Add the child
467                newNode->parent_ = currentNode;
468                currentNode->children_.push_back(newNode);
469                currentNode->state_->addChild(newNode->state_);
470            }
471            else
472                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
473            currentNode = newNode;
474            currentLevel = newLevel;
475        }
476    }
477
478    /*** Internal ***/
479
480    void Game::loadState(GameState* state)
481    {
482        this->bChangingState_ = true;
483        state->activate();
484        if (!this->activeStates_.empty())
485            this->activeStates_.back()->activity_.topState = false;
486        this->activeStates_.push_back(state);
487        state->activity_.topState = true;
488        this->bChangingState_ = false;
489    }
490
491    void Game::unloadState(orxonox::GameState* state)
492    {
493        this->bChangingState_ = true;
494        state->activity_.topState = false;
495        this->activeStates_.pop_back();
496        if (!this->activeStates_.empty())
497            this->activeStates_.back()->activity_.topState = true;
498        try
499        {
500            state->deactivate();
501        }
502        catch (const std::exception& ex)
503        {
504            COUT(2) << "Warning: Unloading GameState '" << state->getName() << "' threw an exception: " << ex.what() << std::endl;
505            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
506        }
507        this->bChangingState_ = false;
508    }
509
510    std::map<std::string, Game::GameStateFactory*> Game::GameStateFactory::factories_s;
511
512    /*static*/ GameState* Game::GameStateFactory::fabricate(const std::string& className, const GameStateConstrParams& params)
513    {
514        std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.find(className);
515        assert(it != factories_s.end());
516        return it->second->fabricate(params);
517    }
518
519    /*static*/ void Game::GameStateFactory::destroyFactories()
520    {
521        for (std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.begin(); it != factories_s.end(); ++it)
522            delete it->second;
523        factories_s.clear();
524    }
525}
Note: See TracBrowser for help on using the repository browser.