Game.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. #include "ScriptListener.h"
  9. GLenum __gl_error_code = GL_NO_ERROR;
  10. ALenum __al_error_code = AL_NO_ERROR;
  11. namespace gameplay
  12. {
  13. static Game* __gameInstance = NULL;
  14. double Game::_pausedTimeLast = 0.0;
  15. double Game::_pausedTimeTotal = 0.0;
  16. Game::Game()
  17. : _initialized(false), _state(UNINITIALIZED),
  18. _frameLastFPS(0), _frameCount(0), _frameRate(0),
  19. _clearDepth(1.0f), _clearStencil(0), _properties(NULL),
  20. _animationController(NULL), _audioController(NULL),
  21. _physicsController(NULL), _audioListener(NULL), _scriptController(NULL),
  22. _scriptListeners(NULL)
  23. {
  24. GP_ASSERT(__gameInstance == NULL);
  25. __gameInstance = this;
  26. _timeEvents = new std::priority_queue<TimeEvent, std::vector<TimeEvent>, std::less<TimeEvent> >();
  27. }
  28. Game::~Game()
  29. {
  30. if (_scriptListeners)
  31. {
  32. for (unsigned int i = 0; i < _scriptListeners->size(); i++)
  33. {
  34. SAFE_DELETE((*_scriptListeners)[i]);
  35. }
  36. SAFE_DELETE(_scriptListeners);
  37. }
  38. if (_scriptController)
  39. {
  40. _scriptController->finalize();
  41. SAFE_DELETE(_scriptController);
  42. }
  43. // Do not call any virtual functions from the destructor.
  44. // Finalization is done from outside this class.
  45. SAFE_DELETE(_timeEvents);
  46. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  47. Ref::printLeaks();
  48. printMemoryLeaks();
  49. #endif
  50. }
  51. Game* Game::getInstance()
  52. {
  53. GP_ASSERT(__gameInstance);
  54. return __gameInstance;
  55. }
  56. double Game::getAbsoluteTime()
  57. {
  58. return Platform::getAbsoluteTime();
  59. }
  60. double Game::getGameTime()
  61. {
  62. return Platform::getAbsoluteTime() - _pausedTimeTotal;
  63. }
  64. void Game::setVsync(bool enable)
  65. {
  66. Platform::setVsync(enable);
  67. }
  68. bool Game::isVsync()
  69. {
  70. return Platform::isVsync();
  71. }
  72. int Game::run()
  73. {
  74. if (_state != UNINITIALIZED)
  75. return -1;
  76. loadConfig();
  77. _width = Platform::getDisplayWidth();
  78. _height = Platform::getDisplayHeight();
  79. // Start up game systems.
  80. if (!startup())
  81. {
  82. shutdown();
  83. return -2;
  84. }
  85. return 0;
  86. }
  87. bool Game::startup()
  88. {
  89. if (_state != UNINITIALIZED)
  90. return false;
  91. setViewport(Rectangle(0.0f, 0.0f, (float)_width, (float)_height));
  92. RenderState::initialize();
  93. FrameBuffer::initialize();
  94. _animationController = new AnimationController();
  95. _animationController->initialize();
  96. _audioController = new AudioController();
  97. _audioController->initialize();
  98. _physicsController = new PhysicsController();
  99. _physicsController->initialize();
  100. loadGamepads();
  101. _scriptController = new ScriptController();
  102. _scriptController->initialize();
  103. // Set the script callback functions.
  104. if (_properties)
  105. {
  106. Properties* scripts = _properties->getNamespace("scripts", true);
  107. if (scripts)
  108. {
  109. const char* name;
  110. while ((name = scripts->getNextProperty()) != NULL)
  111. {
  112. ScriptController::ScriptCallback callback = toCallback(name);
  113. if (callback != ScriptController::INVALID_CALLBACK)
  114. {
  115. std::string url = scripts->getString();
  116. std::string file;
  117. std::string id;
  118. splitURL(url, &file, &id);
  119. if (file.size() <= 0 || id.size() <= 0)
  120. {
  121. GP_ERROR("Invalid %s script callback function '%s'.", name, url.c_str());
  122. }
  123. else
  124. {
  125. _scriptController->loadScript(file.c_str());
  126. _scriptController->registerCallback(callback, id);
  127. }
  128. }
  129. else
  130. {
  131. // Ignore everything else.
  132. }
  133. }
  134. }
  135. }
  136. _state = RUNNING;
  137. return true;
  138. }
  139. void Game::shutdown()
  140. {
  141. // Call user finalization.
  142. if (_state != UNINITIALIZED)
  143. {
  144. GP_ASSERT(_animationController);
  145. GP_ASSERT(_audioController);
  146. GP_ASSERT(_physicsController);
  147. Platform::signalShutdown();
  148. finalize();
  149. for (std::vector<Gamepad*>::iterator itr = _gamepads.begin(); itr != _gamepads.end(); itr++)
  150. {
  151. SAFE_DELETE((*itr));
  152. }
  153. _gamepads.clear();
  154. _scriptController->finalizeGame();
  155. _animationController->finalize();
  156. SAFE_DELETE(_animationController);
  157. _audioController->finalize();
  158. SAFE_DELETE(_audioController);
  159. _physicsController->finalize();
  160. SAFE_DELETE(_physicsController);
  161. // Note: we do not clean up the script controller here
  162. // because users can call Game::exit() from a script.
  163. SAFE_DELETE(_audioListener);
  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. _state = PAUSED;
  177. _pausedTimeLast = Platform::getAbsoluteTime();
  178. _animationController->pause();
  179. _audioController->pause();
  180. _physicsController->pause();
  181. }
  182. }
  183. void Game::resume()
  184. {
  185. if (_state == PAUSED)
  186. {
  187. GP_ASSERT(_animationController);
  188. GP_ASSERT(_audioController);
  189. GP_ASSERT(_physicsController);
  190. _state = RUNNING;
  191. _pausedTimeTotal += Platform::getAbsoluteTime() - _pausedTimeLast;
  192. _animationController->resume();
  193. _audioController->resume();
  194. _physicsController->resume();
  195. }
  196. }
  197. void Game::exit()
  198. {
  199. shutdown();
  200. }
  201. void Game::frame()
  202. {
  203. if (!_initialized)
  204. {
  205. initialize();
  206. _scriptController->initializeGame();
  207. _initialized = true;
  208. }
  209. if (_state == Game::RUNNING)
  210. {
  211. GP_ASSERT(_animationController);
  212. GP_ASSERT(_audioController);
  213. GP_ASSERT(_physicsController);
  214. // Update Time.
  215. static double lastFrameTime = Game::getGameTime();
  216. double frameTime = getGameTime();
  217. float elapsedTime = (frameTime - lastFrameTime);
  218. lastFrameTime = frameTime;
  219. // Update the scheduled and running animations.
  220. _animationController->update(elapsedTime);
  221. // Fire time events to scheduled TimeListeners
  222. fireTimeEvents(frameTime);
  223. // Update the physics.
  224. _physicsController->update(elapsedTime);
  225. // Application Update.
  226. update(elapsedTime);
  227. // Run script update.
  228. _scriptController->update(elapsedTime);
  229. // Audio Rendering.
  230. _audioController->update(elapsedTime);
  231. // Graphics Rendering.
  232. render(elapsedTime);
  233. // Run script render.
  234. _scriptController->render(elapsedTime);
  235. // Update FPS.
  236. ++_frameCount;
  237. if ((Game::getGameTime() - _frameLastFPS) >= 1000)
  238. {
  239. _frameRate = _frameCount;
  240. _frameCount = 0;
  241. _frameLastFPS = getGameTime();
  242. }
  243. }
  244. else
  245. {
  246. // Application Update.
  247. update(0);
  248. // Script update.
  249. _scriptController->update(0);
  250. // Graphics Rendering.
  251. render(0);
  252. // Script render.
  253. _scriptController->render(0);
  254. }
  255. }
  256. void Game::updateOnce()
  257. {
  258. GP_ASSERT(_animationController);
  259. GP_ASSERT(_audioController);
  260. GP_ASSERT(_physicsController);
  261. // Update Time.
  262. static double lastFrameTime = getGameTime();
  263. double frameTime = getGameTime();
  264. float elapsedTime = (frameTime - lastFrameTime);
  265. lastFrameTime = frameTime;
  266. // Update the internal controllers.
  267. _animationController->update(elapsedTime);
  268. _physicsController->update(elapsedTime);
  269. _audioController->update(elapsedTime);
  270. _scriptController->update(elapsedTime);
  271. }
  272. void Game::setViewport(const Rectangle& viewport)
  273. {
  274. _viewport = viewport;
  275. glViewport((GLuint)viewport.x, (GLuint)viewport.y, (GLuint)viewport.width, (GLuint)viewport.height);
  276. }
  277. void Game::clear(ClearFlags flags, const Vector4& clearColor, float clearDepth, int clearStencil)
  278. {
  279. GLbitfield bits = 0;
  280. if (flags & CLEAR_COLOR)
  281. {
  282. if (clearColor.x != _clearColor.x ||
  283. clearColor.y != _clearColor.y ||
  284. clearColor.z != _clearColor.z ||
  285. clearColor.w != _clearColor.w )
  286. {
  287. glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  288. _clearColor.set(clearColor);
  289. }
  290. bits |= GL_COLOR_BUFFER_BIT;
  291. }
  292. if (flags & CLEAR_DEPTH)
  293. {
  294. if (clearDepth != _clearDepth)
  295. {
  296. glClearDepth(clearDepth);
  297. _clearDepth = clearDepth;
  298. }
  299. bits |= GL_DEPTH_BUFFER_BIT;
  300. // We need to explicitly call the static enableDepthWrite() method on StateBlock
  301. // to ensure depth writing is enabled before clearing the depth buffer (and to
  302. // update the global StateBlock render state to reflect this).
  303. RenderState::StateBlock::enableDepthWrite();
  304. }
  305. if (flags & CLEAR_STENCIL)
  306. {
  307. if (clearStencil != _clearStencil)
  308. {
  309. glClearStencil(clearStencil);
  310. _clearStencil = clearStencil;
  311. }
  312. bits |= GL_STENCIL_BUFFER_BIT;
  313. }
  314. glClear(bits);
  315. }
  316. AudioListener* Game::getAudioListener()
  317. {
  318. if (_audioListener == NULL)
  319. {
  320. _audioListener = new AudioListener();
  321. }
  322. return _audioListener;
  323. }
  324. void Game::menuEvent()
  325. {
  326. }
  327. void Game::keyEvent(Keyboard::KeyEvent evt, int key)
  328. {
  329. }
  330. void Game::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  331. {
  332. }
  333. bool Game::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  334. {
  335. return false;
  336. }
  337. void Game::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
  338. {
  339. }
  340. void Game::schedule(float timeOffset, TimeListener* timeListener, void* cookie)
  341. {
  342. GP_ASSERT(_timeEvents);
  343. TimeEvent timeEvent(getGameTime() + timeOffset, timeListener, cookie);
  344. _timeEvents->push(timeEvent);
  345. }
  346. void Game::schedule(float timeOffset, const char* function)
  347. {
  348. if (!_scriptListeners)
  349. _scriptListeners = new std::vector<ScriptListener*>();
  350. ScriptListener* listener = new ScriptListener(function);
  351. _scriptListeners->push_back(listener);
  352. schedule(timeOffset, listener, NULL);
  353. }
  354. void Game::fireTimeEvents(double frameTime)
  355. {
  356. while (_timeEvents->size() > 0)
  357. {
  358. const TimeEvent* timeEvent = &_timeEvents->top();
  359. if (timeEvent->time > frameTime)
  360. {
  361. break;
  362. }
  363. if (timeEvent->listener)
  364. {
  365. timeEvent->listener->timeEvent(frameTime - timeEvent->time, timeEvent->cookie);
  366. }
  367. _timeEvents->pop();
  368. }
  369. }
  370. Game::TimeEvent::TimeEvent(double time, TimeListener* timeListener, void* cookie)
  371. : time(time), listener(timeListener), cookie(cookie)
  372. {
  373. }
  374. bool Game::TimeEvent::operator<(const TimeEvent& v) const
  375. {
  376. // The first element of std::priority_queue is the greatest.
  377. return time > v.time;
  378. }
  379. Properties* Game::getConfig() const
  380. {
  381. if (_properties == NULL)
  382. const_cast<Game*>(this)->loadConfig();
  383. return _properties;
  384. }
  385. void Game::loadConfig()
  386. {
  387. if (_properties == NULL)
  388. {
  389. // Try to load custom config from file.
  390. if (FileSystem::fileExists("game.config"))
  391. {
  392. _properties = Properties::create("game.config");
  393. // Load filesystem aliases.
  394. Properties* aliases = _properties->getNamespace("aliases", true);
  395. if (aliases)
  396. {
  397. FileSystem::loadResourceAliases(aliases);
  398. }
  399. }
  400. }
  401. }
  402. void Game::loadGamepads()
  403. {
  404. if (_properties)
  405. {
  406. // Check if there is a virtual keyboard included in the .config file.
  407. // If there is, try to create it and assign it to "player one".
  408. Properties* gamepadProperties = _properties->getNamespace("gamepads", true);
  409. if (gamepadProperties && gamepadProperties->exists("form"))
  410. {
  411. const char* gamepadFormPath = gamepadProperties->getString("form");
  412. GP_ASSERT(gamepadFormPath);
  413. Gamepad* gamepad = createGamepad(gamepadProperties->getId(), gamepadFormPath);
  414. GP_ASSERT(gamepad);
  415. }
  416. }
  417. }
  418. Gamepad* Game::createGamepad(const char* gamepadId, const char* gamepadFormPath)
  419. {
  420. GP_ASSERT(gamepadFormPath);
  421. Gamepad* gamepad = new Gamepad(gamepadId, gamepadFormPath);
  422. GP_ASSERT(gamepad);
  423. _gamepads.push_back(gamepad);
  424. return gamepad;
  425. }
  426. ScriptController::ScriptCallback Game::toCallback(const char* name)
  427. {
  428. if (strcmp(name, "INITIALIZE") == 0)
  429. return ScriptController::INITIALIZE;
  430. else if (strcmp(name, "UPDATE") == 0)
  431. return ScriptController::UPDATE;
  432. else if (strcmp(name, "RENDER") == 0)
  433. return ScriptController::RENDER;
  434. else if (strcmp(name, "FINALIZE") == 0)
  435. return ScriptController::FINALIZE;
  436. else if (strcmp(name, "KEY_EVENT") == 0)
  437. return ScriptController::KEY_EVENT;
  438. else if (strcmp(name, "TOUCH_EVENT") == 0)
  439. return ScriptController::TOUCH_EVENT;
  440. else if (strcmp(name, "MOUSE_EVENT") == 0)
  441. return ScriptController::MOUSE_EVENT;
  442. else if (strcmp(name, "GAMEPAD_EVENT") == 0)
  443. return ScriptController::GAMEPAD_EVENT;
  444. else
  445. return ScriptController::INVALID_CALLBACK;
  446. }
  447. }