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