CGuiHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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. pushUserEvent(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. pushUserEvent(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. pushUserEvent(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. if (currentEvent.type == SDL_MOUSEMOTION)
  177. {
  178. cursorPosition = Point(currentEvent.motion.x, currentEvent.motion.y);
  179. mouseButtonsMask = currentEvent.motion.state;
  180. }
  181. SDLEventsQueue.pop();
  182. // In a sequence of mouse motion events, skip all but the last one.
  183. // This prevents freezes when every motion event takes longer to handle than interval at which
  184. // the events arrive (like dragging on the minimap in world view, with redraw at every event)
  185. // so that the events would start piling up faster than they can be processed.
  186. if ((currentEvent.type == SDL_MOUSEMOTION) && !SDLEventsQueue.empty() && (SDLEventsQueue.front().type == SDL_MOUSEMOTION))
  187. continue;
  188. handleCurrentEvent(currentEvent);
  189. }
  190. }
  191. void CGuiHandler::convertTouchToMouse(SDL_Event * current)
  192. {
  193. int rLogicalWidth, rLogicalHeight;
  194. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  195. int adjustedMouseY = (int)(current->tfinger.y * rLogicalHeight);
  196. int adjustedMouseX = (int)(current->tfinger.x * rLogicalWidth);
  197. current->button.x = adjustedMouseX;
  198. current->motion.x = adjustedMouseX;
  199. current->button.y = adjustedMouseY;
  200. current->motion.y = adjustedMouseY;
  201. }
  202. void CGuiHandler::fakeMoveCursor(float dx, float dy)
  203. {
  204. int x, y, w, h;
  205. SDL_Event event;
  206. SDL_MouseMotionEvent sme = {SDL_MOUSEMOTION, 0, 0, 0, 0, 0, 0, 0, 0};
  207. sme.state = SDL_GetMouseState(&x, &y);
  208. SDL_GetWindowSize(mainWindow, &w, &h);
  209. sme.x = CCS->curh->position().x + (int)(GH.pointerSpeedMultiplier * w * dx);
  210. sme.y = CCS->curh->position().y + (int)(GH.pointerSpeedMultiplier * h * dy);
  211. vstd::abetween(sme.x, 0, w);
  212. vstd::abetween(sme.y, 0, h);
  213. event.motion = sme;
  214. SDL_PushEvent(&event);
  215. }
  216. void CGuiHandler::fakeMouseMove()
  217. {
  218. fakeMoveCursor(0, 0);
  219. }
  220. void CGuiHandler::startTextInput(const Rect & whereInput)
  221. {
  222. #ifdef VCMI_APPLE
  223. dispatch_async(dispatch_get_main_queue(), ^{
  224. #endif
  225. // TODO ios: looks like SDL bug actually, try fixing there
  226. auto renderer = SDL_GetRenderer(mainWindow);
  227. float scaleX, scaleY;
  228. SDL_Rect viewport;
  229. SDL_RenderGetScale(renderer, &scaleX, &scaleY);
  230. SDL_RenderGetViewport(renderer, &viewport);
  231. #ifdef VCMI_IOS
  232. const auto nativeScale = iOS_utils::screenScale();
  233. scaleX /= nativeScale;
  234. scaleY /= nativeScale;
  235. #endif
  236. SDL_Rect rectInScreenCoordinates;
  237. rectInScreenCoordinates.x = (viewport.x + whereInput.x) * scaleX;
  238. rectInScreenCoordinates.y = (viewport.y + whereInput.y) * scaleY;
  239. rectInScreenCoordinates.w = whereInput.w * scaleX;
  240. rectInScreenCoordinates.h = whereInput.h * scaleY;
  241. SDL_SetTextInputRect(&rectInScreenCoordinates);
  242. if (SDL_IsTextInputActive() == SDL_FALSE)
  243. {
  244. SDL_StartTextInput();
  245. }
  246. #ifdef VCMI_APPLE
  247. });
  248. #endif
  249. }
  250. void CGuiHandler::stopTextInput()
  251. {
  252. #ifdef VCMI_APPLE
  253. dispatch_async(dispatch_get_main_queue(), ^{
  254. #endif
  255. if (SDL_IsTextInputActive() == SDL_TRUE)
  256. {
  257. SDL_StopTextInput();
  258. }
  259. #ifdef VCMI_APPLE
  260. });
  261. #endif
  262. }
  263. void CGuiHandler::fakeMouseButtonEventRelativeMode(bool down, bool right)
  264. {
  265. SDL_Event event;
  266. SDL_MouseButtonEvent sme = {SDL_MOUSEBUTTONDOWN, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  267. if(!down)
  268. {
  269. sme.type = SDL_MOUSEBUTTONUP;
  270. }
  271. sme.button = right ? SDL_BUTTON_RIGHT : SDL_BUTTON_LEFT;
  272. sme.x = CCS->curh->position().x;
  273. sme.y = CCS->curh->position().y;
  274. float xScale, yScale;
  275. int w, h, rLogicalWidth, rLogicalHeight;
  276. SDL_GetWindowSize(mainWindow, &w, &h);
  277. SDL_RenderGetLogicalSize(mainRenderer, &rLogicalWidth, &rLogicalHeight);
  278. SDL_RenderGetScale(mainRenderer, &xScale, &yScale);
  279. SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
  280. moveCursorToPosition( Point(
  281. (int)(sme.x * xScale) + (w - rLogicalWidth * xScale) / 2,
  282. (int)(sme.y * yScale + (h - rLogicalHeight * yScale) / 2)));
  283. SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
  284. event.button = sme;
  285. SDL_PushEvent(&event);
  286. }
  287. void CGuiHandler::handleCurrentEvent( SDL_Event & current )
  288. {
  289. if(current.type == SDL_KEYDOWN || current.type == SDL_KEYUP)
  290. {
  291. SDL_KeyboardEvent key = current.key;
  292. if(current.type == SDL_KEYDOWN && key.keysym.sym >= SDLK_F1 && key.keysym.sym <= SDLK_F15 && settings["session"]["spectate"].Bool())
  293. {
  294. //TODO: we need some central place for all interface-independent hotkeys
  295. Settings s = settings.write["session"];
  296. switch(key.keysym.sym)
  297. {
  298. case SDLK_F5:
  299. if(settings["session"]["spectate-locked-pim"].Bool())
  300. LOCPLINT->pim->unlock();
  301. else
  302. LOCPLINT->pim->lock();
  303. s["spectate-locked-pim"].Bool() = !settings["session"]["spectate-locked-pim"].Bool();
  304. break;
  305. case SDLK_F6:
  306. s["spectate-ignore-hero"].Bool() = !settings["session"]["spectate-ignore-hero"].Bool();
  307. break;
  308. case SDLK_F7:
  309. s["spectate-skip-battle"].Bool() = !settings["session"]["spectate-skip-battle"].Bool();
  310. break;
  311. case SDLK_F8:
  312. s["spectate-skip-battle-result"].Bool() = !settings["session"]["spectate-skip-battle-result"].Bool();
  313. break;
  314. case SDLK_F9:
  315. //not working yet since CClient::run remain locked after BattleInterface removal
  316. // if(LOCPLINT->battleInt)
  317. // {
  318. // GH.popInts(1);
  319. // vstd::clear_pointer(LOCPLINT->battleInt);
  320. // }
  321. break;
  322. default:
  323. break;
  324. }
  325. return;
  326. }
  327. //translate numpad keys
  328. if(key.keysym.sym == SDLK_KP_ENTER)
  329. {
  330. key.keysym.sym = SDLK_RETURN;
  331. key.keysym.scancode = SDL_SCANCODE_RETURN;
  332. }
  333. bool keysCaptured = false;
  334. for(auto i = keyinterested.begin(); i != keyinterested.end() && continueEventHandling; i++)
  335. {
  336. if((*i)->captureThisKey(key.keysym.sym))
  337. {
  338. keysCaptured = true;
  339. break;
  340. }
  341. }
  342. std::list<CIntObject*> miCopy = keyinterested;
  343. for(auto i = miCopy.begin(); i != miCopy.end() && continueEventHandling; i++)
  344. if(vstd::contains(keyinterested,*i) && (!keysCaptured || (*i)->captureThisKey(key.keysym.sym)))
  345. {
  346. if (key.state == SDL_PRESSED)
  347. (**i).keyPressed(key.keysym.sym);
  348. if (key.state == SDL_RELEASED)
  349. (**i).keyReleased(key.keysym.sym);
  350. }
  351. }
  352. else if(current.type == SDL_MOUSEMOTION)
  353. {
  354. handleMouseMotion(current);
  355. }
  356. else if(current.type == SDL_MOUSEBUTTONDOWN)
  357. {
  358. switch(current.button.button)
  359. {
  360. case SDL_BUTTON_LEFT:
  361. {
  362. auto doubleClicked = false;
  363. if(lastClick == getCursorPosition() && (SDL_GetTicks() - lastClickTime) < 300)
  364. {
  365. std::list<CIntObject*> hlp = doubleClickInterested;
  366. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  367. {
  368. if(!vstd::contains(doubleClickInterested, *i)) continue;
  369. if((*i)->pos.isInside(current.motion.x, current.motion.y))
  370. {
  371. (*i)->onDoubleClick();
  372. doubleClicked = true;
  373. }
  374. }
  375. }
  376. lastClick = current.motion;
  377. lastClickTime = SDL_GetTicks();
  378. if(!doubleClicked)
  379. handleMouseButtonClick(lclickable, MouseButton::LEFT, true);
  380. break;
  381. }
  382. case SDL_BUTTON_RIGHT:
  383. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  384. break;
  385. case SDL_BUTTON_MIDDLE:
  386. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, true);
  387. break;
  388. default:
  389. break;
  390. }
  391. }
  392. else if(current.type == SDL_MOUSEWHEEL)
  393. {
  394. std::list<CIntObject*> hlp = wheelInterested;
  395. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  396. {
  397. if(!vstd::contains(wheelInterested,*i)) continue;
  398. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  399. int x = 0, y = 0;
  400. SDL_GetMouseState(&x, &y);
  401. (*i)->wheelScrolled(current.wheel.y < 0, (*i)->pos.isInside(x, y));
  402. }
  403. }
  404. else if(current.type == SDL_TEXTINPUT)
  405. {
  406. for(auto it : textInterested)
  407. {
  408. it->textInputed(current.text);
  409. }
  410. }
  411. else if(current.type == SDL_TEXTEDITING)
  412. {
  413. for(auto it : textInterested)
  414. {
  415. it->textEdited(current.edit);
  416. }
  417. }
  418. else if(current.type == SDL_MOUSEBUTTONUP)
  419. {
  420. if(!multifinger)
  421. {
  422. switch(current.button.button)
  423. {
  424. case SDL_BUTTON_LEFT:
  425. handleMouseButtonClick(lclickable, MouseButton::LEFT, false);
  426. break;
  427. case SDL_BUTTON_RIGHT:
  428. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  429. break;
  430. case SDL_BUTTON_MIDDLE:
  431. handleMouseButtonClick(mclickable, MouseButton::MIDDLE, false);
  432. break;
  433. }
  434. }
  435. }
  436. else if(current.type == SDL_FINGERMOTION)
  437. {
  438. if(isPointerRelativeMode)
  439. {
  440. fakeMoveCursor(current.tfinger.dx, current.tfinger.dy);
  441. }
  442. }
  443. else if(current.type == SDL_FINGERDOWN)
  444. {
  445. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  446. multifinger = fingerCount > 1;
  447. if(isPointerRelativeMode)
  448. {
  449. if(current.tfinger.x > 0.5)
  450. {
  451. bool isRightClick = current.tfinger.y < 0.5;
  452. fakeMouseButtonEventRelativeMode(true, isRightClick);
  453. }
  454. }
  455. #ifndef VCMI_IOS
  456. else if(fingerCount == 2)
  457. {
  458. convertTouchToMouse(&current);
  459. handleMouseMotion(current);
  460. handleMouseButtonClick(rclickable, MouseButton::RIGHT, true);
  461. }
  462. #endif //VCMI_IOS
  463. }
  464. else if(current.type == SDL_FINGERUP)
  465. {
  466. #ifndef VCMI_IOS
  467. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  468. #endif //VCMI_IOS
  469. if(isPointerRelativeMode)
  470. {
  471. if(current.tfinger.x > 0.5)
  472. {
  473. bool isRightClick = current.tfinger.y < 0.5;
  474. fakeMouseButtonEventRelativeMode(false, isRightClick);
  475. }
  476. }
  477. #ifndef VCMI_IOS
  478. else if(multifinger)
  479. {
  480. convertTouchToMouse(&current);
  481. handleMouseMotion(current);
  482. handleMouseButtonClick(rclickable, MouseButton::RIGHT, false);
  483. multifinger = fingerCount != 0;
  484. }
  485. #endif //VCMI_IOS
  486. }
  487. } //event end
  488. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, MouseButton btn, bool isPressed)
  489. {
  490. auto hlp = interestedObjs;
  491. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  492. {
  493. if(!vstd::contains(interestedObjs, *i)) continue;
  494. auto prev = (*i)->mouseState(btn);
  495. if(!isPressed)
  496. (*i)->updateMouseState(btn, isPressed);
  497. if((*i)->pos.isInside(getCursorPosition()))
  498. {
  499. if(isPressed)
  500. (*i)->updateMouseState(btn, isPressed);
  501. (*i)->click(btn, isPressed, prev);
  502. }
  503. else if(!isPressed)
  504. (*i)->click(btn, boost::logic::indeterminate, prev);
  505. }
  506. }
  507. void CGuiHandler::handleMouseMotion(const SDL_Event & current)
  508. {
  509. //sending active, hovered hoverable objects hover() call
  510. std::vector<CIntObject*> hlp;
  511. for(auto & elem : hoverable)
  512. {
  513. if(elem->pos.isInside(getCursorPosition()))
  514. {
  515. if (!(elem)->hovered)
  516. hlp.push_back((elem));
  517. }
  518. else if ((elem)->hovered)
  519. {
  520. (elem)->hover(false);
  521. (elem)->hovered = false;
  522. }
  523. }
  524. for(auto & elem : hlp)
  525. {
  526. elem->hover(true);
  527. elem->hovered = true;
  528. }
  529. // do not send motion events for events outside our window
  530. //if (current.motion.windowID == 0)
  531. handleMoveInterested(current.motion);
  532. }
  533. void CGuiHandler::simpleRedraw()
  534. {
  535. //update only top interface and draw background
  536. if(objsToBlit.size() > 1)
  537. CSDL_Ext::blitAt(screen2,0,0,screen); //blit background
  538. if(!objsToBlit.empty())
  539. objsToBlit.back()->show(screen); //blit active interface/window
  540. }
  541. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  542. {
  543. //sending active, MotionInterested objects mouseMoved() call
  544. std::list<CIntObject*> miCopy = motioninterested;
  545. for(auto & elem : miCopy)
  546. {
  547. if(elem->strongInterest || Rect::createAround(elem->pos, 1).isInside( motion.x, motion.y)) //checking bounds including border fixes bug #2476
  548. {
  549. (elem)->mouseMoved(Point(motion.x, motion.y));
  550. }
  551. }
  552. }
  553. void CGuiHandler::renderFrame()
  554. {
  555. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  556. // During game:
  557. // When ending the game, the pim mutex might be hold by other thread,
  558. // that will notify us about the ending game by setting terminate_cond flag.
  559. //in PreGame terminate_cond stay false
  560. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  561. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  562. boost::this_thread::sleep(boost::posix_time::milliseconds(1));
  563. if(acquiredTheLockOnPim)
  564. {
  565. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  566. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  567. if(nullptr != curInt)
  568. curInt->update();
  569. if(settings["general"]["showfps"].Bool())
  570. drawFPSCounter();
  571. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  572. SDL_RenderClear(mainRenderer);
  573. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  574. CCS->curh->render();
  575. SDL_RenderPresent(mainRenderer);
  576. disposed.clear();
  577. }
  578. mainFPSmng->framerateDelay(); // holds a constant FPS
  579. }
  580. CGuiHandler::CGuiHandler()
  581. : lastClick(-500, -500)
  582. , lastClickTime(0)
  583. , defActionsDef(0)
  584. , captureChildren(false)
  585. , multifinger(false)
  586. , mouseButtonsMask(0)
  587. , continueEventHandling(true)
  588. , curInt(nullptr)
  589. , statusbar(nullptr)
  590. {
  591. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  592. mainFPSmng = new CFramerateManager(60);
  593. //do not init CFramerateManager here --AVS
  594. terminate_cond = new CondSh<bool>(false);
  595. }
  596. CGuiHandler::~CGuiHandler()
  597. {
  598. delete mainFPSmng;
  599. delete terminate_cond;
  600. }
  601. void CGuiHandler::moveCursorToPosition(const Point & position)
  602. {
  603. SDL_WarpMouseInWindow(mainWindow, position.x, position.y);
  604. }
  605. bool CGuiHandler::isKeyboardCtrlDown() const
  606. {
  607. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LCTRL] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RCTRL];
  608. }
  609. bool CGuiHandler::isKeyboardAltDown() const
  610. {
  611. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LALT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RALT];
  612. }
  613. bool CGuiHandler::isKeyboardShiftDown() const
  614. {
  615. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LSHIFT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RSHIFT];
  616. }
  617. void CGuiHandler::breakEventHandling()
  618. {
  619. continueEventHandling = false;
  620. }
  621. const Point & CGuiHandler::getCursorPosition() const
  622. {
  623. return cursorPosition;
  624. }
  625. bool CGuiHandler::isMouseButtonPressed() const
  626. {
  627. return mouseButtonsMask > 0;
  628. }
  629. bool CGuiHandler::isMouseButtonPressed(MouseButton button) const
  630. {
  631. static_assert(static_cast<uint32_t>(MouseButton::LEFT) == SDL_BUTTON_LEFT, "mismatch between VCMI and SDL enum!");
  632. static_assert(static_cast<uint32_t>(MouseButton::MIDDLE) == SDL_BUTTON_MIDDLE, "mismatch between VCMI and SDL enum!");
  633. static_assert(static_cast<uint32_t>(MouseButton::RIGHT) == SDL_BUTTON_RIGHT, "mismatch between VCMI and SDL enum!");
  634. static_assert(static_cast<uint32_t>(MouseButton::EXTRA1) == SDL_BUTTON_X1, "mismatch between VCMI and SDL enum!");
  635. static_assert(static_cast<uint32_t>(MouseButton::EXTRA2) == SDL_BUTTON_X2, "mismatch between VCMI and SDL enum!");
  636. uint32_t index = static_cast<uint32_t>(button);
  637. return mouseButtonsMask & SDL_BUTTON(index);
  638. }
  639. void CGuiHandler::drawFPSCounter()
  640. {
  641. static SDL_Rect overlay = { 0, 0, 64, 32};
  642. uint32_t black = SDL_MapRGB(screen->format, 10, 10, 10);
  643. SDL_FillRect(screen, &overlay, black);
  644. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  645. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, Colors::YELLOW, Point(10, 10));
  646. }
  647. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  648. {
  649. switch(key)
  650. {
  651. case SDLK_DOWN:
  652. return SDLK_KP_2;
  653. case SDLK_UP:
  654. return SDLK_KP_8;
  655. case SDLK_LEFT:
  656. return SDLK_KP_4;
  657. case SDLK_RIGHT:
  658. return SDLK_KP_6;
  659. default:
  660. throw std::runtime_error("Wrong key!");
  661. }
  662. }
  663. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  664. {
  665. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  666. switch(key)
  667. {
  668. REMOVE_KP(0)
  669. REMOVE_KP(1)
  670. REMOVE_KP(2)
  671. REMOVE_KP(3)
  672. REMOVE_KP(4)
  673. REMOVE_KP(5)
  674. REMOVE_KP(6)
  675. REMOVE_KP(7)
  676. REMOVE_KP(8)
  677. REMOVE_KP(9)
  678. REMOVE_KP(PERIOD)
  679. REMOVE_KP(MINUS)
  680. REMOVE_KP(PLUS)
  681. REMOVE_KP(EQUALS)
  682. case SDLK_KP_MULTIPLY:
  683. return SDLK_ASTERISK;
  684. case SDLK_KP_DIVIDE:
  685. return SDLK_SLASH;
  686. case SDLK_KP_ENTER:
  687. return SDLK_RETURN;
  688. default:
  689. return SDLK_UNKNOWN;
  690. }
  691. #undef REMOVE_KP
  692. }
  693. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  694. {
  695. if(number)
  696. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  697. else
  698. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  699. }
  700. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  701. {
  702. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  703. }
  704. bool CGuiHandler::amIGuiThread()
  705. {
  706. return inGuiThread.get() && *inGuiThread;
  707. }
  708. void CGuiHandler::pushUserEvent(EUserEvent usercode)
  709. {
  710. pushUserEvent(usercode, nullptr);
  711. }
  712. void CGuiHandler::pushUserEvent(EUserEvent usercode, void * userdata)
  713. {
  714. SDL_Event event;
  715. event.type = SDL_USEREVENT;
  716. event.user.code = static_cast<int32_t>(usercode);
  717. event.user.data1 = userdata;
  718. SDL_PushEvent(&event);
  719. }
  720. CFramerateManager::CFramerateManager(int rate)
  721. {
  722. this->rate = rate;
  723. this->rateticks = (1000.0 / rate);
  724. this->fps = 0;
  725. this->accumulatedFrames = 0;
  726. this->accumulatedTime = 0;
  727. this->lastticks = 0;
  728. this->timeElapsed = 0;
  729. }
  730. void CFramerateManager::init()
  731. {
  732. this->lastticks = SDL_GetTicks();
  733. }
  734. void CFramerateManager::framerateDelay()
  735. {
  736. ui32 currentTicks = SDL_GetTicks();
  737. timeElapsed = currentTicks - lastticks;
  738. accumulatedFrames++;
  739. // FPS is higher than it should be, then wait some time
  740. if(timeElapsed < rateticks)
  741. {
  742. int timeToSleep = (uint32_t)ceil(this->rateticks) - timeElapsed;
  743. boost::this_thread::sleep(boost::posix_time::milliseconds(timeToSleep));
  744. }
  745. currentTicks = SDL_GetTicks();
  746. // recalculate timeElapsed for external calls via getElapsed()
  747. // limit it to 100 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  748. timeElapsed = std::min<ui32>(currentTicks - lastticks, 100);
  749. lastticks = SDL_GetTicks();
  750. accumulatedTime += timeElapsed;
  751. if(accumulatedFrames >= 100)
  752. {
  753. //about 2 second should be passed
  754. fps = static_cast<int>(ceil(1000.0 / (accumulatedTime / accumulatedFrames)));
  755. accumulatedTime = 0;
  756. accumulatedFrames = 0;
  757. }
  758. }