Game.cpp 15 KB

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