CGuiHandler.cpp 20 KB

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