Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/gui/src/core/Game.cc @ 2845

Last change on this file since 2845 was 2845, checked in by rgrieder, 15 years ago
  • Moved some code from Game to Main and GSRoot
  • Renamed "gui" GameState to "mainMenu"
  • Property svn:eol-style set to native
File size: 12.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 <cassert>
39
40#include "util/Debug.h"
41#include "util/Exception.h"
42#include "Clock.h"
43#include "CommandLine.h"
44#include "ConsoleCommand.h"
45#include "Core.h"
46#include "CoreIncludes.h"
47#include "ConfigValueIncludes.h"
48#include "GameState.h"
49
50namespace orxonox
51{
52    static void stop_game()
53        { Game::getInstance().stop(); }
54    SetConsoleCommandShortcutExternAlias(stop_game, "exit");
55
56    struct _CoreExport GameStateTreeNode
57    {
58        GameState*                      state_;
59        GameStateTreeNode*              parent_;
60        std::vector<GameStateTreeNode*> children_;
61    };
62
63    std::map<std::string, GameState*> Game::allStates_s;
64    Game* Game::singletonRef_s = 0;
65
66    /**
67    @brief
68        Non-initialising constructor.
69    */
70    Game::Game(int argc, char** argv)
71    {
72        assert(singletonRef_s == 0);
73        singletonRef_s = this;
74
75        this->rootStateNode_ = 0;
76        this->activeStateNode_ = 0;
77
78        this->abort_ = false;
79
80        // reset statistics
81        this->statisticsStartTime_ = 0;
82        this->statisticsTickTimes_.clear();
83        this->periodTickTime_ = 0;
84        this->periodTime_ = 0;
85        this->avgFPS_ = 0.0f;
86        this->avgTickTime_ = 0.0f;
87
88        this->core_ = new orxonox::Core();
89        this->gameClock_ = this->core_->initialise(argc, argv);
90
91        RegisterRootObject(Game);
92        this->setConfigValues();
93    }
94
95    /**
96    @brief
97    */
98    Game::~Game()
99    {
100        // Destroy pretty much everyhting left
101        delete this->core_;
102
103        // Delete all GameStates created by the macros
104        for (std::map<std::string, GameState*>::const_iterator it = allStates_s.begin(); it != allStates_s.end(); ++it)
105            delete it->second;
106
107        assert(singletonRef_s);
108        singletonRef_s = 0;
109    }
110
111    void Game::setConfigValues()
112    {
113        SetConfigValue(statisticsRefreshCycle_, 250000)
114            .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
115        SetConfigValue(statisticsAvgLength_, 1000000)
116            .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
117    }
118
119    /**
120    @brief
121        Main loop of the orxonox game.
122    @note
123        We use the Ogre::Timer to measure time since it uses the most precise
124        method an any platform (however the windows timer lacks time when under
125        heavy kernel load!).
126    */
127    void Game::run()
128    {
129        // Always start with the ROOT state
130        this->requestedStateNodes_.push_back(this->rootStateNode_);
131        this->activeStateNode_ = this->rootStateNode_;
132        this->loadState(this->rootStateNode_->state_);
133
134        // START GAME
135        this->gameClock_->capture(); // first delta time should be about 0 seconds
136        while (!this->abort_ && !this->activeStates_.empty())
137        {
138            this->gameClock_->capture();
139            uint64_t currentTime = this->gameClock_->getMicroseconds();
140
141            // STATISTICS
142            statisticsTickInfo tickInfo = {currentTime, 0};
143            statisticsTickTimes_.push_back(tickInfo);
144            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
145
146            // UPDATE STATE STACK
147            while (this->requestedStateNodes_.size() > 1)
148            {
149                // Note: this->requestedStateNodes_.front() is the currently active state node
150                std::vector<GameStateTreeNode*>::iterator it = this->requestedStateNodes_.begin() + 1;
151                if (*it == this->activeStateNode_->parent_)
152                    this->unloadState(this->activeStateNode_->state_);
153                else // has to be child
154                    this->loadState((*it)->state_);
155                this->activeStateNode_ = *it;
156                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
157            }
158
159            // UPDATE, bottom to top in the stack
160            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin();
161                it != this->activeStates_.end(); ++it)
162                (*it)->update(*this->gameClock_);
163
164            // STATISTICS
165            if (this->periodTime_ > statisticsRefreshCycle_)
166            {
167                std::list<statisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
168                assert(it != this->statisticsTickTimes_.end());
169                int64_t lastTime = currentTime - this->statisticsAvgLength_;
170                if ((int64_t)it->tickTime < lastTime)
171                {
172                    do
173                    {
174                        assert(this->periodTickTime_ > it->tickLength);
175                        this->periodTickTime_ -= it->tickLength;
176                        ++it;
177                        assert(it != this->statisticsTickTimes_.end());
178                    } while ((int64_t)it->tickTime < lastTime);
179                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
180                }
181
182                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
183                this->avgFPS_ = (float)framesPerPeriod / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0;
184                this->avgTickTime_ = (float)this->periodTickTime_ / framesPerPeriod / 1000.0;
185
186                this->periodTime_ -= this->statisticsRefreshCycle_;
187            }
188        }
189
190        // UNLOAD all remaining states
191        while (!this->activeStates_.empty())
192            this->unloadState(this->activeStates_.back());
193        this->activeStateNode_ = 0;
194        this->requestedStateNodes_.clear();
195    }
196
197    void Game::stop()
198    {
199        this->abort_ = true;
200    }
201
202    void Game::addTickTime(uint32_t length)
203    {
204        assert(!this->statisticsTickTimes_.empty());
205        this->statisticsTickTimes_.back().tickLength += length;
206        this->periodTickTime_+=length;
207    }
208
209
210    /***** GameState related *****/
211
212    void Game::requestState(const std::string& name)
213    {
214        GameState* state = this->getState(name);
215        if (state == NULL || this->activeStateNode_ == NULL)
216            return;
217
218        GameStateTreeNode* requestedNode = 0;
219
220        // this->requestedStateNodes_.back() is the currently active state
221        GameStateTreeNode* lastRequestedNode = this->requestedStateNodes_.back();
222
223        // Already the active node?
224        if (state == lastRequestedNode->state_)
225        {
226            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
227            return;
228        }
229
230        // Check children first
231        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
232        {
233            if (lastRequestedNode->children_[i]->state_ == state)
234            {
235                requestedNode = lastRequestedNode->children_[i];
236                break;
237            }
238        }
239
240        // Check parent and all its grand parents
241        GameStateTreeNode* currentNode = lastRequestedNode;
242        while (requestedNode == NULL && currentNode->parent_ != NULL)
243        {
244            if (currentNode->state_ == state)
245                requestedNode = currentNode;
246            currentNode = currentNode->parent_;
247        }
248
249        if (requestedNode == NULL)
250            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
251        else
252            this->requestedStateNodes_.push_back(requestedNode);
253    }
254
255    void Game::popState()
256    {
257        if (this->activeStateNode_ != NULL && this->requestedStateNodes_.back()->parent_)
258            this->requestState(this->requestedStateNodes_.back()->parent_->state_->getName());
259        else
260            COUT(2) << "Warning: Could not pop GameState. Ignoring." << std::endl;
261    }
262
263    GameState* Game::getState(const std::string& name)
264    {
265        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(name);
266        if (it != allStates_s.end())
267            return it->second;
268        else
269        {
270            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
271            return 0;
272        }
273    }
274
275    void Game::setStateHierarchy(const std::string& str)
276    {
277        // Split string into pieces of the form whitespacesText
278        std::vector<std::pair<std::string, unsigned> > stateStrings;
279        size_t pos = 0;
280        size_t startPos = 0;
281        while (pos < str.size())
282        {
283            unsigned indentation = 0;
284            while(pos < str.size() && str[pos] == ' ')
285                ++indentation, ++pos;
286            startPos = pos;
287            while(pos < str.size() && str[pos] != ' ')
288                ++pos;
289            stateStrings.push_back(std::pair<std::string, unsigned>(
290                str.substr(startPos, pos - startPos), indentation));
291        }
292        unsigned int currentLevel = 0;
293        GameStateTreeNode* currentNode = 0;
294        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
295        {
296            std::string newStateName = it->first;
297            unsigned newLevel = it->second;
298            GameState* newState = this->getState(newStateName);
299            if (!newState)
300                ThrowException(GameState, std::string("GameState with name '") + newStateName + "' not found!");
301            if (newLevel == 0)
302            {
303                // root
304                if (this->rootStateNode_ != NULL)
305                    ThrowException(GameState, "No two root GameStates are allowed!");
306                GameStateTreeNode* newNode = new GameStateTreeNode;
307                newNode->state_ = newState;
308                newNode->parent_ = 0;
309                this->rootStateNode_ = newNode;
310                currentNode = this->rootStateNode_;
311            }
312            else if (currentNode)
313            {
314                GameStateTreeNode* newNode = new GameStateTreeNode;
315                newNode->state_ = newState;
316                if (newLevel < currentLevel)
317                {
318                    // Get down the hierarchy
319                    do
320                        currentNode = currentNode->parent_;
321                    while (newLevel < --currentLevel);
322                }
323                if (newLevel == currentLevel)
324                {
325                    // same level
326                    newNode->parent_ = currentNode->parent_;
327                    newNode->parent_->children_.push_back(newNode);
328                }
329                else if (newLevel == currentLevel + 1)
330                {
331                    // child
332                    newNode->parent_ = currentNode;
333                    currentNode->children_.push_back(newNode);
334                }
335                else
336                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
337                currentNode = newNode;
338                currentLevel = newLevel;
339            }
340            else
341            {
342                ThrowException(GameState, "No root GameState specified!");
343            }
344        }
345    }
346
347    /*** Internal ***/
348
349    void Game::loadState(GameState* state)
350    {
351        state->activate();
352        this->activeStates_.push_back(state);
353    }
354
355    void Game::unloadState(orxonox::GameState* state)
356    {
357        state->deactivate();
358        this->activeStates_.pop_back();
359    }
360
361    /*static*/ bool Game::addGameState(GameState* state)
362    {
363        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(state->getName());
364        if (it == allStates_s.end())
365            allStates_s[state->getName()] = state;
366        else
367            ThrowException(GameState, "Cannot add two GameStates with the same name to 'Game'.");
368
369        // just a required dummy return value
370        return true;
371    }
372}
Note: See TracBrowser for help on using the repository browser.