Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp6/src/core/Game.cc @ 3289

Last change on this file since 3289 was 3289, checked in by scheusso, 15 years ago

a fix in Clock (more ogre-overflow safe now)
moved framerate control from gsdedicated to game
desired framerate can be controlled by config value FPSLimit_ (in the Game class) now

  • Property svn:eol-style set to native
File size: 14.7 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    struct _CoreExport GameStateTreeNode
62    {
63        GameState* state_;
64        weak_ptr<GameStateTreeNode> parent_;
65        std::vector<shared_ptr<GameStateTreeNode> > children_;
66    };
67
68    std::map<std::string, GameState*> Game::allStates_s;
69    Game* Game::singletonRef_s = 0;
70
71    /**
72    @brief
73        Non-initialising constructor.
74    */
75    Game::Game(int argc, char** argv)
76    {
77        assert(singletonRef_s == 0);
78        singletonRef_s = this;
79
80        this->abort_ = false;
81
82        // reset statistics
83        this->statisticsStartTime_ = 0;
84        this->statisticsTickTimes_.clear();
85        this->periodTickTime_ = 0;
86        this->periodTime_ = 0;
87        this->avgFPS_ = 0.0f;
88        this->avgTickTime_ = 0.0f;
89
90
91        // Set up a basic clock to keep time
92        this->gameClock_ = new Clock();
93
94        this->core_ = new orxonox::Core();
95        this->core_->initialise(argc, argv);
96
97        RegisterRootObject(Game);
98        this->setConfigValues();
99    }
100
101    /**
102    @brief
103    */
104    Game::~Game()
105    {
106        // Destroy pretty much everyhting left
107        delete this->core_;
108
109        delete this->gameClock_;
110
111        assert(singletonRef_s);
112        singletonRef_s = 0;
113    }
114
115    void Game::setConfigValues()
116    {
117        SetConfigValue(statisticsRefreshCycle_, 250000)
118            .description("Sets the time in microseconds interval at which average fps, etc. get updated.");
119        SetConfigValue(statisticsAvgLength_, 1000000)
120            .description("Sets the time in microseconds interval at which average fps, etc. gets calculated.");
121        SetConfigValue(levelName_, "presentation_dm.oxw")
122            .description("Sets the preselection of the level in the main menu.");
123      SetConfigValue(FPSLimit_, 50)
124            .description("Sets the desired framerate (0 for no limit).");
125    }
126
127    void Game::setLevel(std::string levelName)
128    {
129        ModifyConfigValue(levelName_, set, levelName);
130    }
131
132    std::string Game::getLevel()
133    {
134        std::string levelName;
135        CommandLine::getValue("level", &levelName);
136        if (levelName == "")
137            return levelName_;
138        else
139            return levelName;
140    }
141
142    /**
143    @brief
144        Main loop of the orxonox game.
145    @note
146        We use the Ogre::Timer to measure time since it uses the most precise
147        method an any platform (however the windows timer lacks time when under
148        heavy kernel load!).
149    */
150    void Game::run()
151    {
152        // Always start with the ROOT state
153        this->requestedStateNodes_.push_back(this->rootStateNode_);
154        this->activeStateNode_ = this->rootStateNode_;
155        this->loadState(this->rootStateNode_->state_);
156
157        // START GAME
158        this->gameClock_->capture(); // first delta time should be about 0 seconds
159        while (!this->abort_ && !this->activeStates_.empty())
160        {
161            uint64_t currentTime = this->gameClock_->getRealMicroseconds();
162
163            uint64_t nextTickTime = statisticsTickTimes_.back().tickTime + 1000000.f/this->FPSLimit_;
164            if( currentTime < nextTickTime )
165            {
166                usleep( nextTickTime - currentTime );
167                continue;
168            }
169            this->gameClock_->capture();
170
171            // STATISTICS
172            statisticsTickInfo tickInfo = {currentTime, 0};
173            statisticsTickTimes_.push_back(tickInfo);
174            this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds();
175
176            // UPDATE STATE STACK
177            while (this->requestedStateNodes_.size() > 1)
178            {
179                // Note: this->requestedStateNodes_.front() is the currently active state node
180                std::vector<shared_ptr<GameStateTreeNode> >::iterator it = this->requestedStateNodes_.begin() + 1;
181                if (*it == this->activeStateNode_->parent_.lock())
182                    this->unloadState(this->activeStateNode_->state_);
183                else // has to be child
184                    this->loadState((*it)->state_);
185                this->activeStateNode_ = *it;
186                this->requestedStateNodes_.erase(this->requestedStateNodes_.begin());
187            }
188
189            // UPDATE, bottom to top in the stack
190            this->core_->update(*this->gameClock_);
191            for (std::vector<GameState*>::const_iterator it = this->activeStates_.begin();
192                it != this->activeStates_.end(); ++it)
193            {
194                // Add tick time for most of the states
195                uint64_t timeBeforeTick;
196                if ((*it)->getCountTickTime())
197                    timeBeforeTick = this->gameClock_->getRealMicroseconds();
198               
199                (*it)->update(*this->gameClock_);
200
201                if ((*it)->getCountTickTime())
202                    this->addTickTime(static_cast<uint32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick));
203            }
204
205            // STATISTICS
206            if (this->periodTime_ > statisticsRefreshCycle_)
207            {
208                std::list<statisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin();
209                assert(it != this->statisticsTickTimes_.end());
210                int64_t lastTime = currentTime - this->statisticsAvgLength_;
211                if ((int64_t)it->tickTime < lastTime)
212                {
213                    do
214                    {
215                        assert(this->periodTickTime_ > it->tickLength);
216                        this->periodTickTime_ -= it->tickLength;
217                        ++it;
218                        assert(it != this->statisticsTickTimes_.end());
219                    } while ((int64_t)it->tickTime < lastTime);
220                    this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it);
221                }
222
223                uint32_t framesPerPeriod = this->statisticsTickTimes_.size();
224                this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f;
225                this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f;
226
227                this->periodTime_ -= this->statisticsRefreshCycle_;
228            }
229        }
230
231        // UNLOAD all remaining states
232        while (!this->activeStates_.empty())
233            this->unloadState(this->activeStates_.back());
234        this->activeStateNode_.reset();
235        this->requestedStateNodes_.clear();
236    }
237
238    void Game::stop()
239    {
240        this->abort_ = true;
241    }
242
243    void Game::addTickTime(uint32_t length)
244    {
245        assert(!this->statisticsTickTimes_.empty());
246        this->statisticsTickTimes_.back().tickLength += length;
247        this->periodTickTime_+=length;
248    }
249
250
251    /***** GameState related *****/
252
253    void Game::requestState(const std::string& name)
254    {
255        GameState* state = this->getState(name);
256        if (state == NULL || this->activeStateNode_ == NULL)
257            return;
258
259        shared_ptr<GameStateTreeNode> requestedNode;
260
261        // this->requestedStateNodes_.back() is the currently active state
262        shared_ptr<GameStateTreeNode> lastRequestedNode = this->requestedStateNodes_.back();
263
264        // Already the active node?
265        if (state == lastRequestedNode->state_)
266        {
267            COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl;
268            return;
269        }
270
271        // Check children first
272        for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i)
273        {
274            if (lastRequestedNode->children_[i]->state_ == state)
275            {
276                requestedNode = lastRequestedNode->children_[i];
277                break;
278            }
279        }
280
281        // Check parent and all its grand parents
282        shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode;
283        while (requestedNode == NULL && currentNode != NULL)
284        {
285            if (currentNode->state_ == state)
286                requestedNode = currentNode;
287            currentNode = currentNode->parent_.lock();
288        }
289
290        if (requestedNode == NULL)
291            COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl;
292        else
293            this->requestedStateNodes_.push_back(requestedNode);
294    }
295
296    void Game::requestStates(const std::string& names)
297    {
298        SubString tokens(names, ",;", " ");
299        for (unsigned int i = 0; i < tokens.size(); ++i)
300            this->requestState(tokens[i]);
301    }
302
303    void Game::popState()
304    {
305        if (this->activeStateNode_ != NULL && this->requestedStateNodes_.back()->parent_.lock())
306            this->requestState(this->requestedStateNodes_.back()->parent_.lock()->state_->getName());
307        else
308            COUT(2) << "Warning: Could not pop GameState. Ignoring." << std::endl;
309    }
310
311    GameState* Game::getState(const std::string& name)
312    {
313        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(name));
314        if (it != allStates_s.end())
315            return it->second;
316        else
317        {
318            COUT(1) << "Error: Could not find GameState '" << name << "'. Ignoring." << std::endl;
319            return 0;
320        }
321    }
322
323    void Game::setStateHierarchy(const std::string& str)
324    {
325        // Split string into pieces of the form whitespacesText
326        std::vector<std::pair<std::string, unsigned> > stateStrings;
327        size_t pos = 0;
328        size_t startPos = 0;
329        while (pos < str.size())
330        {
331            unsigned indentation = 0;
332            while(pos < str.size() && str[pos] == ' ')
333                ++indentation, ++pos;
334            startPos = pos;
335            while(pos < str.size() && str[pos] != ' ')
336                ++pos;
337            stateStrings.push_back(std::pair<std::string, unsigned>(
338                str.substr(startPos, pos - startPos), indentation));
339        }
340        unsigned int currentLevel = 0;
341        shared_ptr<GameStateTreeNode> currentNode;
342        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
343        {
344            std::string newStateName = it->first;
345            unsigned newLevel = it->second;
346            GameState* newState = this->getState(newStateName);
347            if (!newState)
348                ThrowException(GameState, std::string("GameState with name '") + newStateName + "' not found!");
349            if (newLevel == 0)
350            {
351                // root
352                if (this->rootStateNode_ != NULL)
353                    ThrowException(GameState, "No two root GameStates are allowed!");
354                shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
355                newNode->state_ = newState;
356                this->rootStateNode_ = newNode;
357                currentNode = this->rootStateNode_;
358            }
359            else if (currentNode)
360            {
361                shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
362                newNode->state_ = newState;
363                if (newLevel < currentLevel)
364                {
365                    // Get down the hierarchy
366                    do
367                        currentNode = currentNode->parent_.lock();
368                    while (newLevel < --currentLevel);
369                }
370                if (newLevel == currentLevel)
371                {
372                    // same level
373                    newNode->parent_ = currentNode->parent_;
374                    newNode->parent_.lock()->children_.push_back(newNode);
375                }
376                else if (newLevel == currentLevel + 1)
377                {
378                    // child
379                    newNode->parent_ = currentNode;
380                    currentNode->children_.push_back(newNode);
381                }
382                else
383                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
384                currentNode = newNode;
385                currentLevel = newLevel;
386            }
387            else
388            {
389                ThrowException(GameState, "No root GameState specified!");
390            }
391        }
392    }
393
394    /*** Internal ***/
395
396    void Game::loadState(GameState* state)
397    {
398        if (!this->activeStates_.empty())
399            this->activeStates_.back()->activity_.topState = false;
400        state->activate();
401        state->activity_.topState = true;
402        this->activeStates_.push_back(state);
403    }
404
405    void Game::unloadState(orxonox::GameState* state)
406    {
407        state->activity_.topState = false;
408        state->deactivate();
409        this->activeStates_.pop_back();
410        if (!this->activeStates_.empty())
411            this->activeStates_.back()->activity_.topState = true;
412    }
413
414    /*static*/ bool Game::addGameState(GameState* state)
415    {
416        std::map<std::string, GameState*>::const_iterator it = allStates_s.find(getLowercase(state->getName()));
417        if (it == allStates_s.end())
418            allStates_s[getLowercase(state->getName())] = state;
419        else
420            ThrowException(GameState, "Cannot add two GameStates with the same name to 'Game'.");
421
422        // just a required dummy return value
423        return true;
424    }
425
426    /*static*/ void Game::destroyStates()
427    {
428        // Delete all GameStates created by the macros
429        for (std::map<std::string, GameState*>::const_iterator it = allStates_s.begin(); it != allStates_s.end(); ++it)
430            delete it->second;
431        allStates_s.clear();
432    }
433}
Note: See TracBrowser for help on using the repository browser.