CGuiHandler.cpp 20 KB

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