Game.cpp 14 KB

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