Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Moved Game::getLevel to LevelManager::getStartLevel and Game::setLevel to LevelManager::setStartLevel.

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