CGuiHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. /*
  2. * CGuiHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGuiHandler.h"
  12. #include "../lib/CondSh.h"
  13. #include <SDL.h>
  14. #include "CIntObject.h"
  15. #include "CCursorHandler.h"
  16. #include "../CGameInfo.h"
  17. #include "../../lib/CThreadHelper.h"
  18. #include "../../lib/CConfigHandler.h"
  19. #include "../CMT.h"
  20. #include "../CPlayerInterface.h"
  21. #include "../battle/CBattleInterface.h"
  22. extern std::queue<SDL_Event> SDLEventsQueue;
  23. extern boost::mutex eventsM;
  24. boost::thread_specific_ptr<bool> inGuiThread;
  25. SObjectConstruction::SObjectConstruction(CIntObject *obj)
  26. :myObj(obj)
  27. {
  28. GH.createdObj.push_front(obj);
  29. GH.captureChildren = true;
  30. }
  31. SObjectConstruction::~SObjectConstruction()
  32. {
  33. assert(GH.createdObj.size());
  34. assert(GH.createdObj.front() == myObj);
  35. GH.createdObj.pop_front();
  36. GH.captureChildren = GH.createdObj.size();
  37. }
  38. SSetCaptureState::SSetCaptureState(bool allow, ui8 actions)
  39. {
  40. previousCapture = GH.captureChildren;
  41. GH.captureChildren = false;
  42. prevActions = GH.defActionsDef;
  43. GH.defActionsDef = actions;
  44. }
  45. SSetCaptureState::~SSetCaptureState()
  46. {
  47. GH.captureChildren = previousCapture;
  48. GH.defActionsDef = prevActions;
  49. }
  50. static inline void
  51. processList(const ui16 mask, const ui16 flag, std::list<CIntObject*> *lst, std::function<void (std::list<CIntObject*> *)> cb)
  52. {
  53. if (mask & flag)
  54. cb(lst);
  55. }
  56. void CGuiHandler::processLists(const ui16 activityFlag, std::function<void (std::list<CIntObject*> *)> cb)
  57. {
  58. processList(CIntObject::LCLICK,activityFlag,&lclickable,cb);
  59. processList(CIntObject::RCLICK,activityFlag,&rclickable,cb);
  60. processList(CIntObject::MCLICK,activityFlag,&mclickable,cb);
  61. processList(CIntObject::HOVER,activityFlag,&hoverable,cb);
  62. processList(CIntObject::MOVE,activityFlag,&motioninterested,cb);
  63. processList(CIntObject::KEYBOARD,activityFlag,&keyinterested,cb);
  64. processList(CIntObject::TIME,activityFlag,&timeinterested,cb);
  65. processList(CIntObject::WHEEL,activityFlag,&wheelInterested,cb);
  66. processList(CIntObject::DOUBLECLICK,activityFlag,&doubleClickInterested,cb);
  67. processList(CIntObject::TEXTINPUT,activityFlag,&textInterested,cb);
  68. }
  69. void CGuiHandler::handleElementActivate(CIntObject * elem, ui16 activityFlag)
  70. {
  71. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  72. lst->push_front(elem);
  73. });
  74. elem->active_m |= activityFlag;
  75. }
  76. void CGuiHandler::handleElementDeActivate(CIntObject * elem, ui16 activityFlag)
  77. {
  78. processLists(activityFlag,[&](std::list<CIntObject*> * lst){
  79. auto hlp = std::find(lst->begin(),lst->end(),elem);
  80. assert(hlp != lst->end());
  81. lst->erase(hlp);
  82. });
  83. elem->active_m &= ~activityFlag;
  84. }
  85. void CGuiHandler::popInt(std::shared_ptr<IShowActivatable> top)
  86. {
  87. assert(listInt.front() == top);
  88. top->deactivate();
  89. disposed.push_back(top);
  90. listInt.pop_front();
  91. objsToBlit -= top;
  92. if(!listInt.empty())
  93. listInt.front()->activate();
  94. totalRedraw();
  95. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  96. }
  97. void CGuiHandler::pushInt(std::shared_ptr<IShowActivatable> newInt)
  98. {
  99. assert(newInt);
  100. assert(!vstd::contains(listInt, newInt)); // do not add same object twice
  101. //a new interface will be present, we'll need to use buffer surface (unless it's advmapint that will alter screenBuf on activate anyway)
  102. screenBuf = screen2;
  103. if(!listInt.empty())
  104. listInt.front()->deactivate();
  105. listInt.push_front(newInt);
  106. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  107. newInt->activate();
  108. objsToBlit.push_back(newInt);
  109. totalRedraw();
  110. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  111. }
  112. void CGuiHandler::popInts(int howMany)
  113. {
  114. if(!howMany) return; //senseless but who knows...
  115. assert(listInt.size() >= howMany);
  116. listInt.front()->deactivate();
  117. for(int i=0; i < howMany; i++)
  118. {
  119. objsToBlit -= listInt.front();
  120. disposed.push_back(listInt.front());
  121. listInt.pop_front();
  122. }
  123. if(!listInt.empty())
  124. {
  125. listInt.front()->activate();
  126. totalRedraw();
  127. }
  128. fakeMouseMove();
  129. pushSDLEvent(SDL_USEREVENT, EUserEvent::INTERFACE_CHANGED);
  130. }
  131. std::shared_ptr<IShowActivatable> CGuiHandler::topInt()
  132. {
  133. if(listInt.empty())
  134. return std::shared_ptr<IShowActivatable>();
  135. else
  136. return listInt.front();
  137. }
  138. void CGuiHandler::totalRedraw()
  139. {
  140. #ifdef VCMI_ANDROID
  141. SDL_FillRect(screen2, NULL, SDL_MapRGB(screen2->format, 0, 0, 0));
  142. #endif
  143. for(auto & elem : objsToBlit)
  144. elem->showAll(screen2);
  145. blitAt(screen2,0,0,screen);
  146. }
  147. void CGuiHandler::updateTime()
  148. {
  149. int ms = mainFPSmng->getElapsedMilliseconds();
  150. std::list<CIntObject*> hlp = timeinterested;
  151. for (auto & elem : hlp)
  152. {
  153. if(!vstd::contains(timeinterested,elem)) continue;
  154. (elem)->onTimer(ms);
  155. }
  156. }
  157. void CGuiHandler::handleEvents()
  158. {
  159. //player interface may want special event handling
  160. if(nullptr != LOCPLINT && LOCPLINT->capturedAllEvents())
  161. return;
  162. boost::unique_lock<boost::mutex> lock(eventsM);
  163. while(!SDLEventsQueue.empty())
  164. {
  165. continueEventHandling = true;
  166. SDL_Event ev = SDLEventsQueue.front();
  167. current = &ev;
  168. SDLEventsQueue.pop();
  169. // In a sequence of mouse motion events, skip all but the last one.
  170. // This prevents freezes when every motion event takes longer to handle than interval at which
  171. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  172. // so that the events would start piling up faster than they can be processed.
  173. if ((ev.type == SDL_MOUSEMOTION) && !SDLEventsQueue.empty() && (SDLEventsQueue.front().type == SDL_MOUSEMOTION))
  174. continue;
  175. handleCurrentEvent();
  176. }
  177. }
  178. bool multifinger = false;
  179. int lastFingerCount;
  180. void convertTouch(SDL_Event * current)
  181. {
  182. int rLogicalWidth, rLogicalHeight;
  183. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  184. int adjustedMouseY = (int)(current->tfinger.y * rLogicalHeight);
  185. int adjustedMouseX = (int)(current->tfinger.x * rLogicalWidth);
  186. current->button.x = adjustedMouseX;
  187. current->motion.x = adjustedMouseX;
  188. current->button.y = adjustedMouseY;
  189. current->motion.y = adjustedMouseY;
  190. }
  191. void CGuiHandler::handleCurrentEvent()
  192. {
  193. if(current->type == SDL_KEYDOWN || current->type == SDL_KEYUP)
  194. {
  195. SDL_KeyboardEvent key = current->key;
  196. if(current->type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  197. {
  198. //TODO: we need some central place for all interface-independent hotkeys
  199. Settings s = settings.write["session"];
  200. switch(key.keysym.sym)
  201. {
  202. case SDLK_F5:
  203. if(settings["session"]["spectate-locked-pim"].Bool())
  204. LOCPLINT->pim->unlock();
  205. else
  206. LOCPLINT->pim->lock();
  207. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  208. break;
  209. case SDLK_F6:
  210. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  211. break;
  212. case SDLK_F7:
  213. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  214. break;
  215. case SDLK_F8:
  216. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  217. break;
  218. case SDLK_F9:
  219. //not working yet since CClient::run remain locked after CBattleInterface removal
  220. // if(LOCPLINT->battleInt)
  221. // {
  222. // GH.popInts(1);
  223. // vstd::clear_pointer(LOCPLINT->battleInt);
  224. // }
  225. break;
  226. default:
  227. break;
  228. }
  229. return;
  230. }
  231. //translate numpad keys
  232. if(key.keysym.sym == SDLK_KP_ENTER)
  233. {
  234. key.keysym.sym = SDLK_RETURN;
  235. key.keysym.scancode = SDL_SCANCODE_RETURN;
  236. }
  237. bool keysCaptured = false;
  238. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  239. {
  240. if((*i)->captureThisEvent(key))
  241. {
  242. keysCaptured = true;
  243. break;
  244. }
  245. }
  246. std::list<CIntObject*> miCopy = keyinterested;
  247. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  248. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisEvent(key)))
  249. (**i).keyPressed(key);
  250. }
  251. else if(current->type == SDL_MOUSEMOTION)
  252. {
  253. handleMouseMotion();
  254. }
  255. else if(current->type == SDL_MOUSEBUTTONDOWN)
  256. {
  257. switch(current->button.button)
  258. {
  259. case SDL_BUTTON_LEFT:
  260. if(lastClick == current->motion && (SDL_GetTicks() - lastClickTime) < 300)
  261. {
  262. std::list<CIntObject*> hlp = doubleClickInterested;
  263. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  264. {
  265. if(!vstd::contains(doubleClickInterested, *i)) continue;
  266. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  267. {
  268. (*i)->onDoubleClick();
  269. }
  270. }
  271. }
  272. lastClick = current->motion;
  273. lastClickTime = SDL_GetTicks();
  274. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, true);
  275. break;
  276. case SDL_BUTTON_RIGHT:
  277. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  278. break;
  279. case SDL_BUTTON_MIDDLE:
  280. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, true);
  281. break;
  282. default:
  283. break;
  284. }
  285. }
  286. else if(current->type == SDL_MOUSEWHEEL)
  287. {
  288. std::list<CIntObject*> hlp = wheelInterested;
  289. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  290. {
  291. if(!vstd::contains(wheelInterested,*i)) continue;
  292. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  293. int x = 0, y = 0;
  294. SDL_GetMouseState(&x, &y);
  295. (*i)->wheelScrolled(current->wheel.y < 0, isItIn(&(*i)->pos, x, y));
  296. }
  297. }
  298. else if(current->type == SDL_TEXTINPUT)
  299. {
  300. for(auto it : textInterested)
  301. {
  302. it->textInputed(current->text);
  303. }
  304. }
  305. else if(current->type == SDL_TEXTEDITING)
  306. {
  307. for(auto it : textInterested)
  308. {
  309. it->textEdited(current->edit);
  310. }
  311. }
  312. else if(current->type == SDL_MOUSEBUTTONUP)
  313. {
  314. if(multifinger && lastFingerCount >= 1)
  315. {
  316. multifinger = false;
  317. }
  318. else
  319. {
  320. switch(current->button.button)
  321. {
  322. case SDL_BUTTON_LEFT:
  323. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, false);
  324. break;
  325. case SDL_BUTTON_RIGHT:
  326. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  327. break;
  328. case SDL_BUTTON_MIDDLE:
  329. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, false);
  330. break;
  331. }
  332. }
  333. }
  334. else if(current->type == SDL_FINGERDOWN)
  335. {
  336. lastFingerCount = SDL_GetNumTouchFingers(current->tfinger.touchId);
  337. multifinger = lastFingerCount > 1;
  338. if(lastFingerCount == 2)
  339. {
  340. convertTouch(current);
  341. handleMouseMotion();
  342. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  343. }
  344. }
  345. else if(current->type == SDL_FINGERUP)
  346. {
  347. lastFingerCount = SDL_GetNumTouchFingers(current->tfinger.touchId);
  348. if(multifinger)
  349. {
  350. multifinger = false;
  351. convertTouch(current);
  352. handleMouseMotion();
  353. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  354. }
  355. }
  356. current = nullptr;
  357. } //event end
  358. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed)
  359. {
  360. auto hlp = interestedObjs;
  361. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  362. {
  363. if(!vstd::contains(interestedObjs, *i)) continue;
  364. auto prev = (*i)->mouseState(btn);
  365. if(!isPressed)
  366. (*i)->updateMouseState(btn, isPressed);
  367. if(isItIn(&(*i)->pos, current->motion.x, current->motion.y))
  368. {
  369. if(isPressed)
  370. (*i)->updateMouseState(btn, isPressed);
  371. (*i)->click(btn, isPressed, prev);
  372. }
  373. else if(!isPressed)
  374. (*i)->click(btn, boost::logic::indeterminate, prev);
  375. }
  376. }
  377. void CGuiHandler::handleMouseMotion()
  378. {
  379. //sending active, hovered hoverable objects hover() call
  380. std::vector<CIntObject*> hlp;
  381. for(auto & elem : hoverable)
  382. {
  383. if(isItIn(&(elem)->pos, current->motion.x, current->motion.y))
  384. {
  385. if (!(elem)->hovered)
  386. hlp.push_back((elem));
  387. }
  388. else if ((elem)->hovered)
  389. {
  390. (elem)->hover(false);
  391. (elem)->hovered = false;
  392. }
  393. }
  394. for(auto & elem : hlp)
  395. {
  396. elem->hover(true);
  397. elem->hovered = true;
  398. }
  399. handleMoveInterested(current->motion);
  400. }
  401. void CGuiHandler::simpleRedraw()
  402. {
  403. //update only top interface and draw background
  404. if(objsToBlit.size() > 1)
  405. blitAt(screen2,0,0,screen); //blit background
  406. if(!objsToBlit.empty())
  407. objsToBlit.back()->show(screen); //blit active interface/window
  408. }
  409. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  410. {
  411. //sending active, MotionInterested objects mouseMoved() call
  412. std::list<CIntObject*> miCopy = motioninterested;
  413. for(auto & elem : miCopy)
  414. {
  415. if(elem->strongInterest || isItInOrLowerBounds(&elem->pos, motion.x, motion.y)) //checking lower bounds fixes bug #2476
  416. {
  417. (elem)->mouseMoved(motion);
  418. }
  419. }
  420. }
  421. void CGuiHandler::fakeMouseMove()
  422. {
  423. SDL_Event event;
  424. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  425. int x, y;
  426. sme.state = SDL_GetMouseState(&x, &y);
  427. sme.x = x;
  428. sme.y = y;
  429. event.motion = sme;
  430. SDL_PushEvent(&event);
  431. }
  432. void CGuiHandler::renderFrame()
  433. {
  434. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  435. // During game:
  436. // When ending the game, the pim mutex might be hold by other thread,
  437. // that will notify us about the ending game by setting terminate_cond flag.
  438. //in PreGame terminate_cond stay false
  439. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  440. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  441. boost::this_thread::sleep(boost::posix_time::milliseconds(15));
  442. if(acquiredTheLockOnPim)
  443. {
  444. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  445. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  446. if(nullptr != curInt)
  447. curInt->update();
  448. if(settings["general"]["showfps"].Bool())
  449. drawFPSCounter();
  450. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  451. SDL_RenderClear(mainRenderer);
  452. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  453. CCS->curh->render();
  454. SDL_RenderPresent(mainRenderer);
  455. disposed.clear();
  456. }
  457. mainFPSmng->framerateDelay(); // holds a constant FPS
  458. }
  459. CGuiHandler::CGuiHandler()
  460. : lastClick(-500, -500),lastClickTime(0), defActionsDef(0), captureChildren(false)
  461. {
  462. continueEventHandling = true;
  463. curInt = nullptr;
  464. current = nullptr;
  465. statusbar = nullptr;
  466. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  467. mainFPSmng = new CFramerateManager(48);
  468. //do not init CFramerateManager here --AVS
  469. terminate_cond = new CondSh<bool>(false);
  470. }
  471. CGuiHandler::~CGuiHandler()
  472. {
  473. delete mainFPSmng;
  474. delete terminate_cond;
  475. }
  476. void CGuiHandler::breakEventHandling()
  477. {
  478. continueEventHandling = false;
  479. }
  480. void CGuiHandler::drawFPSCounter()
  481. {
  482. const static SDL_Color yellow = {255, 255, 0, 0};
  483. static SDL_Rect overlay = { 0, 0, 64, 32};
  484. Uint32 black = SDL_MapRGB(screen->format, 10, 10, 10);
  485. SDL_FillRect(screen, &overlay, black);
  486. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  487. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, yellow, Point(10, 10));
  488. }
  489. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  490. {
  491. switch(key)
  492. {
  493. case SDLK_DOWN:
  494. return SDLK_KP_2;
  495. case SDLK_UP:
  496. return SDLK_KP_8;
  497. case SDLK_LEFT:
  498. return SDLK_KP_4;
  499. case SDLK_RIGHT:
  500. return SDLK_KP_6;
  501. default:
  502. throw std::runtime_error("Wrong key!");
  503. }
  504. }
  505. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  506. {
  507. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  508. switch(key)
  509. {
  510. REMOVE_KP(0)
  511. REMOVE_KP(1)
  512. REMOVE_KP(2)
  513. REMOVE_KP(3)
  514. REMOVE_KP(4)
  515. REMOVE_KP(5)
  516. REMOVE_KP(6)
  517. REMOVE_KP(7)
  518. REMOVE_KP(8)
  519. REMOVE_KP(9)
  520. REMOVE_KP(PERIOD)
  521. REMOVE_KP(MINUS)
  522. REMOVE_KP(PLUS)
  523. REMOVE_KP(EQUALS)
  524. case SDLK_KP_MULTIPLY:
  525. return SDLK_ASTERISK;
  526. case SDLK_KP_DIVIDE:
  527. return SDLK_SLASH;
  528. case SDLK_KP_ENTER:
  529. return SDLK_RETURN;
  530. default:
  531. return SDLK_UNKNOWN;
  532. }
  533. #undef REMOVE_KP
  534. }
  535. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  536. {
  537. if(number)
  538. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  539. else
  540. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  541. }
  542. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  543. {
  544. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  545. }
  546. bool CGuiHandler::amIGuiThread()
  547. {
  548. return inGuiThread.get() && *inGuiThread;
  549. }
  550. void CGuiHandler::pushSDLEvent(int type, int usercode)
  551. {
  552. SDL_Event event;
  553. event.type = type;
  554. event.user.code = usercode; // not necessarily used
  555. SDL_PushEvent(&event);
  556. }
  557. CFramerateManager::CFramerateManager(int rate)
  558. {
  559. this->rate = rate;
  560. this->rateticks = (1000.0 / rate);
  561. this->fps = 0;
  562. this->accumulatedFrames = 0;
  563. this->accumulatedTime = 0;
  564. this->lastticks = 0;
  565. this->timeElapsed = 0;
  566. }
  567. void CFramerateManager::init()
  568. {
  569. this->lastticks = SDL_GetTicks();
  570. }
  571. void CFramerateManager::framerateDelay()
  572. {
  573. ui32 currentTicks = SDL_GetTicks();
  574. timeElapsed = currentTicks - lastticks;
  575. accumulatedFrames++;
  576. // FPS is higher than it should be, then wait some time
  577. if(timeElapsed < rateticks)
  578. {
  579. SDL_Delay((Uint32)ceil(this->rateticks) - timeElapsed);
  580. }
  581. currentTicks = SDL_GetTicks();
  582. // recalculate timeElapsed for external calls via getElapsed()
  583. // limit it to 1000 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  584. timeElapsed = std::min<ui32>(currentTicks - lastticks, 1000);
  585. lastticks = SDL_GetTicks();
  586. accumulatedTime += timeElapsed;
  587. if(accumulatedFrames >= 100)
  588. {
  589. //about 2 second should be passed
  590. fps = static_cast<int>(ceil(1000.0 / (accumulatedTime / accumulatedFrames)));
  591. accumulatedTime = 0;
  592. accumulatedFrames = 0;
  593. }
  594. }