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/Clock.h" |
---|
41 | #include "util/Debug.h" |
---|
42 | #include "util/Exception.h" |
---|
43 | #include "util/ScopeGuard.h" |
---|
44 | #include "util/Sleep.h" |
---|
45 | #include "util/SubString.h" |
---|
46 | #include "CommandLineParser.h" |
---|
47 | #include "ConsoleCommand.h" |
---|
48 | #include "Core.h" |
---|
49 | #include "CoreIncludes.h" |
---|
50 | #include "ConfigValueIncludes.h" |
---|
51 | #include "GameMode.h" |
---|
52 | #include "GameState.h" |
---|
53 | |
---|
54 | namespace orxonox |
---|
55 | { |
---|
56 | static void stop_game() |
---|
57 | { Game::getInstance().stop(); } |
---|
58 | SetConsoleCommandShortcutExternAlias(stop_game, "exit"); |
---|
59 | static void printFPS() |
---|
60 | { COUT(0) << Game::getInstance().getAvgFPS() << std::endl; } |
---|
61 | SetConsoleCommandShortcutExternAlias(printFPS, "printFPS"); |
---|
62 | static void printTickTime() |
---|
63 | { COUT(0) << Game::getInstance().getAvgTickTime() << std::endl; } |
---|
64 | SetConsoleCommandShortcutExternAlias(printTickTime, "printTickTime"); |
---|
65 | |
---|
66 | std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s; |
---|
67 | Game* Game::singletonPtr_s = 0; |
---|
68 | |
---|
69 | //! Represents one node of the game state tree. |
---|
70 | struct GameStateTreeNode |
---|
71 | { |
---|
72 | std::string name_; |
---|
73 | weak_ptr<GameStateTreeNode> parent_; |
---|
74 | std::vector<shared_ptr<GameStateTreeNode> > children_; |
---|
75 | }; |
---|
76 | |
---|
77 | Game::Game(const std::string& cmdLine) |
---|
78 | // Destroy factories before the Core! |
---|
79 | : gsFactoryDestroyer_(Game::GameStateFactory::getFactories(), &std::map<std::string, shared_ptr<GameStateFactory> >::clear) |
---|
80 | { |
---|
81 | this->bAbort_ = false; |
---|
82 | bChangingState_ = false; |
---|
83 | |
---|
84 | #ifdef ORXONOX_PLATFORM_WINDOWS |
---|
85 | minimumSleepTime_ = 1000/*us*/; |
---|
86 | #else |
---|
87 | minimumSleepTime_ = 0/*us*/; |
---|
88 | #endif |
---|
89 | |
---|
90 | // Create an empty root state |
---|
91 | this->declareGameState<GameState>("GameState", "emptyRootGameState", true, false); |
---|
92 | |
---|
93 | // Set up a basic clock to keep time |
---|
94 | this->gameClock_.reset(new Clock()); |
---|
95 | |
---|
96 | // Create the Core |
---|
97 | this->core_.reset(new Core(cmdLine)); |
---|
98 | |
---|
99 | // Do this after the Core creation! |
---|
100 | ClassIdentifier<Game>::getIdentifier("Game")->initialiseObject(this, "Game", true); |
---|
101 | // Remove us from the object lists again to avoid problems when destroying the Game |
---|
102 | this->unregisterObject(); |
---|
103 | this->setConfigValues(); |
---|
104 | |
---|
105 | // After the core has been created, we can safely instantiate the GameStates that don't require graphics |
---|
106 | for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin(); |
---|
107 | it != gameStateDeclarations_s.end(); ++it) |
---|
108 | { |
---|
109 | if (!it->second.bGraphicsMode) |
---|
110 | constructedStates_[it->second.stateName] = GameStateFactory::fabricate(it->second); |
---|
111 | } |
---|
112 | |
---|
113 | // The empty root state is ALWAYS loaded! |
---|
114 | this->rootStateNode_ = shared_ptr<GameStateTreeNode>(new GameStateTreeNode()); |
---|
115 | this->rootStateNode_->name_ = "emptyRootGameState"; |
---|
116 | this->loadedTopStateNode_ = this->rootStateNode_; |
---|
117 | this->loadedStates_.push_back(this->getState(rootStateNode_->name_)); |
---|
118 | } |
---|
119 | |
---|
120 | /** |
---|
121 | @brief |
---|
122 | All destruction code is handled by scoped_ptrs and SimpleScopeGuards. |
---|
123 | */ |
---|
124 | Game::~Game() |
---|
125 | { |
---|
126 | } |
---|
127 | |
---|
128 | void Game::setConfigValues() |
---|
129 | { |
---|
130 | SetConfigValue(statisticsRefreshCycle_, 250000) |
---|
131 | .description("Sets the time in microseconds interval at which average fps, etc. get updated."); |
---|
132 | SetConfigValue(statisticsAvgLength_, 1000000) |
---|
133 | .description("Sets the time in microseconds interval at which average fps, etc. gets calculated."); |
---|
134 | SetConfigValue(fpsLimit_, 50) |
---|
135 | .description("Sets the desired framerate (0 for no limit)."); |
---|
136 | } |
---|
137 | |
---|
138 | /** |
---|
139 | @brief |
---|
140 | Main loop of the orxonox game. |
---|
141 | @note |
---|
142 | We use the Ogre::Timer to measure time since it uses the most precise |
---|
143 | method an any platform (however the windows timer lacks time when under |
---|
144 | heavy kernel load!). |
---|
145 | */ |
---|
146 | void Game::run() |
---|
147 | { |
---|
148 | if (this->requestedStateNodes_.empty()) |
---|
149 | COUT(0) << "Warning: Starting game without requesting GameState. This automatically terminates the program." << std::endl; |
---|
150 | |
---|
151 | // reset statistics |
---|
152 | this->statisticsStartTime_ = 0; |
---|
153 | this->statisticsTickTimes_.clear(); |
---|
154 | this->periodTickTime_ = 0; |
---|
155 | this->periodTime_ = 0; |
---|
156 | this->avgFPS_ = 0.0f; |
---|
157 | this->avgTickTime_ = 0.0f; |
---|
158 | this->excessSleepTime_ = 0; |
---|
159 | |
---|
160 | // START GAME |
---|
161 | // first delta time should be about 0 seconds |
---|
162 | this->gameClock_->capture(); |
---|
163 | // A first item is required for the fps limiter |
---|
164 | StatisticsTickInfo tickInfo = {0, 0}; |
---|
165 | statisticsTickTimes_.push_back(tickInfo); |
---|
166 | while (!this->bAbort_ && (!this->loadedStates_.empty() || this->requestedStateNodes_.size() > 0)) |
---|
167 | { |
---|
168 | // Generate the dt |
---|
169 | this->gameClock_->capture(); |
---|
170 | |
---|
171 | // Statistics init |
---|
172 | StatisticsTickInfo tickInfo = {gameClock_->getMicroseconds(), 0}; |
---|
173 | statisticsTickTimes_.push_back(tickInfo); |
---|
174 | this->periodTime_ += this->gameClock_->getDeltaTimeMicroseconds(); |
---|
175 | |
---|
176 | // Update the GameState stack if required |
---|
177 | this->updateGameStateStack(); |
---|
178 | |
---|
179 | // Core preUpdate (doesn't throw) |
---|
180 | try |
---|
181 | { this->core_->preUpdate(*this->gameClock_); } |
---|
182 | catch (...) |
---|
183 | { |
---|
184 | COUT(0) << "An exception occurred in the Core preUpdate: " << Exception::handleMessage() << std::endl; |
---|
185 | COUT(0) << "This should really never happen! Closing the program." << std::endl; |
---|
186 | this->stop(); |
---|
187 | break; |
---|
188 | } |
---|
189 | |
---|
190 | // Update the GameStates bottom up in the stack |
---|
191 | this->updateGameStates(); |
---|
192 | |
---|
193 | // Core postUpdate (doesn't throw) |
---|
194 | try |
---|
195 | { this->core_->postUpdate(*this->gameClock_); } |
---|
196 | catch (...) |
---|
197 | { |
---|
198 | COUT(0) << "An exception occurred in the Core postUpdate: " << Exception::handleMessage() << std::endl; |
---|
199 | COUT(0) << "This should really never happen! Closing the program." << std::endl; |
---|
200 | this->stop(); |
---|
201 | break; |
---|
202 | } |
---|
203 | |
---|
204 | // Evaluate statistics |
---|
205 | this->updateStatistics(); |
---|
206 | |
---|
207 | // Limit framerate |
---|
208 | this->updateFPSLimiter(); |
---|
209 | } |
---|
210 | |
---|
211 | // UNLOAD all remaining states |
---|
212 | while (this->loadedStates_.size() > 1) |
---|
213 | this->unloadState(this->loadedStates_.back()->getName()); |
---|
214 | this->loadedTopStateNode_ = this->rootStateNode_; |
---|
215 | this->requestedStateNodes_.clear(); |
---|
216 | } |
---|
217 | |
---|
218 | void Game::updateGameStateStack() |
---|
219 | { |
---|
220 | while (this->requestedStateNodes_.size() > 0) |
---|
221 | { |
---|
222 | shared_ptr<GameStateTreeNode> requestedStateNode = this->requestedStateNodes_.front(); |
---|
223 | assert(this->loadedTopStateNode_); |
---|
224 | if (!this->loadedTopStateNode_->parent_.expired() && requestedStateNode == this->loadedTopStateNode_->parent_.lock()) |
---|
225 | this->unloadState(loadedTopStateNode_->name_); |
---|
226 | else // has to be child |
---|
227 | { |
---|
228 | try |
---|
229 | { |
---|
230 | this->loadState(requestedStateNode->name_); |
---|
231 | } |
---|
232 | catch (...) |
---|
233 | { |
---|
234 | COUT(1) << "Error: Loading GameState '" << requestedStateNode->name_ << "' failed: " << Exception::handleMessage() << std::endl; |
---|
235 | // All scheduled operations have now been rendered inert --> flush them and issue a warning |
---|
236 | if (this->requestedStateNodes_.size() > 1) |
---|
237 | COUT(4) << "All " << this->requestedStateNodes_.size() - 1 << " scheduled transitions have been ignored." << std::endl; |
---|
238 | this->requestedStateNodes_.clear(); |
---|
239 | break; |
---|
240 | } |
---|
241 | } |
---|
242 | this->loadedTopStateNode_ = requestedStateNode; |
---|
243 | this->requestedStateNodes_.erase(this->requestedStateNodes_.begin()); |
---|
244 | } |
---|
245 | } |
---|
246 | |
---|
247 | void Game::updateGameStates() |
---|
248 | { |
---|
249 | // Note: The first element is the empty root state, which doesn't need ticking |
---|
250 | for (GameStateVector::const_iterator it = this->loadedStates_.begin() + 1; |
---|
251 | it != this->loadedStates_.end(); ++it) |
---|
252 | { |
---|
253 | try |
---|
254 | { |
---|
255 | // Add tick time for most of the states |
---|
256 | uint64_t timeBeforeTick = 0; |
---|
257 | if ((*it)->getInfo().bIgnoreTickTime) |
---|
258 | timeBeforeTick = this->gameClock_->getRealMicroseconds(); |
---|
259 | (*it)->update(*this->gameClock_); |
---|
260 | if ((*it)->getInfo().bIgnoreTickTime) |
---|
261 | this->subtractTickTime(static_cast<int32_t>(this->gameClock_->getRealMicroseconds() - timeBeforeTick)); |
---|
262 | } |
---|
263 | catch (...) |
---|
264 | { |
---|
265 | COUT(1) << "An exception occurred while updating '" << (*it)->getName() << "': " << Exception::handleMessage() << std::endl; |
---|
266 | COUT(1) << "This should really never happen!" << std::endl; |
---|
267 | COUT(1) << "Unloading all GameStates depending on the one that crashed." << std::endl; |
---|
268 | shared_ptr<GameStateTreeNode> current = this->loadedTopStateNode_; |
---|
269 | while (current->name_ != (*it)->getName() && current) |
---|
270 | current = current->parent_.lock(); |
---|
271 | if (current && current->parent_.lock()) |
---|
272 | this->requestState(current->parent_.lock()->name_); |
---|
273 | else |
---|
274 | this->stop(); |
---|
275 | break; |
---|
276 | } |
---|
277 | } |
---|
278 | } |
---|
279 | |
---|
280 | void Game::updateStatistics() |
---|
281 | { |
---|
282 | // Add the tick time of this frame (rendering time has already been subtracted) |
---|
283 | uint64_t currentTime = gameClock_->getMicroseconds(); |
---|
284 | uint64_t currentRealTime = gameClock_->getRealMicroseconds(); |
---|
285 | this->statisticsTickTimes_.back().tickLength += currentRealTime - currentTime; |
---|
286 | this->periodTickTime_ += currentRealTime - currentTime; |
---|
287 | if (this->periodTime_ > this->statisticsRefreshCycle_) |
---|
288 | { |
---|
289 | std::list<StatisticsTickInfo>::iterator it = this->statisticsTickTimes_.begin(); |
---|
290 | assert(it != this->statisticsTickTimes_.end()); |
---|
291 | int64_t lastTime = currentTime - this->statisticsAvgLength_; |
---|
292 | if (static_cast<int64_t>(it->tickTime) < lastTime) |
---|
293 | { |
---|
294 | do |
---|
295 | { |
---|
296 | assert(this->periodTickTime_ >= it->tickLength); |
---|
297 | this->periodTickTime_ -= it->tickLength; |
---|
298 | ++it; |
---|
299 | assert(it != this->statisticsTickTimes_.end()); |
---|
300 | } while (static_cast<int64_t>(it->tickTime) < lastTime); |
---|
301 | this->statisticsTickTimes_.erase(this->statisticsTickTimes_.begin(), it); |
---|
302 | } |
---|
303 | |
---|
304 | uint32_t framesPerPeriod = this->statisticsTickTimes_.size(); |
---|
305 | this->avgFPS_ = static_cast<float>(framesPerPeriod) / (currentTime - this->statisticsTickTimes_.front().tickTime) * 1000000.0f; |
---|
306 | this->avgTickTime_ = static_cast<float>(this->periodTickTime_) / framesPerPeriod / 1000.0f; |
---|
307 | |
---|
308 | this->periodTime_ -= this->statisticsRefreshCycle_; |
---|
309 | } |
---|
310 | } |
---|
311 | |
---|
312 | void Game::updateFPSLimiter() |
---|
313 | { |
---|
314 | // Why fpsLimit_ - 1? No idea, but otherwise the fps rate is always (from 10 to 200!) one frame too high |
---|
315 | uint32_t nextTime = gameClock_->getMicroseconds() - excessSleepTime_ + static_cast<uint32_t>(1000000.0f / (fpsLimit_ - 1)); |
---|
316 | uint64_t currentRealTime = gameClock_->getRealMicroseconds(); |
---|
317 | while (currentRealTime < nextTime - minimumSleepTime_) |
---|
318 | { |
---|
319 | usleep(nextTime - currentRealTime); |
---|
320 | currentRealTime = gameClock_->getRealMicroseconds(); |
---|
321 | } |
---|
322 | // Integrate excess to avoid steady state error |
---|
323 | excessSleepTime_ = currentRealTime - nextTime; |
---|
324 | // Anti windup |
---|
325 | if (excessSleepTime_ > 50000) // 20ms is about the maximum time Windows would sleep for too long |
---|
326 | excessSleepTime_ = 50000; |
---|
327 | } |
---|
328 | |
---|
329 | void Game::stop() |
---|
330 | { |
---|
331 | this->bAbort_ = true; |
---|
332 | } |
---|
333 | |
---|
334 | void Game::subtractTickTime(int32_t length) |
---|
335 | { |
---|
336 | assert(!this->statisticsTickTimes_.empty()); |
---|
337 | this->statisticsTickTimes_.back().tickLength -= length; |
---|
338 | this->periodTickTime_ -= length; |
---|
339 | } |
---|
340 | |
---|
341 | |
---|
342 | /***** GameState related *****/ |
---|
343 | |
---|
344 | void Game::requestState(const std::string& name) |
---|
345 | { |
---|
346 | if (!this->checkState(name)) |
---|
347 | { |
---|
348 | COUT(2) << "Warning: GameState named '" << name << "' doesn't exist!" << std::endl; |
---|
349 | return; |
---|
350 | } |
---|
351 | |
---|
352 | if (this->bChangingState_) |
---|
353 | { |
---|
354 | COUT(2) << "Warning: Requesting GameStates while loading/unloading a GameState is illegal! Ignoring." << std::endl; |
---|
355 | return; |
---|
356 | } |
---|
357 | |
---|
358 | shared_ptr<GameStateTreeNode> lastRequestedNode; |
---|
359 | if (this->requestedStateNodes_.empty()) |
---|
360 | lastRequestedNode = this->loadedTopStateNode_; |
---|
361 | else |
---|
362 | lastRequestedNode = this->requestedStateNodes_.back(); |
---|
363 | if (name == lastRequestedNode->name_) |
---|
364 | { |
---|
365 | COUT(2) << "Warning: Requesting the currently active state! Ignoring." << std::endl; |
---|
366 | return; |
---|
367 | } |
---|
368 | |
---|
369 | // Check children first |
---|
370 | std::vector<shared_ptr<GameStateTreeNode> > requestedNodes; |
---|
371 | for (unsigned int i = 0; i < lastRequestedNode->children_.size(); ++i) |
---|
372 | { |
---|
373 | if (lastRequestedNode->children_[i]->name_ == name) |
---|
374 | { |
---|
375 | requestedNodes.push_back(lastRequestedNode->children_[i]); |
---|
376 | break; |
---|
377 | } |
---|
378 | } |
---|
379 | |
---|
380 | if (requestedNodes.empty()) |
---|
381 | { |
---|
382 | // Check parent and all its grand parents |
---|
383 | shared_ptr<GameStateTreeNode> currentNode = lastRequestedNode; |
---|
384 | while (currentNode != NULL) |
---|
385 | { |
---|
386 | if (currentNode->name_ == name) |
---|
387 | break; |
---|
388 | currentNode = currentNode->parent_.lock(); |
---|
389 | requestedNodes.push_back(currentNode); |
---|
390 | } |
---|
391 | if (currentNode == NULL) |
---|
392 | requestedNodes.clear(); |
---|
393 | } |
---|
394 | |
---|
395 | if (requestedNodes.empty()) |
---|
396 | COUT(1) << "Error: Requested GameState transition is not allowed. Ignoring." << std::endl; |
---|
397 | else |
---|
398 | this->requestedStateNodes_.insert(requestedStateNodes_.end(), requestedNodes.begin(), requestedNodes.end()); |
---|
399 | } |
---|
400 | |
---|
401 | void Game::requestStates(const std::string& names) |
---|
402 | { |
---|
403 | SubString tokens(names, ",;", " "); |
---|
404 | for (unsigned int i = 0; i < tokens.size(); ++i) |
---|
405 | this->requestState(tokens[i]); |
---|
406 | } |
---|
407 | |
---|
408 | void Game::popState() |
---|
409 | { |
---|
410 | shared_ptr<GameStateTreeNode> lastRequestedNode; |
---|
411 | if (this->requestedStateNodes_.empty()) |
---|
412 | lastRequestedNode = this->loadedTopStateNode_; |
---|
413 | else |
---|
414 | lastRequestedNode = this->requestedStateNodes_.back(); |
---|
415 | if (lastRequestedNode != this->rootStateNode_) |
---|
416 | this->requestState(lastRequestedNode->parent_.lock()->name_); |
---|
417 | else |
---|
418 | COUT(2) << "Warning: Can't pop the internal dummy root GameState" << std::endl; |
---|
419 | } |
---|
420 | |
---|
421 | shared_ptr<GameState> Game::getState(const std::string& name) |
---|
422 | { |
---|
423 | GameStateMap::const_iterator it = constructedStates_.find(name); |
---|
424 | if (it != constructedStates_.end()) |
---|
425 | return it->second; |
---|
426 | else |
---|
427 | { |
---|
428 | std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name); |
---|
429 | if (it != gameStateDeclarations_s.end()) |
---|
430 | COUT(1) << "Error: GameState '" << name << "' has not yet been loaded." << std::endl; |
---|
431 | else |
---|
432 | COUT(1) << "Error: Could not find GameState '" << name << "'." << std::endl; |
---|
433 | return shared_ptr<GameState>(); |
---|
434 | } |
---|
435 | } |
---|
436 | |
---|
437 | void Game::setStateHierarchy(const std::string& str) |
---|
438 | { |
---|
439 | // Split string into pieces of the form whitespacesText |
---|
440 | std::vector<std::pair<std::string, int> > stateStrings; |
---|
441 | size_t pos = 0; |
---|
442 | size_t startPos = 0; |
---|
443 | while (pos < str.size()) |
---|
444 | { |
---|
445 | int indentation = 0; |
---|
446 | while(pos < str.size() && str[pos] == ' ') |
---|
447 | ++indentation, ++pos; |
---|
448 | startPos = pos; |
---|
449 | while(pos < str.size() && str[pos] != ' ') |
---|
450 | ++pos; |
---|
451 | stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation)); |
---|
452 | } |
---|
453 | if (stateStrings.empty()) |
---|
454 | ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating."); |
---|
455 | // Add element with large identation to detect the last with just an iterator |
---|
456 | stateStrings.push_back(std::make_pair("", -1)); |
---|
457 | |
---|
458 | // Parse elements recursively |
---|
459 | std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin(); |
---|
460 | parseStates(begin, this->rootStateNode_); |
---|
461 | } |
---|
462 | |
---|
463 | /*** Internal ***/ |
---|
464 | |
---|
465 | void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode) |
---|
466 | { |
---|
467 | SubString tokens(it->first, ","); |
---|
468 | std::vector<std::pair<std::string, int> >::const_iterator startIt = it; |
---|
469 | |
---|
470 | for (unsigned int i = 0; i < tokens.size(); ++i) |
---|
471 | { |
---|
472 | it = startIt; // Reset iterator to the beginning of the sub tree |
---|
473 | if (!this->checkState(tokens[i])) |
---|
474 | ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!"); |
---|
475 | if (tokens[i] == this->rootStateNode_->name_) |
---|
476 | ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy..."); |
---|
477 | shared_ptr<GameStateTreeNode> node(new GameStateTreeNode()); |
---|
478 | node->name_ = tokens[i]; |
---|
479 | node->parent_ = currentNode; |
---|
480 | currentNode->children_.push_back(node); |
---|
481 | |
---|
482 | int currentLevel = it->second; |
---|
483 | ++it; |
---|
484 | while (it->second != -1) |
---|
485 | { |
---|
486 | if (it->second <= currentLevel) |
---|
487 | break; |
---|
488 | else if (it->second == currentLevel + 1) |
---|
489 | parseStates(it, node); |
---|
490 | else |
---|
491 | ThrowException(GameState, "Indentation error while parsing the hierarchy."); |
---|
492 | } |
---|
493 | } |
---|
494 | } |
---|
495 | |
---|
496 | void Game::loadGraphics() |
---|
497 | { |
---|
498 | if (!GameMode::showsGraphics()) |
---|
499 | { |
---|
500 | core_->loadGraphics(); |
---|
501 | Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics); |
---|
502 | |
---|
503 | // Construct all the GameStates that require graphics |
---|
504 | for (std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.begin(); |
---|
505 | it != gameStateDeclarations_s.end(); ++it) |
---|
506 | { |
---|
507 | if (it->second.bGraphicsMode) |
---|
508 | { |
---|
509 | // Game state loading failure is serious --> don't catch |
---|
510 | shared_ptr<GameState> gameState = GameStateFactory::fabricate(it->second); |
---|
511 | if (!constructedStates_.insert(std::make_pair( |
---|
512 | it->second.stateName, gameState)).second) |
---|
513 | assert(false); // GameState was already created! |
---|
514 | } |
---|
515 | } |
---|
516 | graphicsUnloader.Dismiss(); |
---|
517 | } |
---|
518 | } |
---|
519 | |
---|
520 | void Game::unloadGraphics() |
---|
521 | { |
---|
522 | if (GameMode::showsGraphics()) |
---|
523 | { |
---|
524 | // Destroy all the GameStates that require graphics |
---|
525 | for (GameStateMap::iterator it = constructedStates_.begin(); it != constructedStates_.end();) |
---|
526 | { |
---|
527 | if (it->second->getInfo().bGraphicsMode) |
---|
528 | constructedStates_.erase(it++); |
---|
529 | else |
---|
530 | ++it; |
---|
531 | } |
---|
532 | |
---|
533 | core_->unloadGraphics(); |
---|
534 | } |
---|
535 | } |
---|
536 | |
---|
537 | bool Game::checkState(const std::string& name) const |
---|
538 | { |
---|
539 | std::map<std::string, GameStateInfo>::const_iterator it = gameStateDeclarations_s.find(name); |
---|
540 | if (it == gameStateDeclarations_s.end()) |
---|
541 | return false; |
---|
542 | else |
---|
543 | return true; |
---|
544 | } |
---|
545 | |
---|
546 | void Game::loadState(const std::string& name) |
---|
547 | { |
---|
548 | this->bChangingState_ = true; |
---|
549 | LOKI_ON_BLOCK_EXIT_OBJ(*this, &Game::resetChangingState); |
---|
550 | |
---|
551 | // If state requires graphics, load it |
---|
552 | Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics); |
---|
553 | if (gameStateDeclarations_s[name].bGraphicsMode && !GameMode::showsGraphics()) |
---|
554 | this->loadGraphics(); |
---|
555 | else |
---|
556 | graphicsUnloader.Dismiss(); |
---|
557 | |
---|
558 | shared_ptr<GameState> state = this->getState(name); |
---|
559 | state->activate(); |
---|
560 | if (!this->loadedStates_.empty()) |
---|
561 | this->loadedStates_.back()->activity_.topState = false; |
---|
562 | this->loadedStates_.push_back(state); |
---|
563 | state->activity_.topState = true; |
---|
564 | |
---|
565 | graphicsUnloader.Dismiss(); |
---|
566 | } |
---|
567 | |
---|
568 | void Game::unloadState(const std::string& name) |
---|
569 | { |
---|
570 | this->bChangingState_ = true; |
---|
571 | try |
---|
572 | { |
---|
573 | shared_ptr<GameState> state = this->getState(name); |
---|
574 | state->activity_.topState = false; |
---|
575 | this->loadedStates_.pop_back(); |
---|
576 | if (!this->loadedStates_.empty()) |
---|
577 | this->loadedStates_.back()->activity_.topState = true; |
---|
578 | state->deactivate(); |
---|
579 | } |
---|
580 | catch (...) |
---|
581 | { |
---|
582 | COUT(2) << "Warning: Unloading GameState '" << name << "' threw an exception: " << Exception::handleMessage() << std::endl; |
---|
583 | COUT(2) << " There might be potential resource leaks involved! To avoid this, improve exception-safety." << std::endl; |
---|
584 | } |
---|
585 | // Check if graphics is still required |
---|
586 | if (!bAbort_) |
---|
587 | { |
---|
588 | bool graphicsRequired = false; |
---|
589 | for (unsigned i = 0; i < loadedStates_.size(); ++i) |
---|
590 | graphicsRequired |= loadedStates_[i]->getInfo().bGraphicsMode; |
---|
591 | if (!graphicsRequired) |
---|
592 | this->unloadGraphics(); |
---|
593 | } |
---|
594 | this->bChangingState_ = false; |
---|
595 | } |
---|
596 | |
---|
597 | /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories() |
---|
598 | { |
---|
599 | static std::map<std::string, shared_ptr<GameStateFactory> > factories; |
---|
600 | return factories; |
---|
601 | } |
---|
602 | |
---|
603 | /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info) |
---|
604 | { |
---|
605 | std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className); |
---|
606 | assert(it != getFactories().end()); |
---|
607 | return it->second->fabricateInternal(info); |
---|
608 | } |
---|
609 | } |
---|