Game.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "Platform.h"
  4. #include "RenderState.h"
  5. #include "FileSystem.h"
  6. #include "FrameBuffer.h"
  7. #include "SceneLoader.h"
  8. /** @script{ignore} */
  9. GLenum __gl_error_code = GL_NO_ERROR;
  10. /** @script{ignore} */
  11. ALenum __al_error_code = AL_NO_ERROR;
  12. namespace gameplay
  13. {
  14. static Game* __gameInstance = NULL;
  15. double Game::_pausedTimeLast = 0.0;
  16. double Game::_pausedTimeTotal = 0.0;
  17. Game::Game()
  18. : _initialized(false), _state(UNINITIALIZED), _pausedCount(0),
  19. _frameLastFPS(0), _frameCount(0), _frameRate(0),
  20. _clearDepth(1.0f), _clearStencil(0), _properties(NULL),
  21. _animationController(NULL), _audioController(NULL),
  22. _physicsController(NULL), _aiController(NULL), _audioListener(NULL),
  23. _timeEvents(NULL), _scriptController(NULL), _scriptListeners(NULL)
  24. {
  25. GP_ASSERT(__gameInstance == NULL);
  26. __gameInstance = this;
  27. _timeEvents = new std::priority_queue<TimeEvent, std::vector<TimeEvent>, std::less<TimeEvent> >();
  28. }
  29. Game::~Game()
  30. {
  31. SAFE_DELETE(_scriptController);
  32. // Do not call any virtual functions from the destructor.
  33. // Finalization is done from outside this class.
  34. SAFE_DELETE(_timeEvents);
  35. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  36. Ref::printLeaks();
  37. printMemoryLeaks();
  38. #endif
  39. }
  40. Game* Game::getInstance()
  41. {
  42. GP_ASSERT(__gameInstance);
  43. return __gameInstance;
  44. }
  45. double Game::getAbsoluteTime()
  46. {
  47. return Platform::getAbsoluteTime();
  48. }
  49. double Game::getGameTime()
  50. {
  51. return Platform::getAbsoluteTime() - _pausedTimeTotal;
  52. }
  53. void Game::setVsync(bool enable)
  54. {
  55. Platform::setVsync(enable);
  56. }
  57. bool Game::isVsync()
  58. {
  59. return Platform::isVsync();
  60. }
  61. int Game::run()
  62. {
  63. if (_state != UNINITIALIZED)
  64. return -1;
  65. loadConfig();
  66. _width = Platform::getDisplayWidth();
  67. _height = Platform::getDisplayHeight();
  68. // Start up game systems.
  69. if (!startup())
  70. {
  71. shutdown();
  72. return -2;
  73. }
  74. return 0;
  75. }
  76. bool Game::startup()
  77. {
  78. if (_state != UNINITIALIZED)
  79. return false;
  80. setViewport(Rectangle(0.0f, 0.0f, (float)_width, (float)_height));
  81. RenderState::initialize();
  82. FrameBuffer::initialize();
  83. _animationController = new AnimationController();
  84. _animationController->initialize();
  85. _audioController = new AudioController();
  86. _audioController->initialize();
  87. _physicsController = new PhysicsController();
  88. _physicsController->initialize();
  89. _aiController = new AIController();
  90. _aiController->initialize();
  91. _scriptController = new ScriptController();
  92. _scriptController->initialize();
  93. // Load any gamepads, ui or physical.
  94. loadGamepads();
  95. // Set the script callback functions.
  96. if (_properties)
  97. {
  98. Properties* scripts = _properties->getNamespace("scripts", true);
  99. if (scripts)
  100. {
  101. const char* callback;
  102. while ((callback = scripts->getNextProperty()) != NULL)
  103. {
  104. std::string url = scripts->getString();
  105. std::string file;
  106. std::string id;
  107. splitURL(url, &file, &id);
  108. if (file.size() <= 0 || id.size() <= 0)
  109. {
  110. GP_ERROR("Invalid %s script callback function '%s'.", callback, url.c_str());
  111. }
  112. else
  113. {
  114. _scriptController->loadScript(file.c_str());
  115. _scriptController->registerCallback(callback, id.c_str());
  116. }
  117. }
  118. }
  119. }
  120. _state = RUNNING;
  121. return true;
  122. }
  123. void Game::shutdown()
  124. {
  125. // Call user finalization.
  126. if (_state != UNINITIALIZED)
  127. {
  128. GP_ASSERT(_animationController);
  129. GP_ASSERT(_audioController);
  130. GP_ASSERT(_physicsController);
  131. GP_ASSERT(_aiController);
  132. Platform::signalShutdown();
  133. // Call user finalize
  134. finalize();
  135. // Shutdown scripting system first so that any objects allocated in script are released before our subsystems are released
  136. _scriptController->finalizeGame();
  137. if (_scriptListeners)
  138. {
  139. for (size_t i = 0; i < _scriptListeners->size(); i++)
  140. {
  141. SAFE_DELETE((*_scriptListeners)[i]);
  142. }
  143. SAFE_DELETE(_scriptListeners);
  144. }
  145. _scriptController->finalize();
  146. unsigned int gamepadCount = Gamepad::getGamepadCount();
  147. for (unsigned int i = 0; i < gamepadCount; i++)
  148. {
  149. Gamepad* gamepad = Gamepad::getGamepad(i, false);
  150. SAFE_DELETE(gamepad);
  151. }
  152. _animationController->finalize();
  153. SAFE_DELETE(_animationController);
  154. _audioController->finalize();
  155. SAFE_DELETE(_audioController);
  156. _physicsController->finalize();
  157. SAFE_DELETE(_physicsController);
  158. _aiController->finalize();
  159. SAFE_DELETE(_aiController);
  160. // Note: we do not clean up the script controller here
  161. // because users can call Game::exit() from a script.
  162. SAFE_DELETE(_audioListener);
  163. FrameBuffer::finalize();
  164. RenderState::finalize();
  165. SAFE_DELETE(_properties);
  166. _state = UNINITIALIZED;
  167. }
  168. }
  169. void Game::pause()
  170. {
  171. if (_state == RUNNING)
  172. {
  173. GP_ASSERT(_animationController);
  174. GP_ASSERT(_audioController);
  175. GP_ASSERT(_physicsController);
  176. GP_ASSERT(_aiController);
  177. _state = PAUSED;
  178. _pausedTimeLast = Platform::getAbsoluteTime();
  179. _animationController->pause();
  180. _audioController->pause();
  181. _physicsController->pause();
  182. _aiController->pause();
  183. }
  184. ++_pausedCount;
  185. }
  186. void Game::resume()
  187. {
  188. if (_state == PAUSED)
  189. {
  190. --_pausedCount;
  191. if (_pausedCount == 0)
  192. {
  193. GP_ASSERT(_animationController);
  194. GP_ASSERT(_audioController);
  195. GP_ASSERT(_physicsController);
  196. GP_ASSERT(_aiController);
  197. _state = RUNNING;
  198. _pausedTimeTotal += Platform::getAbsoluteTime() - _pausedTimeLast;
  199. _animationController->resume();
  200. _audioController->resume();
  201. _physicsController->resume();
  202. _aiController->resume();
  203. }
  204. }
  205. }
  206. void Game::exit()
  207. {
  208. // Only perform a full/clean shutdown if FORCE_CLEAN_SHUTDOWN or
  209. // GAMEPLAY_MEM_LEAK_DETECTION is defined. Every modern OS is able to
  210. // handle reclaiming process memory hundreds of times faster than it
  211. // would take us to go through every pointer in the engine and release
  212. // them nicely. For large games, shutdown can end up taking long time,
  213. // so we'll just call ::exit(0) to force an instant shutdown.
  214. #if defined FORCE_CLEAN_SHUTDOWN || defined GAMEPLAY_MEM_LEAK_DETECTION
  215. // Schedule a call to shutdown rather than calling it right away.
  216. // This handles the case of shutting down the script system from
  217. // within a script function (which can cause errors).
  218. static ShutdownListener listener;
  219. schedule(0, &listener);
  220. #else
  221. // End the process immediately without a full shutdown
  222. ::exit(0);
  223. #endif
  224. }
  225. void Game::frame()
  226. {
  227. if (!_initialized)
  228. {
  229. // Perform lazy first time initialization
  230. initialize();
  231. _scriptController->initializeGame();
  232. _initialized = true;
  233. // Fire first game resize event
  234. Platform::resizeEventInternal(_width, _height);
  235. }
  236. static double lastFrameTime = Game::getGameTime();
  237. double frameTime = getGameTime();
  238. // Fire time events to scheduled TimeListeners
  239. fireTimeEvents(frameTime);
  240. if (_state == Game::RUNNING)
  241. {
  242. GP_ASSERT(_animationController);
  243. GP_ASSERT(_audioController);
  244. GP_ASSERT(_physicsController);
  245. GP_ASSERT(_aiController);
  246. // Update Time.
  247. float elapsedTime = (frameTime - lastFrameTime);
  248. lastFrameTime = frameTime;
  249. // Update the scheduled and running animations.
  250. _animationController->update(elapsedTime);
  251. // Update the physics.
  252. _physicsController->update(elapsedTime);
  253. // Update AI.
  254. _aiController->update(elapsedTime);
  255. // Update gamepads.
  256. Gamepad::updateInternal(elapsedTime);
  257. // Application Update.
  258. update(elapsedTime);
  259. // Update forms.
  260. Form::updateInternal(elapsedTime);
  261. // Run script update.
  262. _scriptController->update(elapsedTime);
  263. // Audio Rendering.
  264. _audioController->update(elapsedTime);
  265. // Graphics Rendering.
  266. render(elapsedTime);
  267. // Run script render.
  268. _scriptController->render(elapsedTime);
  269. // Update FPS.
  270. ++_frameCount;
  271. if ((Game::getGameTime() - _frameLastFPS) >= 1000)
  272. {
  273. _frameRate = _frameCount;
  274. _frameCount = 0;
  275. _frameLastFPS = getGameTime();
  276. }
  277. }
  278. else if (_state == Game::PAUSED)
  279. {
  280. // Update gamepads.
  281. Gamepad::updateInternal(0);
  282. // Update forms.
  283. Form::updateInternal(0);
  284. // Application Update.
  285. update(0);
  286. // Script update.
  287. _scriptController->update(0);
  288. // Graphics Rendering.
  289. render(0);
  290. // Script render.
  291. _scriptController->render(0);
  292. }
  293. }
  294. void Game::renderOnce(const char* function)
  295. {
  296. _scriptController->executeFunction<void>(function, NULL);
  297. Platform::swapBuffers();
  298. }
  299. void Game::updateOnce()
  300. {
  301. GP_ASSERT(_animationController);
  302. GP_ASSERT(_audioController);
  303. GP_ASSERT(_physicsController);
  304. GP_ASSERT(_aiController);
  305. // Update Time.
  306. static double lastFrameTime = getGameTime();
  307. double frameTime = getGameTime();
  308. float elapsedTime = (frameTime - lastFrameTime);
  309. lastFrameTime = frameTime;
  310. // Update the internal controllers.
  311. _animationController->update(elapsedTime);
  312. _physicsController->update(elapsedTime);
  313. _aiController->update(elapsedTime);
  314. _audioController->update(elapsedTime);
  315. _scriptController->update(elapsedTime);
  316. }
  317. void Game::setViewport(const Rectangle& viewport)
  318. {
  319. _viewport = viewport;
  320. glViewport((GLuint)viewport.x, (GLuint)viewport.y, (GLuint)viewport.width, (GLuint)viewport.height);
  321. }
  322. void Game::clear(ClearFlags flags, const Vector4& clearColor, float clearDepth, int clearStencil)
  323. {
  324. GLbitfield bits = 0;
  325. if (flags & CLEAR_COLOR)
  326. {
  327. if (clearColor.x != _clearColor.x ||
  328. clearColor.y != _clearColor.y ||
  329. clearColor.z != _clearColor.z ||
  330. clearColor.w != _clearColor.w )
  331. {
  332. glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  333. _clearColor.set(clearColor);
  334. }
  335. bits |= GL_COLOR_BUFFER_BIT;
  336. }
  337. if (flags & CLEAR_DEPTH)
  338. {
  339. if (clearDepth != _clearDepth)
  340. {
  341. glClearDepth(clearDepth);
  342. _clearDepth = clearDepth;
  343. }
  344. bits |= GL_DEPTH_BUFFER_BIT;
  345. // We need to explicitly call the static enableDepthWrite() method on StateBlock
  346. // to ensure depth writing is enabled before clearing the depth buffer (and to
  347. // update the global StateBlock render state to reflect this).
  348. RenderState::StateBlock::enableDepthWrite();
  349. }
  350. if (flags & CLEAR_STENCIL)
  351. {
  352. if (clearStencil != _clearStencil)
  353. {
  354. glClearStencil(clearStencil);
  355. _clearStencil = clearStencil;
  356. }
  357. bits |= GL_STENCIL_BUFFER_BIT;
  358. }
  359. glClear(bits);
  360. }
  361. void Game::clear(ClearFlags flags, float red, float green, float blue, float alpha, float clearDepth, int clearStencil)
  362. {
  363. clear(flags, Vector4(red, green, blue, alpha), clearDepth, clearStencil);
  364. }
  365. AudioListener* Game::getAudioListener()
  366. {
  367. if (_audioListener == NULL)
  368. {
  369. _audioListener = new AudioListener();
  370. }
  371. return _audioListener;
  372. }
  373. void Game::menuEvent()
  374. {
  375. }
  376. void Game::keyEvent(Keyboard::KeyEvent evt, int key)
  377. {
  378. }
  379. void Game::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  380. {
  381. }
  382. bool Game::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  383. {
  384. return false;
  385. }
  386. void Game::resizeEvent(unsigned int width, unsigned int height)
  387. {
  388. }
  389. bool Game::isGestureSupported(Gesture::GestureEvent evt)
  390. {
  391. return Platform::isGestureSupported(evt);
  392. }
  393. void Game::registerGesture(Gesture::GestureEvent evt)
  394. {
  395. Platform::registerGesture(evt);
  396. }
  397. void Game::unregisterGesture(Gesture::GestureEvent evt)
  398. {
  399. Platform::unregisterGesture(evt);
  400. }
  401. bool Game::isGestureRegistered(Gesture::GestureEvent evt)
  402. {
  403. return Platform::isGestureRegistered(evt);
  404. }
  405. void Game::gestureSwipeEvent(int x, int y, int direction)
  406. {
  407. }
  408. void Game::gesturePinchEvent(int x, int y, float scale)
  409. {
  410. }
  411. void Game::gestureTapEvent(int x, int y)
  412. {
  413. }
  414. void Game::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad, unsigned int analogIndex)
  415. {
  416. }
  417. void Game::getArguments(int* argc, char*** argv) const
  418. {
  419. Platform::getArguments(argc, argv);
  420. }
  421. void Game::schedule(float timeOffset, TimeListener* timeListener, void* cookie)
  422. {
  423. GP_ASSERT(_timeEvents);
  424. TimeEvent timeEvent(getGameTime() + timeOffset, timeListener, cookie);
  425. _timeEvents->push(timeEvent);
  426. }
  427. void Game::schedule(float timeOffset, const char* function)
  428. {
  429. if (!_scriptListeners)
  430. _scriptListeners = new std::vector<ScriptListener*>();
  431. ScriptListener* listener = new ScriptListener(function);
  432. _scriptListeners->push_back(listener);
  433. schedule(timeOffset, listener, NULL);
  434. }
  435. void Game::fireTimeEvents(double frameTime)
  436. {
  437. while (_timeEvents->size() > 0)
  438. {
  439. const TimeEvent* timeEvent = &_timeEvents->top();
  440. if (timeEvent->time > frameTime)
  441. {
  442. break;
  443. }
  444. if (timeEvent->listener)
  445. {
  446. timeEvent->listener->timeEvent(frameTime - timeEvent->time, timeEvent->cookie);
  447. }
  448. _timeEvents->pop();
  449. }
  450. }
  451. Game::ScriptListener::ScriptListener(const char* url)
  452. {
  453. function = Game::getInstance()->getScriptController()->loadUrl(url);
  454. }
  455. void Game::ScriptListener::timeEvent(long timeDiff, void* cookie)
  456. {
  457. Game::getInstance()->getScriptController()->executeFunction<void>(function.c_str(), "l", timeDiff);
  458. }
  459. Game::TimeEvent::TimeEvent(double time, TimeListener* timeListener, void* cookie)
  460. : time(time), listener(timeListener), cookie(cookie)
  461. {
  462. }
  463. bool Game::TimeEvent::operator<(const TimeEvent& v) const
  464. {
  465. // The first element of std::priority_queue is the greatest.
  466. return time > v.time;
  467. }
  468. Properties* Game::getConfig() const
  469. {
  470. if (_properties == NULL)
  471. const_cast<Game*>(this)->loadConfig();
  472. return _properties;
  473. }
  474. void Game::loadConfig()
  475. {
  476. if (_properties == NULL)
  477. {
  478. // Try to load custom config from file.
  479. if (FileSystem::fileExists("game.config"))
  480. {
  481. _properties = Properties::create("game.config");
  482. // Load filesystem aliases.
  483. Properties* aliases = _properties->getNamespace("aliases", true);
  484. if (aliases)
  485. {
  486. FileSystem::loadResourceAliases(aliases);
  487. }
  488. }
  489. else
  490. {
  491. // Create an empty config
  492. _properties = new Properties();
  493. }
  494. }
  495. }
  496. void Game::loadGamepads()
  497. {
  498. // Load virtual gamepads.
  499. if (_properties)
  500. {
  501. // Check if there are any virtual gamepads included in the .config file.
  502. // If there are, create and initialize them.
  503. _properties->rewind();
  504. Properties* inner = _properties->getNextNamespace();
  505. while (inner != NULL)
  506. {
  507. std::string spaceName(inner->getNamespace());
  508. // This namespace was accidentally named "gamepads" originally but we'll keep this check
  509. // for backwards compatibility.
  510. if (spaceName == "gamepads" || spaceName == "gamepad")
  511. {
  512. if (inner->exists("form"))
  513. {
  514. const char* gamepadFormPath = inner->getString("form");
  515. GP_ASSERT(gamepadFormPath);
  516. Gamepad* gamepad = Gamepad::add(gamepadFormPath);
  517. GP_ASSERT(gamepad);
  518. }
  519. }
  520. inner = _properties->getNextNamespace();
  521. }
  522. }
  523. }
  524. void Game::ShutdownListener::timeEvent(long timeDiff, void* cookie)
  525. {
  526. Game::getInstance()->shutdown();
  527. }
  528. }