CGuiHandler.cpp 20 KB

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