CGuiHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. 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)->captureThisEvent(key))
  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)->captureThisEvent(key)))
  345. (**i).keyPressed(key);
  346. }
  347. else if(current.type == SDL_MOUSEMOTION)
  348. {
  349. handleMouseMotion(current);
  350. }
  351. else if(current.type == SDL_MOUSEBUTTONDOWN)
  352. {
  353. switch(current.button.button)
  354. {
  355. case SDL_BUTTON_LEFT:
  356. {
  357. auto doubleClicked = false;
  358. if(lastClick == getCursorPosition() && (SDL_GetTicks() - lastClickTime) < 300)
  359. {
  360. std::list<CIntObject*> hlp = doubleClickInterested;
  361. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  362. {
  363. if(!vstd::contains(doubleClickInterested, *i)) continue;
  364. if((*i)->pos.isInside(current.motion.x, current.motion.y))
  365. {
  366. (*i)->onDoubleClick();
  367. doubleClicked = true;
  368. }
  369. }
  370. }
  371. lastClick = current.motion;
  372. lastClickTime = SDL_GetTicks();
  373. if(!doubleClicked)
  374. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, true);
  375. break;
  376. }
  377. case SDL_BUTTON_RIGHT:
  378. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  379. break;
  380. case SDL_BUTTON_MIDDLE:
  381. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, true);
  382. break;
  383. default:
  384. break;
  385. }
  386. }
  387. else if(current.type == SDL_MOUSEWHEEL)
  388. {
  389. std::list<CIntObject*> hlp = wheelInterested;
  390. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  391. {
  392. if(!vstd::contains(wheelInterested,*i)) continue;
  393. // SDL doesn't have the proper values for mouse positions on SDL_MOUSEWHEEL, refetch them
  394. int x = 0, y = 0;
  395. SDL_GetMouseState(&x, &y);
  396. (*i)->wheelScrolled(current.wheel.y < 0, (*i)->pos.isInside(x, y));
  397. }
  398. }
  399. else if(current.type == SDL_TEXTINPUT)
  400. {
  401. for(auto it : textInterested)
  402. {
  403. it->textInputed(current.text);
  404. }
  405. }
  406. else if(current.type == SDL_TEXTEDITING)
  407. {
  408. for(auto it : textInterested)
  409. {
  410. it->textEdited(current.edit);
  411. }
  412. }
  413. else if(current.type == SDL_MOUSEBUTTONUP)
  414. {
  415. if(!multifinger)
  416. {
  417. switch(current.button.button)
  418. {
  419. case SDL_BUTTON_LEFT:
  420. handleMouseButtonClick(lclickable, EIntObjMouseBtnType::LEFT, false);
  421. break;
  422. case SDL_BUTTON_RIGHT:
  423. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  424. break;
  425. case SDL_BUTTON_MIDDLE:
  426. handleMouseButtonClick(mclickable, EIntObjMouseBtnType::MIDDLE, false);
  427. break;
  428. }
  429. }
  430. }
  431. else if(current.type == SDL_FINGERMOTION)
  432. {
  433. if(isPointerRelativeMode)
  434. {
  435. fakeMoveCursor(current.tfinger.dx, current.tfinger.dy);
  436. }
  437. }
  438. else if(current.type == SDL_FINGERDOWN)
  439. {
  440. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  441. multifinger = fingerCount > 1;
  442. if(isPointerRelativeMode)
  443. {
  444. if(current.tfinger.x > 0.5)
  445. {
  446. bool isRightClick = current.tfinger.y < 0.5;
  447. fakeMouseButtonEventRelativeMode(true, isRightClick);
  448. }
  449. }
  450. #ifndef VCMI_IOS
  451. else if(fingerCount == 2)
  452. {
  453. convertTouchToMouse(&current);
  454. handleMouseMotion(current);
  455. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, true);
  456. }
  457. #endif //VCMI_IOS
  458. }
  459. else if(current.type == SDL_FINGERUP)
  460. {
  461. #ifndef VCMI_IOS
  462. auto fingerCount = SDL_GetNumTouchFingers(current.tfinger.touchId);
  463. #endif //VCMI_IOS
  464. if(isPointerRelativeMode)
  465. {
  466. if(current.tfinger.x > 0.5)
  467. {
  468. bool isRightClick = current.tfinger.y < 0.5;
  469. fakeMouseButtonEventRelativeMode(false, isRightClick);
  470. }
  471. }
  472. #ifndef VCMI_IOS
  473. else if(multifinger)
  474. {
  475. convertTouchToMouse(&current);
  476. handleMouseMotion(current);
  477. handleMouseButtonClick(rclickable, EIntObjMouseBtnType::RIGHT, false);
  478. multifinger = fingerCount != 0;
  479. }
  480. #endif //VCMI_IOS
  481. }
  482. } //event end
  483. void CGuiHandler::handleMouseButtonClick(CIntObjectList & interestedObjs, EIntObjMouseBtnType btn, bool isPressed)
  484. {
  485. auto hlp = interestedObjs;
  486. for(auto i = hlp.begin(); i != hlp.end() && continueEventHandling; i++)
  487. {
  488. if(!vstd::contains(interestedObjs, *i)) continue;
  489. auto prev = (*i)->mouseState(btn);
  490. if(!isPressed)
  491. (*i)->updateMouseState(btn, isPressed);
  492. if((*i)->pos.isInside(getCursorPosition()))
  493. {
  494. if(isPressed)
  495. (*i)->updateMouseState(btn, isPressed);
  496. (*i)->click(btn, isPressed, prev);
  497. }
  498. else if(!isPressed)
  499. (*i)->click(btn, boost::logic::indeterminate, prev);
  500. }
  501. }
  502. void CGuiHandler::handleMouseMotion(const SDL_Event & current)
  503. {
  504. //sending active, hovered hoverable objects hover() call
  505. std::vector<CIntObject*> hlp;
  506. for(auto & elem : hoverable)
  507. {
  508. if(elem->pos.isInside(getCursorPosition()))
  509. {
  510. if (!(elem)->hovered)
  511. hlp.push_back((elem));
  512. }
  513. else if ((elem)->hovered)
  514. {
  515. (elem)->hover(false);
  516. (elem)->hovered = false;
  517. }
  518. }
  519. for(auto & elem : hlp)
  520. {
  521. elem->hover(true);
  522. elem->hovered = true;
  523. }
  524. // do not send motion events for events outside our window
  525. //if (current.motion.windowID == 0)
  526. handleMoveInterested(current.motion);
  527. }
  528. void CGuiHandler::simpleRedraw()
  529. {
  530. //update only top interface and draw background
  531. if(objsToBlit.size() > 1)
  532. CSDL_Ext::blitAt(screen2,0,0,screen); //blit background
  533. if(!objsToBlit.empty())
  534. objsToBlit.back()->show(screen); //blit active interface/window
  535. }
  536. void CGuiHandler::handleMoveInterested(const SDL_MouseMotionEvent & motion)
  537. {
  538. //sending active, MotionInterested objects mouseMoved() call
  539. std::list<CIntObject*> miCopy = motioninterested;
  540. for(auto & elem : miCopy)
  541. {
  542. if(elem->strongInterest || Rect::createAround(elem->pos, 1).isInside( motion.x, motion.y)) //checking bounds including border fixes bug #2476
  543. {
  544. (elem)->mouseMoved(Point(motion.x, motion.y));
  545. }
  546. }
  547. }
  548. void CGuiHandler::renderFrame()
  549. {
  550. // Updating GUI requires locking pim mutex (that protects screen and GUI state).
  551. // During game:
  552. // When ending the game, the pim mutex might be hold by other thread,
  553. // that will notify us about the ending game by setting terminate_cond flag.
  554. //in PreGame terminate_cond stay false
  555. bool acquiredTheLockOnPim = false; //for tracking whether pim mutex locking succeeded
  556. while(!terminate_cond->get() && !(acquiredTheLockOnPim = CPlayerInterface::pim->try_lock())) //try acquiring long until it succeeds or we are told to terminate
  557. boost::this_thread::sleep(boost::posix_time::milliseconds(1));
  558. if(acquiredTheLockOnPim)
  559. {
  560. // If we are here, pim mutex has been successfully locked - let's store it in a safe RAII lock.
  561. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim, boost::adopt_lock);
  562. if(nullptr != curInt)
  563. curInt->update();
  564. if(settings["general"]["showfps"].Bool())
  565. drawFPSCounter();
  566. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  567. SDL_RenderClear(mainRenderer);
  568. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  569. CCS->curh->render();
  570. SDL_RenderPresent(mainRenderer);
  571. disposed.clear();
  572. }
  573. mainFPSmng->framerateDelay(); // holds a constant FPS
  574. }
  575. CGuiHandler::CGuiHandler()
  576. : lastClick(-500, -500)
  577. , lastClickTime(0)
  578. , defActionsDef(0)
  579. , captureChildren(false)
  580. , multifinger(false)
  581. , mouseButtonsMask(0)
  582. , continueEventHandling(true)
  583. , curInt(nullptr)
  584. , statusbar(nullptr)
  585. {
  586. // Creates the FPS manager and sets the framerate to 48 which is doubled the value of the original Heroes 3 FPS rate
  587. mainFPSmng = new CFramerateManager(60);
  588. //do not init CFramerateManager here --AVS
  589. terminate_cond = new CondSh<bool>(false);
  590. }
  591. CGuiHandler::~CGuiHandler()
  592. {
  593. delete mainFPSmng;
  594. delete terminate_cond;
  595. }
  596. void CGuiHandler::moveCursorToPosition(const Point & position)
  597. {
  598. SDL_WarpMouseInWindow(mainWindow, position.x, position.y);
  599. }
  600. bool CGuiHandler::isKeyboardCtrlDown() const
  601. {
  602. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LCTRL] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RCTRL];
  603. }
  604. bool CGuiHandler::isKeyboardAltDown() const
  605. {
  606. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LALT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RALT];
  607. }
  608. bool CGuiHandler::isKeyboardShiftDown() const
  609. {
  610. return SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_LSHIFT] || SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_RSHIFT];
  611. }
  612. void CGuiHandler::breakEventHandling()
  613. {
  614. continueEventHandling = false;
  615. }
  616. const Point & CGuiHandler::getCursorPosition() const
  617. {
  618. return cursorPosition;
  619. }
  620. bool CGuiHandler::isMouseButtonPressed() const
  621. {
  622. return mouseButtonsMask > 0;
  623. }
  624. bool CGuiHandler::isMouseButtonPressed(MouseButton button) const
  625. {
  626. static_assert(static_cast<uint32_t>(MouseButton::LEFT) == SDL_BUTTON_LEFT, "mismatch between VCMI and SDL enum!");
  627. static_assert(static_cast<uint32_t>(MouseButton::MIDDLE) == SDL_BUTTON_MIDDLE, "mismatch between VCMI and SDL enum!");
  628. static_assert(static_cast<uint32_t>(MouseButton::RIGHT) == SDL_BUTTON_RIGHT, "mismatch between VCMI and SDL enum!");
  629. static_assert(static_cast<uint32_t>(MouseButton::EXTRA1) == SDL_BUTTON_X1, "mismatch between VCMI and SDL enum!");
  630. static_assert(static_cast<uint32_t>(MouseButton::EXTRA2) == SDL_BUTTON_X2, "mismatch between VCMI and SDL enum!");
  631. uint32_t index = static_cast<uint32_t>(button);
  632. return mouseButtonsMask & SDL_BUTTON(index);
  633. }
  634. void CGuiHandler::drawFPSCounter()
  635. {
  636. static SDL_Rect overlay = { 0, 0, 64, 32};
  637. uint32_t black = SDL_MapRGB(screen->format, 10, 10, 10);
  638. SDL_FillRect(screen, &overlay, black);
  639. std::string fps = boost::lexical_cast<std::string>(mainFPSmng->fps);
  640. graphics->fonts[FONT_BIG]->renderTextLeft(screen, fps, Colors::YELLOW, Point(10, 10));
  641. }
  642. SDL_Keycode CGuiHandler::arrowToNum(SDL_Keycode key)
  643. {
  644. switch(key)
  645. {
  646. case SDLK_DOWN:
  647. return SDLK_KP_2;
  648. case SDLK_UP:
  649. return SDLK_KP_8;
  650. case SDLK_LEFT:
  651. return SDLK_KP_4;
  652. case SDLK_RIGHT:
  653. return SDLK_KP_6;
  654. default:
  655. throw std::runtime_error("Wrong key!");
  656. }
  657. }
  658. SDL_Keycode CGuiHandler::numToDigit(SDL_Keycode key)
  659. {
  660. #define REMOVE_KP(keyName) case SDLK_KP_ ## keyName : return SDLK_ ## keyName;
  661. switch(key)
  662. {
  663. REMOVE_KP(0)
  664. REMOVE_KP(1)
  665. REMOVE_KP(2)
  666. REMOVE_KP(3)
  667. REMOVE_KP(4)
  668. REMOVE_KP(5)
  669. REMOVE_KP(6)
  670. REMOVE_KP(7)
  671. REMOVE_KP(8)
  672. REMOVE_KP(9)
  673. REMOVE_KP(PERIOD)
  674. REMOVE_KP(MINUS)
  675. REMOVE_KP(PLUS)
  676. REMOVE_KP(EQUALS)
  677. case SDLK_KP_MULTIPLY:
  678. return SDLK_ASTERISK;
  679. case SDLK_KP_DIVIDE:
  680. return SDLK_SLASH;
  681. case SDLK_KP_ENTER:
  682. return SDLK_RETURN;
  683. default:
  684. return SDLK_UNKNOWN;
  685. }
  686. #undef REMOVE_KP
  687. }
  688. bool CGuiHandler::isNumKey(SDL_Keycode key, bool number)
  689. {
  690. if(number)
  691. return key >= SDLK_KP_1 && key <= SDLK_KP_0;
  692. else
  693. return (key >= SDLK_KP_1 && key <= SDLK_KP_0) || key == SDLK_KP_MINUS || key == SDLK_KP_PLUS || key == SDLK_KP_EQUALS;
  694. }
  695. bool CGuiHandler::isArrowKey(SDL_Keycode key)
  696. {
  697. return key == SDLK_UP || key == SDLK_DOWN || key == SDLK_LEFT || key == SDLK_RIGHT;
  698. }
  699. bool CGuiHandler::amIGuiThread()
  700. {
  701. return inGuiThread.get() && *inGuiThread;
  702. }
  703. void CGuiHandler::pushSDLEvent(int type, int usercode)
  704. {
  705. SDL_Event event;
  706. event.type = type;
  707. event.user.code = usercode; // not necessarily used
  708. SDL_PushEvent(&event);
  709. }
  710. CFramerateManager::CFramerateManager(int rate)
  711. {
  712. this->rate = rate;
  713. this->rateticks = (1000.0 / rate);
  714. this->fps = 0;
  715. this->accumulatedFrames = 0;
  716. this->accumulatedTime = 0;
  717. this->lastticks = 0;
  718. this->timeElapsed = 0;
  719. }
  720. void CFramerateManager::init()
  721. {
  722. this->lastticks = SDL_GetTicks();
  723. }
  724. void CFramerateManager::framerateDelay()
  725. {
  726. ui32 currentTicks = SDL_GetTicks();
  727. timeElapsed = currentTicks - lastticks;
  728. accumulatedFrames++;
  729. // FPS is higher than it should be, then wait some time
  730. if(timeElapsed < rateticks)
  731. {
  732. int timeToSleep = (uint32_t)ceil(this->rateticks) - timeElapsed;
  733. boost::this_thread::sleep(boost::posix_time::milliseconds(timeToSleep));
  734. }
  735. currentTicks = SDL_GetTicks();
  736. // recalculate timeElapsed for external calls via getElapsed()
  737. // limit it to 100 ms to avoid breaking animation in case of huge lag (e.g. triggered breakpoint)
  738. timeElapsed = std::min<ui32>(currentTicks - lastticks, 100);
  739. lastticks = SDL_GetTicks();
  740. accumulatedTime += timeElapsed;
  741. if(accumulatedFrames >= 100)
  742. {
  743. //about 2 second should be passed
  744. fps = static_cast<int>(ceil(1000.0 / (accumulatedTime / accumulatedFrames)));
  745. accumulatedTime = 0;
  746. accumulatedFrames = 0;
  747. }
  748. }