Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Moved GameState construction from pre-main() to after Core creation. That makes it possible to use Core features (like configValues) in the GameState constructor.

  • Property svn:eol-style set to native
File size: 17.9 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        SetConfigValue(levelName_, "presentation_dm.oxw")
152            .description("Sets the preselection of the level in the main menu.");
153    }
154
155    void Game::setLevel(std::string levelName)
156    {
157        ModifyConfigValue(levelName_, set, levelName);
158    }
159
160    std::string Game::getLevel()
161    {
162        std::string levelName;
163        CommandLine::getValue("level", &levelName);
164        if (levelName == "")
165            return levelName_;
166        else
167            return levelName;
168    }
169
170    /**
171    @brief
172        Main loop of the orxonox game.
173    @note
174        We use the Ogre::Timer to measure time since it uses the most precise
175        method an any platform (however the windows timer lacks time when under
176        heavy kernel load!).
177    */
178    void Game::run()
179    {
180        if (this->requestedStateNodes_.empty())
181            COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl;
182
183        // START GAME
184        this->gameClock_->capture(); // first delta time should be about 0 seconds
185        while (!this->bAbort_ && (!this->activeStates_.empty() || this->requestedStateNodes_.size() > 0))
186        {
187            this->gameClock_->capture();
188            uint64_t currentTime = this->gameClock_->getMicroseconds();
189
190            // STATISTICS
191            StatisticsTickInfo tickInfo = {currentTime, 0};
192            statisticsTickTimes_.push_back(tickInfo);
193            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
194
195            // UPDATE STATE STACK
196            while (this->requestedStateNodes_.size() > 0)
197            {
198                shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front();
199                assert(this->activeStateNode_);
200                if (!this->activeStateNode_->parent_.expired() && requestedStateNode == this->activeStateNode_->parent_.lock())
201                    this->unloadState(this->activeStateNode_->state_);
202                else // has to be child
203                {
204                    try
205                    {
206                        this->loadState(requestedStateNode->state_);
207                    }
208                    catch (const std::exception& ex)
209                    {
210                        COUT(1) << "Error: Loading GameState '" << requestedStateNode->state_->getName() << "' failed: " << ex.what() << std::endl;
211                        // All scheduled operations have now been rendered inert --> flush them and issue a warning
212                        if (this->requestedStateNodes_.size() > 1)
213                            COUT(1) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl;
214                        this->requestedStateNodes_.clear();
215                        break;
216                    }
217                }
218                this->activeStateNode_ = requestedStateNode;
219                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
220            }
221
222            // UPDATE, Core first
223            try
224            {
225                this->core_->update(*this->gameClock_);
226            }
227            catch (...)
228            {
229                COUT(0) << "An exception occured while ticking the Core. This should really never happen!" << std::endl;
230                COUT(0) << "Closing the program." << std::endl;
231                this->stop();
232                break;
233            }
234
235            // UPDATE, GameStates bottom to top in the stack
236            // Note: The first element is the empty root state, which doesn't need ticking
237            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin() + 1;
238                it != this->activeStates_.end(); ++it)
239            {
240                try
241                {
242                    // Add tick time for most of the states
243                    uint64_t timeBeforeTick;
244                    if (!(*it)->ignoreTickTime())
245                        timeBeforeTick = this->gameClock_->getRealMicroseconds();
246                    (*it)->update(*this->gameClock_);
247                    if (!(*it)->ignoreTickTime())
248                        this->addTickTime(static_cast<uint32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
249                }
250                catch (...)
251                {
252                    COUT(1) << "An exception occured while ticking GameState '" << (*it)->getName() << "'. This should really never happen!" << std::endl;
253                    COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl;
254                    if ((*it)->getParent() != NULL)
255                        this->requestState((*it)->getParent()->getName());
256                    else
257                        this->stop();
258                    break;
259                }
260
261            }
262
263            // STATISTICS
264            if (this->periodTime_ > statisticsRefreshCycle_)
265            {
266                std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
267                assert(it != this->statisticsTickTimes_.end());
268                int64_t lastTime = currentTime - this->statisticsAvgLength_;
269                if ((int64_t)it->tickTime < lastTime)
270                {
271                    do
272                    {
273                        assert(this->periodTickTime_ >= it->tickLength);
274                        this->periodTickTime_ -= it->tickLength;
275                        ++it;
276                        assert(it != this->statisticsTickTimes_.end());
277                    } while ((int64_t)it->tickTime < lastTime);
278                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
279                }
280
281                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
282                this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
283                this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
284
285                this->periodTime_ -= this->statisticsRefreshCycle_;
286            }
287        }
288
289        // UNLOAD all remaining states
290        while (this->activeStates_.size() > 1)
291            this->unloadState(this->activeStates_.back());
292        this->activeStateNode_ = this->rootStateNode_;
293        this->requestedStateNodes_.clear();
294    }
295
296    void Game::stop()
297    {
298        this->bAbort_ = true;
299    }
300
301    void Game::addTickTime(uint32_t length)
302    {
303        assert(!this->statisticsTickTimes_.empty());
304        this->statisticsTickTimes_.back().tickLength += length;
305        this->periodTickTime_+=length;
306    }
307
308
309    /***** GameState related *****/
310
311    void Game::requestState(const std::string& name)
312    {
313        GameState* state = this->getState(name);
314        if (state == NULL)
315            return;
316
317        //if (this->bChangingState_)
318        //{
319        //    COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl;
320        //    return;
321        //}
322
323        shared_ptr<GameStateTreeNode> lastRequestedNode;
324        if (this->requestedStateNodes_.empty())
325            lastRequestedNode = this->activeStateNode_;
326        else
327            lastRequestedNode = this->requestedStateNodes_.back();
328        if (state == lastRequestedNode->state_)
329        {
330            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
331            return;
332        }
333
334        // Check children first
335        shared_ptr<GameStateTreeNode> requestedNode;
336        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
337        {
338            if (lastRequestedNode->children_[i]->state_ == state)
339            {
340                requestedNode = lastRequestedNode->children_[i];
341                break;
342            }
343        }
344
345        // Check parent and all its grand parents
346        shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
347        while (requestedNode == NULL && currentNode != NULL)
348        {
349            if (currentNode->state_ == state)
350                requestedNode = currentNode;
351            currentNode = currentNode->parent_.lock();
352        }
353
354        if (requestedNode == NULL)
355            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
356        else
357            this->requestedStateNodes_.push_back(requestedNode);
358    }
359
360    void Game::requestStates(const std::string& names)
361    {
362        SubString tokens(names, ",;", " ");
363        for (unsigned int i = 0; i < tokens.size(); ++i)
364            this->requestState(tokens[i]);
365    }
366
367    void Game::popState()
368    {
369        shared_ptr<GameStateTreeNode> lastRequestedNode;
370        if (this->requestedStateNodes_.empty())
371            lastRequestedNode = this->activeStateNode_;
372        else
373            lastRequestedNode = this->requestedStateNodes_.back();
374        if (lastRequestedNode != this->rootStateNode_)
375            this->requestState(lastRequestedNode->parent_.lock()->state_->getName());
376        else
377            COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl;
378    }
379
380    GameState* Game::getState(const std::string& name)
381    {
382        std::map<std::string, GameState*>::const_iterator it = gameStates_.find(getLowercase(name));
383        if (it != gameStates_.end())
384            return it->second;
385        else
386        {
387            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
388            return 0;
389        }
390    }
391
392    void Game::setStateHierarchy(const std::string& str)
393    {
394        // Split string into pieces of the form whitespacesText
395        std::vector<std::pair<std::string, unsigned> > stateStrings;
396        size_t pos = 0;
397        size_t startPos = 0;
398        while (pos < str.size())
399        {
400            unsigned indentation = 0;
401            while(pos < str.size() && str[pos] == ' ')
402                ++indentation, ++pos;
403            startPos = pos;
404            while(pos < str.size() && str[pos] != ' ')
405                ++pos;
406            stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
407        }
408        unsigned int currentLevel = 0;
409        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
410        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
411        {
412            std::string newStateName = it->first;
413            unsigned newLevel = it->second + 1; // empty root is 0
414            GameState* newState = this->getState(newStateName);
415            if (!newState)
416                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
417            if (newState == this->rootStateNode_->state_)
418                ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
419            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
420            newNode->state_ = newState;
421
422            if (newLevel <= currentLevel)
423            {
424                do
425                    currentNode = currentNode->parent_.lock();
426                while (newLevel <= --currentLevel);
427            }
428            if (newLevel == currentLevel + 1)
429            {
430                // Add the child
431                newNode->parent_ = currentNode;
432                currentNode->children_.push_back(newNode);
433                currentNode->state_->addChild(newNode->state_);
434            }
435            else
436                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
437            currentNode = newNode;
438            currentLevel = newLevel;
439        }
440    }
441
442    /*** Internal ***/
443
444    void Game::loadState(GameState* state)
445    {
446        this->bChangingState_ = true;
447        state->activate();
448        if (!this->activeStates_.empty())
449            this->activeStates_.back()->activity_.topState = false;
450        this->activeStates_.push_back(state);
451        state->activity_.topState = true;
452        this->bChangingState_ = false;
453    }
454
455    void Game::unloadState(orxonox::GameState* state)
456    {
457        this->bChangingState_ = true;
458        state->activity_.topState = false;
459        this->activeStates_.pop_back();
460        if (!this->activeStates_.empty())
461            this->activeStates_.back()->activity_.topState = true;
462        try
463        {
464            state->deactivate();
465        }
466        catch (const std::exception& ex)
467        {
468            COUT(2) << "Warning: Unloading GameState '" << state->getName() << "' threw an exception: " << ex.what() << std::endl;
469            COUT(2) << "         There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl;
470        }
471        this->bChangingState_ = false;
472    }
473
474    std::map<std::string, Game::GameStateFactory*> Game::GameStateFactory::factories_s;
475
476    /*static*/ GameState* Game::GameStateFactory::fabricate(const std::string& className, const GameStateConstrParams& params)
477    {
478        std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.find(className);
479        assert(it != factories_s.end());
480        return it->second->fabricate(params);
481    }
482
483    /*static*/ void Game::GameStateFactory::destroyFactories()
484    {
485        for (std::map<std::string, GameStateFactory*>::const_iterator it = factories_s.begin(); it != factories_s.end(); ++it)
486            delete it->second;
487        factories_s.clear();
488    }
489}
Note: See TracBrowser for help on using the repository browser.