Input.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Mutex.h"
  26. #include "../Core/ProcessUtils.h"
  27. #include "../Core/Profiler.h"
  28. #include "../Core/StringUtils.h"
  29. #include "../Graphics/Graphics.h"
  30. #include "../Graphics/GraphicsEvents.h"
  31. #include "../Input/Input.h"
  32. #include "../IO/FileSystem.h"
  33. #include "../IO/Log.h"
  34. #include "../IO/RWOpsWrapper.h"
  35. #include "../Resource/ResourceCache.h"
  36. #include "../UI/Text.h"
  37. #include "../UI/UI.h"
  38. #ifdef _WIN32
  39. #include "../Engine/Engine.h"
  40. #endif
  41. #include <SDL/SDL.h>
  42. #ifdef __EMSCRIPTEN__
  43. #include <emscripten/html5.h>
  44. #endif
  45. #include "../DebugNew.h"
  46. extern "C" int SDL_AddTouch(SDL_TouchID touchID, SDL_TouchDeviceType type, const char* name);
  47. // Use a "click inside window to focus" mechanism on desktop platforms when the mouse cursor is hidden
  48. #if defined(_WIN32) || (defined(__APPLE__) && !defined(IOS) && !defined(TVOS)) || (defined(__linux__) && !defined(__ANDROID__))
  49. #define REQUIRE_CLICK_TO_FOCUS
  50. #endif
  51. namespace Urho3D
  52. {
  53. const int SCREEN_JOYSTICK_START_ID = 0x40000000;
  54. const StringHash VAR_BUTTON_KEY_BINDING("VAR_BUTTON_KEY_BINDING");
  55. const StringHash VAR_BUTTON_MOUSE_BUTTON_BINDING("VAR_BUTTON_MOUSE_BUTTON_BINDING");
  56. const StringHash VAR_LAST_KEYSYM("VAR_LAST_KEYSYM");
  57. const StringHash VAR_SCREEN_JOYSTICK_ID("VAR_SCREEN_JOYSTICK_ID");
  58. const unsigned TOUCHID_MAX = 32;
  59. /// Convert SDL keycode if necessary.
  60. Key ConvertSDLKeyCode(int keySym, int scanCode)
  61. {
  62. if (scanCode == SCANCODE_AC_BACK)
  63. return KEY_ESCAPE;
  64. else
  65. return (Key)SDL_tolower(keySym);
  66. }
  67. UIElement* TouchState::GetTouchedElement()
  68. {
  69. return touchedElement_.Get();
  70. }
  71. #ifdef __EMSCRIPTEN__
  72. #define EM_TRUE 1
  73. #define EM_FALSE 0
  74. /// Glue between Urho Input and Emscripten HTML5
  75. /** HTML5 (Emscripten) is limited in the way it handles input. The EmscriptenInput class attempts to provide the glue between Urho3D Input behavior and HTML5, where SDL currently fails to do so.
  76. *
  77. * Mouse Input:
  78. * - The OS mouse cursor position can't be set.
  79. * - The mouse can be trapped within play area via 'PointerLock API', which requires a request and interaction between the user and browser.
  80. * - To request mouse lock, call SetMouseMode(MM_RELATIVE). The E_MOUSEMODECHANGED event will be sent if/when the user confirms the request.
  81. * NOTE: The request must be initiated by the user (eg: on mouse button down/up, key down/up).
  82. * - The user can press 'escape' key and browser will force user out of pointer lock. Urho will send the E_MOUSEMODECHANGED event.
  83. * - SetMouseMode(MM_ABSOLUTE) will leave pointer lock.
  84. * - MM_WRAP is unsupported.
  85. */
  86. /// % Emscripten Input glue. Intended to be used by the Input subsystem only.
  87. class EmscriptenInput
  88. {
  89. friend class Input;
  90. public:
  91. /// Constructor, expecting pointer to constructing Input instance.
  92. EmscriptenInput(Input* inputInst);
  93. /// Static callback method for Pointer Lock API. Handles change in Pointer Lock state and sends events for mouse mode change.
  94. static EM_BOOL HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData);
  95. /// Static callback method for tracking focus change events.
  96. static EM_BOOL HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData);
  97. /// Static callback method for suppressing mouse jump.
  98. static EM_BOOL HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData);
  99. /// Static callback method to handle SDL events.
  100. static int HandleSDLEvents(void* userData, SDL_Event* event);
  101. /// Send request to user to gain pointer lock. This requires a user-browser interaction on the first call.
  102. void RequestPointerLock(MouseMode mode, bool suppressEvent = false);
  103. /// Send request to exit pointer lock. This has the benefit of not requiring the user-browser interaction on the next pointer lock request.
  104. void ExitPointerLock(bool suppressEvent = false);
  105. /// Returns whether the page is visible.
  106. bool IsVisible();
  107. private:
  108. /// Instance of Input subsystem that constructed this instance.
  109. Input* inputInst_;
  110. /// The mouse mode being requested for pointer-lock.
  111. static MouseMode requestedMouseMode_;
  112. /// Flag indicating whether to suppress the next mouse mode change event.
  113. static bool suppressMouseModeEvent_;
  114. /// The mouse mode of the previous request for pointer-lock.
  115. static MouseMode invalidatedRequestedMouseMode_;
  116. /// Flag indicating the previous request to suppress the next mouse mode change event.
  117. static bool invalidatedSuppressMouseModeEvent_;
  118. };
  119. bool EmscriptenInput::suppressMouseModeEvent_ = false;
  120. MouseMode EmscriptenInput::requestedMouseMode_ = MM_INVALID;
  121. bool EmscriptenInput::invalidatedSuppressMouseModeEvent_ = false;
  122. MouseMode EmscriptenInput::invalidatedRequestedMouseMode_ = MM_INVALID;
  123. EmscriptenInput::EmscriptenInput(Input* inputInst) :
  124. inputInst_(inputInst)
  125. {
  126. auto* vInputInst = (void*)inputInst;
  127. // Handle pointer lock
  128. emscripten_set_pointerlockchange_callback(NULL, vInputInst, false, EmscriptenInput::HandlePointerLockChange);
  129. // Handle mouse events to prevent mouse jumps
  130. emscripten_set_mousedown_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  131. emscripten_set_mousemove_callback(NULL, vInputInst, true, EmscriptenInput::HandleMouseJump);
  132. // Handle focus changes
  133. emscripten_set_focusout_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  134. emscripten_set_focus_callback(NULL, vInputInst, false, EmscriptenInput::HandleFocusChange);
  135. // Handle SDL events
  136. SDL_AddEventWatch(EmscriptenInput::HandleSDLEvents, vInputInst);
  137. }
  138. void EmscriptenInput::RequestPointerLock(MouseMode mode, bool suppressEvent)
  139. {
  140. requestedMouseMode_ = mode;
  141. suppressMouseModeEvent_ = suppressEvent;
  142. emscripten_request_pointerlock(NULL, true);
  143. }
  144. void EmscriptenInput::ExitPointerLock(bool suppressEvent)
  145. {
  146. if (requestedMouseMode_ != MM_INVALID)
  147. {
  148. invalidatedRequestedMouseMode_ = requestedMouseMode_;
  149. invalidatedSuppressMouseModeEvent_ = suppressMouseModeEvent_;
  150. }
  151. requestedMouseMode_ = MM_INVALID;
  152. suppressMouseModeEvent_ = suppressEvent;
  153. if (inputInst_->IsMouseLocked())
  154. {
  155. inputInst_->emscriptenExitingPointerLock_ = true;
  156. emscripten_exit_pointerlock();
  157. }
  158. }
  159. bool EmscriptenInput::IsVisible()
  160. {
  161. EmscriptenVisibilityChangeEvent visibilityStatus;
  162. if (emscripten_get_visibility_status(&visibilityStatus) >= EMSCRIPTEN_RESULT_SUCCESS)
  163. return visibilityStatus.hidden >= EM_TRUE ? false : true;
  164. // Assume visible
  165. URHO3D_LOGWARNING("Could not determine visibility status.");
  166. return true;
  167. }
  168. EM_BOOL EmscriptenInput::HandlePointerLockChange(int eventType, const EmscriptenPointerlockChangeEvent* keyEvent, void* userData)
  169. {
  170. auto* const inputInst = (Input*)userData;
  171. bool invalid = false;
  172. const bool suppress = suppressMouseModeEvent_;
  173. if (requestedMouseMode_ == MM_INVALID && invalidatedRequestedMouseMode_ != MM_INVALID)
  174. {
  175. invalid = true;
  176. requestedMouseMode_ = invalidatedRequestedMouseMode_;
  177. suppressMouseModeEvent_ = invalidatedSuppressMouseModeEvent_;
  178. invalidatedRequestedMouseMode_ = MM_INVALID;
  179. invalidatedSuppressMouseModeEvent_ = false;
  180. }
  181. if (keyEvent->isActive >= EM_TRUE)
  182. {
  183. // Pointer Lock is now active
  184. inputInst->emscriptenPointerLock_ = true;
  185. inputInst->emscriptenEnteredPointerLock_ = true;
  186. inputInst->SetMouseModeEmscriptenFinal(requestedMouseMode_, suppressMouseModeEvent_);
  187. }
  188. else
  189. {
  190. // Pointer Lock is now inactive
  191. inputInst->emscriptenPointerLock_ = false;
  192. if (inputInst->mouseMode_ == MM_RELATIVE)
  193. inputInst->SetMouseModeEmscriptenFinal(MM_FREE, suppressMouseModeEvent_);
  194. else if (inputInst->mouseMode_ == MM_ABSOLUTE)
  195. inputInst->SetMouseModeEmscriptenFinal(MM_ABSOLUTE, suppressMouseModeEvent_);
  196. inputInst->emscriptenExitingPointerLock_ = false;
  197. }
  198. if (invalid)
  199. {
  200. if (keyEvent->isActive >= EM_TRUE)
  201. {
  202. // ExitPointerLock was called before the pointer-lock request was accepted.
  203. // Exit from pointer-lock to avoid unexpected behavior.
  204. invalidatedRequestedMouseMode_ = MM_INVALID;
  205. inputInst->emscriptenInput_->ExitPointerLock(suppress);
  206. return EM_TRUE;
  207. }
  208. }
  209. requestedMouseMode_ = MM_INVALID;
  210. suppressMouseModeEvent_ = false;
  211. invalidatedRequestedMouseMode_ = MM_INVALID;
  212. invalidatedSuppressMouseModeEvent_ = false;
  213. return EM_TRUE;
  214. }
  215. EM_BOOL EmscriptenInput::HandleFocusChange(int eventType, const EmscriptenFocusEvent* keyEvent, void* userData)
  216. {
  217. auto* const inputInst = (Input*)userData;
  218. inputInst->SuppressNextMouseMove();
  219. if (eventType == EMSCRIPTEN_EVENT_FOCUSOUT)
  220. inputInst->LoseFocus();
  221. else if (eventType == EMSCRIPTEN_EVENT_FOCUS)
  222. inputInst->GainFocus();
  223. return EM_TRUE;
  224. }
  225. EM_BOOL EmscriptenInput::HandleMouseJump(int eventType, const EmscriptenMouseEvent * mouseEvent, void* userData)
  226. {
  227. // Suppress mouse jump on pointer-lock change
  228. auto* const inputInst = (Input*)userData;
  229. bool suppress = false;
  230. if (eventType == EMSCRIPTEN_EVENT_MOUSEDOWN && inputInst->emscriptenEnteredPointerLock_)
  231. {
  232. suppress = true;
  233. inputInst->emscriptenEnteredPointerLock_ = false;
  234. }
  235. else if (eventType == EMSCRIPTEN_EVENT_MOUSEMOVE && inputInst->emscriptenExitingPointerLock_)
  236. {
  237. suppress = true;
  238. }
  239. if (suppress)
  240. inputInst->SuppressNextMouseMove();
  241. return EM_FALSE;
  242. }
  243. int EmscriptenInput::HandleSDLEvents(void* userData, SDL_Event* event)
  244. {
  245. auto* const inputInst = (Input*)userData;
  246. inputInst->HandleSDLEvent(event);
  247. return 0;
  248. }
  249. #endif
  250. #ifdef _WIN32
  251. // On Windows repaint while the window is actively being resized.
  252. int Win32_ResizingEventWatcher(void* data, SDL_Event* event)
  253. {
  254. if (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_RESIZED)
  255. {
  256. SDL_Window* win = SDL_GetWindowFromID(event->window.windowID);
  257. if (win == (SDL_Window*)data)
  258. {
  259. if (auto* ctx = (Context*)SDL_GetWindowData(win, "URHO3D_CONTEXT"))
  260. {
  261. if (auto* graphics = ctx->GetSubsystem<Graphics>())
  262. {
  263. if (graphics->IsInitialized())
  264. {
  265. graphics->OnWindowResized();
  266. ctx->GetSubsystem<Engine>()->RunFrame();
  267. }
  268. }
  269. }
  270. }
  271. }
  272. return 0;
  273. }
  274. #endif
  275. void JoystickState::Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats)
  276. {
  277. buttons_.Resize(numButtons);
  278. buttonPress_.Resize(numButtons);
  279. axes_.Resize(numAxes);
  280. hats_.Resize(numHats);
  281. Reset();
  282. }
  283. void JoystickState::Reset()
  284. {
  285. for (unsigned i = 0; i < buttons_.Size(); ++i)
  286. {
  287. buttons_[i] = false;
  288. buttonPress_[i] = false;
  289. }
  290. for (unsigned i = 0; i < axes_.Size(); ++i)
  291. axes_[i] = 0.0f;
  292. for (unsigned i = 0; i < hats_.Size(); ++i)
  293. hats_[i] = HAT_CENTER;
  294. }
  295. Input::Input(Context* context) :
  296. Object(context),
  297. mouseButtonDown_(0),
  298. mouseButtonPress_(0),
  299. lastVisibleMousePosition_(MOUSE_POSITION_OFFSCREEN),
  300. mouseMoveWheel_(0),
  301. inputScale_(Vector2::ONE),
  302. windowID_(0),
  303. toggleFullscreen_(true),
  304. mouseVisible_(false),
  305. lastMouseVisible_(false),
  306. mouseGrabbed_(false),
  307. lastMouseGrabbed_(false),
  308. mouseMode_(MM_ABSOLUTE),
  309. lastMouseMode_(MM_ABSOLUTE),
  310. #ifndef __EMSCRIPTEN__
  311. sdlMouseRelative_(false),
  312. #else
  313. emscriptenPointerLock_(false),
  314. emscriptenEnteredPointerLock_(false),
  315. emscriptenExitingPointerLock_(false),
  316. #endif
  317. touchEmulation_(false),
  318. inputFocus_(false),
  319. minimized_(false),
  320. focusedThisFrame_(false),
  321. suppressNextMouseMove_(false),
  322. mouseMoveScaled_(false),
  323. initialized_(false)
  324. {
  325. context_->RequireSDL(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
  326. for (int i = 0; i < TOUCHID_MAX; i++)
  327. availableTouchIDs_.Push(i);
  328. SubscribeToEvent(E_SCREENMODE, URHO3D_HANDLER(Input, HandleScreenMode));
  329. #if defined(__ANDROID__)
  330. // Prevent mouse events from being registered as synthetic touch events and vice versa
  331. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0");
  332. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  333. #elif defined(__EMSCRIPTEN__)
  334. emscriptenInput_ = new EmscriptenInput(this);
  335. #endif
  336. // Try to initialize right now, but skip if screen mode is not yet set
  337. Initialize();
  338. }
  339. Input::~Input()
  340. {
  341. context_->ReleaseSDL();
  342. }
  343. void Input::Update()
  344. {
  345. assert(initialized_);
  346. URHO3D_PROFILE(UpdateInput);
  347. #ifndef __EMSCRIPTEN__
  348. bool mouseMoved = false;
  349. if (mouseMove_ != IntVector2::ZERO)
  350. mouseMoved = true;
  351. ResetInputAccumulation();
  352. SDL_Event evt;
  353. while (SDL_PollEvent(&evt))
  354. HandleSDLEvent(&evt);
  355. if (suppressNextMouseMove_ && (mouseMove_ != IntVector2::ZERO || mouseMoved))
  356. UnsuppressMouseMove();
  357. #endif
  358. // Check for focus change this frame
  359. SDL_Window* window = graphics_->GetWindow();
  360. unsigned flags = window ? SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS) : 0;
  361. #ifndef __EMSCRIPTEN__
  362. if (window)
  363. {
  364. #ifdef REQUIRE_CLICK_TO_FOCUS
  365. // When using the "click to focus" mechanism, only focus automatically in fullscreen or non-hidden mouse mode
  366. if (!inputFocus_ && ((mouseVisible_ || mouseMode_ == MM_FREE) || graphics_->GetFullscreen()) && (flags & SDL_WINDOW_INPUT_FOCUS))
  367. #else
  368. if (!inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS))
  369. #endif
  370. focusedThisFrame_ = true;
  371. if (focusedThisFrame_)
  372. GainFocus();
  373. // Check for losing focus. The window flags are not reliable when using an external window, so prevent losing focus in that case
  374. if (inputFocus_ && !graphics_->GetExternalWindow() && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  375. LoseFocus();
  376. }
  377. else
  378. return;
  379. // Handle mouse mode MM_WRAP
  380. if (mouseVisible_ && mouseMode_ == MM_WRAP)
  381. {
  382. IntVector2 windowPos = graphics_->GetWindowPosition();
  383. IntVector2 mpos;
  384. SDL_GetGlobalMouseState(&mpos.x_, &mpos.y_);
  385. mpos -= windowPos;
  386. const int buffer = 5;
  387. const int width = graphics_->GetWidth() - buffer * 2;
  388. const int height = graphics_->GetHeight() - buffer * 2;
  389. // SetMousePosition utilizes backbuffer coordinate system, scale now from window coordinates
  390. mpos.x_ = (int)(mpos.x_ * inputScale_.x_);
  391. mpos.y_ = (int)(mpos.y_ * inputScale_.y_);
  392. bool warp = false;
  393. if (mpos.x_ < buffer)
  394. {
  395. warp = true;
  396. mpos.x_ += width;
  397. }
  398. if (mpos.x_ > buffer + width)
  399. {
  400. warp = true;
  401. mpos.x_ -= width;
  402. }
  403. if (mpos.y_ < buffer)
  404. {
  405. warp = true;
  406. mpos.y_ += height;
  407. }
  408. if (mpos.y_ > buffer + height)
  409. {
  410. warp = true;
  411. mpos.y_ -= height;
  412. }
  413. if (warp)
  414. {
  415. SetMousePosition(mpos);
  416. SuppressNextMouseMove();
  417. }
  418. }
  419. #else
  420. if (!window)
  421. return;
  422. #endif
  423. #ifndef __EMSCRIPTEN__
  424. if (!touchEmulation_ && (graphics_->GetExternalWindow() || ((!sdlMouseRelative_ && !mouseVisible_ && mouseMode_ != MM_FREE) && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  425. #else
  426. if (!touchEmulation_ && !emscriptenPointerLock_ && (graphics_->GetExternalWindow() || (!mouseVisible_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  427. #endif
  428. {
  429. const IntVector2 mousePosition = GetMousePosition();
  430. mouseMove_ = mousePosition - lastMousePosition_;
  431. mouseMoveScaled_ = true; // Already in backbuffer scale, since GetMousePosition() operates in that
  432. #ifndef __EMSCRIPTEN__
  433. if (graphics_->GetExternalWindow())
  434. lastMousePosition_ = mousePosition;
  435. else
  436. {
  437. // Recenter the mouse cursor manually after move
  438. CenterMousePosition();
  439. }
  440. #else
  441. if (mouseMode_ == MM_ABSOLUTE || mouseMode_ == MM_FREE)
  442. lastMousePosition_ = mousePosition;
  443. if (emscriptenExitingPointerLock_)
  444. SuppressNextMouseMove();
  445. #endif
  446. // Send mouse move event if necessary
  447. if (mouseMove_ != IntVector2::ZERO)
  448. {
  449. if (!suppressNextMouseMove_)
  450. {
  451. using namespace MouseMove;
  452. VariantMap& eventData = GetEventDataMap();
  453. eventData[P_X] = mousePosition.x_;
  454. eventData[P_Y] = mousePosition.y_;
  455. eventData[P_DX] = mouseMove_.x_;
  456. eventData[P_DY] = mouseMove_.y_;
  457. eventData[P_BUTTONS] = (unsigned)mouseButtonDown_;
  458. eventData[P_QUALIFIERS] = (unsigned)GetQualifiers();
  459. SendEvent(E_MOUSEMOVE, eventData);
  460. }
  461. }
  462. }
  463. #ifndef __EMSCRIPTEN__
  464. else if (!touchEmulation_ && !mouseVisible_ && sdlMouseRelative_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))
  465. {
  466. // Keep the cursor trapped in window.
  467. CenterMousePosition();
  468. }
  469. #endif
  470. }
  471. void Input::SetMouseVisible(bool enable, bool suppressEvent)
  472. {
  473. const bool startMouseVisible = mouseVisible_;
  474. // In touch emulation mode only enabled mouse is allowed
  475. if (touchEmulation_)
  476. enable = true;
  477. // In mouse mode relative, the mouse should be invisible
  478. if (mouseMode_ == MM_RELATIVE)
  479. {
  480. if (!suppressEvent)
  481. lastMouseVisible_ = enable;
  482. enable = false;
  483. }
  484. // SDL Raspberry Pi "video driver" does not have proper OS mouse support yet, so no-op for now
  485. #ifndef RPI
  486. if (enable != mouseVisible_)
  487. {
  488. if (initialized_)
  489. {
  490. // External windows can only support visible mouse cursor
  491. if (graphics_->GetExternalWindow())
  492. {
  493. mouseVisible_ = true;
  494. if (!suppressEvent)
  495. lastMouseVisible_ = true;
  496. return;
  497. }
  498. if (!enable && inputFocus_)
  499. {
  500. #ifndef __EMSCRIPTEN__
  501. if (mouseVisible_)
  502. lastVisibleMousePosition_ = GetMousePosition();
  503. if (mouseMode_ == MM_ABSOLUTE)
  504. SetMouseModeAbsolute(SDL_TRUE);
  505. #else
  506. if (mouseMode_ == MM_ABSOLUTE && !emscriptenPointerLock_)
  507. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  508. #endif
  509. SDL_ShowCursor(SDL_FALSE);
  510. mouseVisible_ = false;
  511. }
  512. else if (mouseMode_ != MM_RELATIVE)
  513. {
  514. SetMouseGrabbed(false, suppressEvent);
  515. SDL_ShowCursor(SDL_TRUE);
  516. mouseVisible_ = true;
  517. #ifndef __EMSCRIPTEN__
  518. if (mouseMode_ == MM_ABSOLUTE)
  519. SetMouseModeAbsolute(SDL_FALSE);
  520. // Update cursor position
  521. auto* ui = GetSubsystem<UI>();
  522. Cursor* cursor = ui->GetCursor();
  523. // If the UI Cursor was visible, use that position instead of last visible OS cursor position
  524. if (cursor && cursor->IsVisible())
  525. {
  526. IntVector2 pos = cursor->GetScreenPosition();
  527. if (pos != MOUSE_POSITION_OFFSCREEN)
  528. {
  529. SetMousePosition(pos);
  530. lastMousePosition_ = pos;
  531. }
  532. }
  533. else
  534. {
  535. if (lastVisibleMousePosition_ != MOUSE_POSITION_OFFSCREEN)
  536. {
  537. SetMousePosition(lastVisibleMousePosition_);
  538. lastMousePosition_ = lastVisibleMousePosition_;
  539. }
  540. }
  541. #else
  542. if (mouseMode_ == MM_ABSOLUTE && emscriptenPointerLock_)
  543. emscriptenInput_->ExitPointerLock(suppressEvent);
  544. #endif
  545. }
  546. }
  547. else
  548. {
  549. // Allow to set desired mouse visibility before initialization
  550. mouseVisible_ = enable;
  551. }
  552. if (mouseVisible_ != startMouseVisible)
  553. {
  554. SuppressNextMouseMove();
  555. if (!suppressEvent)
  556. {
  557. lastMouseVisible_ = mouseVisible_;
  558. using namespace MouseVisibleChanged;
  559. VariantMap& eventData = GetEventDataMap();
  560. eventData[P_VISIBLE] = mouseVisible_;
  561. SendEvent(E_MOUSEVISIBLECHANGED, eventData);
  562. }
  563. }
  564. }
  565. #endif
  566. }
  567. void Input::ResetMouseVisible()
  568. {
  569. #ifndef __EMSCRIPTEN__
  570. SetMouseVisible(lastMouseVisible_, false);
  571. #else
  572. SetMouseVisibleEmscripten(lastMouseVisible_, false);
  573. #endif
  574. }
  575. #ifdef __EMSCRIPTEN__
  576. void Input::SetMouseVisibleEmscripten(bool enable, bool suppressEvent)
  577. {
  578. if (enable != mouseVisible_)
  579. {
  580. if (mouseMode_ == MM_ABSOLUTE)
  581. {
  582. if (enable)
  583. {
  584. mouseVisible_ = true;
  585. SDL_ShowCursor(SDL_TRUE);
  586. emscriptenInput_->ExitPointerLock(suppressEvent);
  587. }
  588. else
  589. {
  590. if (emscriptenPointerLock_)
  591. {
  592. mouseVisible_ = false;
  593. SDL_ShowCursor(SDL_FALSE);
  594. }
  595. else
  596. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  597. }
  598. }
  599. else
  600. {
  601. mouseVisible_ = enable;
  602. SDL_ShowCursor(enable ? SDL_TRUE : SDL_FALSE);
  603. }
  604. }
  605. if (!suppressEvent)
  606. lastMouseVisible_ = mouseVisible_;
  607. }
  608. void Input::SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent)
  609. {
  610. if (!suppressEvent)
  611. lastMouseMode_ = mode;
  612. mouseMode_ = mode;
  613. if (mode == MM_ABSOLUTE)
  614. {
  615. if (emscriptenPointerLock_)
  616. {
  617. SetMouseVisibleEmscripten(false, suppressEvent);
  618. }
  619. else
  620. {
  621. SetMouseVisibleEmscripten(true, suppressEvent);
  622. }
  623. UI* const ui = GetSubsystem<UI>();
  624. Cursor* const cursor = ui->GetCursor();
  625. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  626. }
  627. else if (mode == MM_RELATIVE && emscriptenPointerLock_)
  628. {
  629. SetMouseGrabbed(true, suppressEvent);
  630. SetMouseVisibleEmscripten(false, suppressEvent);
  631. }
  632. else
  633. {
  634. SetMouseGrabbed(false, suppressEvent);
  635. }
  636. SuppressNextMouseMove();
  637. if (!suppressEvent)
  638. {
  639. VariantMap& eventData = GetEventDataMap();
  640. eventData[MouseModeChanged::P_MODE] = mode;
  641. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  642. SendEvent(E_MOUSEMODECHANGED, eventData);
  643. }
  644. }
  645. void Input::SetMouseModeEmscripten(MouseMode mode, bool suppressEvent)
  646. {
  647. if (mode != mouseMode_)
  648. SuppressNextMouseMove();
  649. const MouseMode previousMode = mouseMode_;
  650. mouseMode_ = mode;
  651. UI* const ui = GetSubsystem<UI>();
  652. Cursor* const cursor = ui->GetCursor();
  653. // Handle changing from previous mode
  654. if (previousMode == MM_RELATIVE)
  655. ResetMouseVisible();
  656. // Handle changing to new mode
  657. if (mode == MM_FREE)
  658. {
  659. // Attempt to cancel pending pointer-lock requests
  660. emscriptenInput_->ExitPointerLock(suppressEvent);
  661. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  662. }
  663. else if (mode == MM_ABSOLUTE)
  664. {
  665. if (!mouseVisible_)
  666. {
  667. if (emscriptenPointerLock_)
  668. {
  669. SetMouseVisibleEmscripten(false, suppressEvent);
  670. }
  671. else
  672. {
  673. if (!cursor)
  674. SetMouseVisible(true, suppressEvent);
  675. // Deferred mouse mode change to pointer-lock callback
  676. mouseMode_ = previousMode;
  677. emscriptenInput_->RequestPointerLock(MM_ABSOLUTE, suppressEvent);
  678. }
  679. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  680. }
  681. }
  682. else if (mode == MM_RELATIVE)
  683. {
  684. if (emscriptenPointerLock_)
  685. {
  686. SetMouseVisibleEmscripten(false, true);
  687. SetMouseGrabbed(!(cursor && cursor->IsVisible()), suppressEvent);
  688. }
  689. else
  690. {
  691. // Defer mouse mode change to pointer-lock callback
  692. SetMouseGrabbed(false, true);
  693. mouseMode_ = previousMode;
  694. emscriptenInput_->RequestPointerLock(MM_RELATIVE, suppressEvent);
  695. }
  696. }
  697. }
  698. #endif
  699. void Input::SetMouseGrabbed(bool grab, bool suppressEvent)
  700. {
  701. // To not interfere with touch UI operation, never report the mouse as grabbed on Android / iOS
  702. #if !defined(__ANDROID__) && !defined(IOS)
  703. mouseGrabbed_ = grab;
  704. if (!suppressEvent)
  705. lastMouseGrabbed_ = grab;
  706. #endif
  707. }
  708. void Input::ResetMouseGrabbed()
  709. {
  710. SetMouseGrabbed(lastMouseGrabbed_, true);
  711. }
  712. #ifndef __EMSCRIPTEN__
  713. void Input::SetMouseModeAbsolute(SDL_bool enable)
  714. {
  715. SDL_Window* const window = graphics_->GetWindow();
  716. SDL_SetWindowGrab(window, enable);
  717. }
  718. void Input::SetMouseModeRelative(SDL_bool enable)
  719. {
  720. SDL_Window* const window = graphics_->GetWindow();
  721. int result = SDL_SetRelativeMouseMode(enable);
  722. sdlMouseRelative_ = enable && (result == 0);
  723. if (result == -1)
  724. SDL_SetWindowGrab(window, enable);
  725. }
  726. #endif
  727. void Input::SetMouseMode(MouseMode mode, bool suppressEvent)
  728. {
  729. const MouseMode previousMode = mouseMode_;
  730. #ifdef __EMSCRIPTEN__
  731. SetMouseModeEmscripten(mode, suppressEvent);
  732. #else
  733. if (mode != mouseMode_)
  734. {
  735. if (initialized_)
  736. {
  737. SuppressNextMouseMove();
  738. mouseMode_ = mode;
  739. SDL_Window* const window = graphics_->GetWindow();
  740. auto* const ui = GetSubsystem<UI>();
  741. Cursor* const cursor = ui->GetCursor();
  742. // Handle changing from previous mode
  743. if (previousMode == MM_ABSOLUTE)
  744. {
  745. if (!mouseVisible_)
  746. SetMouseModeAbsolute(SDL_FALSE);
  747. }
  748. if (previousMode == MM_RELATIVE)
  749. {
  750. SetMouseModeRelative(SDL_FALSE);
  751. ResetMouseVisible();
  752. }
  753. else if (previousMode == MM_WRAP)
  754. SDL_SetWindowGrab(window, SDL_FALSE);
  755. // Handle changing to new mode
  756. if (mode == MM_ABSOLUTE)
  757. {
  758. if (!mouseVisible_)
  759. SetMouseModeAbsolute(SDL_TRUE);
  760. }
  761. else if (mode == MM_RELATIVE)
  762. {
  763. SetMouseVisible(false, true);
  764. SetMouseModeRelative(SDL_TRUE);
  765. }
  766. else if (mode == MM_WRAP)
  767. {
  768. SetMouseGrabbed(true, suppressEvent);
  769. SDL_SetWindowGrab(window, SDL_TRUE);
  770. }
  771. if (mode != MM_WRAP)
  772. SetMouseGrabbed(!(mouseVisible_ || (cursor && cursor->IsVisible())), suppressEvent);
  773. }
  774. else
  775. {
  776. // Allow to set desired mouse mode before initialization
  777. mouseMode_ = mode;
  778. }
  779. }
  780. #endif
  781. if (!suppressEvent)
  782. {
  783. lastMouseMode_ = mode;
  784. if (mouseMode_ != previousMode)
  785. {
  786. VariantMap& eventData = GetEventDataMap();
  787. eventData[MouseModeChanged::P_MODE] = mode;
  788. eventData[MouseModeChanged::P_MOUSELOCKED] = IsMouseLocked();
  789. SendEvent(E_MOUSEMODECHANGED, eventData);
  790. }
  791. }
  792. }
  793. void Input::ResetMouseMode()
  794. {
  795. SetMouseMode(lastMouseMode_, false);
  796. }
  797. void Input::SetToggleFullscreen(bool enable)
  798. {
  799. toggleFullscreen_ = enable;
  800. }
  801. static void PopulateKeyBindingMap(HashMap<String, int>& keyBindingMap)
  802. {
  803. if (keyBindingMap.Empty())
  804. {
  805. keyBindingMap.Insert(MakePair<String, int>("SPACE", KEY_SPACE));
  806. keyBindingMap.Insert(MakePair<String, int>("LCTRL", KEY_LCTRL));
  807. keyBindingMap.Insert(MakePair<String, int>("RCTRL", KEY_RCTRL));
  808. keyBindingMap.Insert(MakePair<String, int>("LSHIFT", KEY_LSHIFT));
  809. keyBindingMap.Insert(MakePair<String, int>("RSHIFT", KEY_RSHIFT));
  810. keyBindingMap.Insert(MakePair<String, int>("LALT", KEY_LALT));
  811. keyBindingMap.Insert(MakePair<String, int>("RALT", KEY_RALT));
  812. keyBindingMap.Insert(MakePair<String, int>("LGUI", KEY_LGUI));
  813. keyBindingMap.Insert(MakePair<String, int>("RGUI", KEY_RGUI));
  814. keyBindingMap.Insert(MakePair<String, int>("TAB", KEY_TAB));
  815. keyBindingMap.Insert(MakePair<String, int>("RETURN", KEY_RETURN));
  816. keyBindingMap.Insert(MakePair<String, int>("RETURN2", KEY_RETURN2));
  817. keyBindingMap.Insert(MakePair<String, int>("ENTER", KEY_KP_ENTER));
  818. keyBindingMap.Insert(MakePair<String, int>("SELECT", KEY_SELECT));
  819. keyBindingMap.Insert(MakePair<String, int>("LEFT", KEY_LEFT));
  820. keyBindingMap.Insert(MakePair<String, int>("RIGHT", KEY_RIGHT));
  821. keyBindingMap.Insert(MakePair<String, int>("UP", KEY_UP));
  822. keyBindingMap.Insert(MakePair<String, int>("DOWN", KEY_DOWN));
  823. keyBindingMap.Insert(MakePair<String, int>("PAGEUP", KEY_PAGEUP));
  824. keyBindingMap.Insert(MakePair<String, int>("PAGEDOWN", KEY_PAGEDOWN));
  825. keyBindingMap.Insert(MakePair<String, int>("F1", KEY_F1));
  826. keyBindingMap.Insert(MakePair<String, int>("F2", KEY_F2));
  827. keyBindingMap.Insert(MakePair<String, int>("F3", KEY_F3));
  828. keyBindingMap.Insert(MakePair<String, int>("F4", KEY_F4));
  829. keyBindingMap.Insert(MakePair<String, int>("F5", KEY_F5));
  830. keyBindingMap.Insert(MakePair<String, int>("F6", KEY_F6));
  831. keyBindingMap.Insert(MakePair<String, int>("F7", KEY_F7));
  832. keyBindingMap.Insert(MakePair<String, int>("F8", KEY_F8));
  833. keyBindingMap.Insert(MakePair<String, int>("F9", KEY_F9));
  834. keyBindingMap.Insert(MakePair<String, int>("F10", KEY_F10));
  835. keyBindingMap.Insert(MakePair<String, int>("F11", KEY_F11));
  836. keyBindingMap.Insert(MakePair<String, int>("F12", KEY_F12));
  837. }
  838. }
  839. static void PopulateMouseButtonBindingMap(HashMap<String, int>& mouseButtonBindingMap)
  840. {
  841. if (mouseButtonBindingMap.Empty())
  842. {
  843. mouseButtonBindingMap.Insert(MakePair<String, int>("LEFT", SDL_BUTTON_LEFT));
  844. mouseButtonBindingMap.Insert(MakePair<String, int>("MIDDLE", SDL_BUTTON_MIDDLE));
  845. mouseButtonBindingMap.Insert(MakePair<String, int>("RIGHT", SDL_BUTTON_RIGHT));
  846. mouseButtonBindingMap.Insert(MakePair<String, int>("X1", SDL_BUTTON_X1));
  847. mouseButtonBindingMap.Insert(MakePair<String, int>("X2", SDL_BUTTON_X2));
  848. }
  849. }
  850. SDL_JoystickID Input::AddScreenJoystick(XMLFile* layoutFile, XMLFile* styleFile)
  851. {
  852. static HashMap<String, int> keyBindingMap;
  853. static HashMap<String, int> mouseButtonBindingMap;
  854. if (!graphics_)
  855. {
  856. URHO3D_LOGWARNING("Cannot add screen joystick in headless mode");
  857. return -1;
  858. }
  859. // If layout file is not given, use the default screen joystick layout
  860. if (!layoutFile)
  861. {
  862. auto* cache = GetSubsystem<ResourceCache>();
  863. layoutFile = cache->GetResource<XMLFile>("UI/ScreenJoystick.xml");
  864. if (!layoutFile) // Error is already logged
  865. return -1;
  866. }
  867. auto* ui = GetSubsystem<UI>();
  868. SharedPtr<UIElement> screenJoystick = ui->LoadLayout(layoutFile, styleFile);
  869. if (!screenJoystick) // Error is already logged
  870. return -1;
  871. screenJoystick->SetSize(ui->GetRoot()->GetSize());
  872. ui->GetRoot()->AddChild(screenJoystick);
  873. // Get an unused ID for the screen joystick
  874. /// \todo After a real joystick has been plugged in 1073741824 times, the ranges will overlap
  875. SDL_JoystickID joystickID = SCREEN_JOYSTICK_START_ID;
  876. while (joysticks_.Contains(joystickID))
  877. ++joystickID;
  878. JoystickState& state = joysticks_[joystickID];
  879. state.joystickID_ = joystickID;
  880. state.name_ = screenJoystick->GetName();
  881. state.screenJoystick_ = screenJoystick;
  882. unsigned numButtons = 0;
  883. unsigned numAxes = 0;
  884. unsigned numHats = 0;
  885. const Vector<SharedPtr<UIElement> >& children = state.screenJoystick_->GetChildren();
  886. for (Vector<SharedPtr<UIElement> >::ConstIterator iter = children.Begin(); iter != children.End(); ++iter)
  887. {
  888. UIElement* element = iter->Get();
  889. String name = element->GetName();
  890. if (name.StartsWith("Button"))
  891. {
  892. ++numButtons;
  893. // Check whether the button has key binding
  894. auto* text = element->GetChildDynamicCast<Text>("KeyBinding", false);
  895. if (text)
  896. {
  897. text->SetVisible(false);
  898. const String& key = text->GetText();
  899. int keyBinding;
  900. if (key.Length() == 1)
  901. keyBinding = key[0];
  902. else
  903. {
  904. PopulateKeyBindingMap(keyBindingMap);
  905. HashMap<String, int>::Iterator i = keyBindingMap.Find(key);
  906. if (i != keyBindingMap.End())
  907. keyBinding = i->second_;
  908. else
  909. {
  910. URHO3D_LOGERRORF("Unsupported key binding: %s", key.CString());
  911. keyBinding = M_MAX_INT;
  912. }
  913. }
  914. if (keyBinding != M_MAX_INT)
  915. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  916. }
  917. // Check whether the button has mouse button binding
  918. text = element->GetChildDynamicCast<Text>("MouseButtonBinding", false);
  919. if (text)
  920. {
  921. text->SetVisible(false);
  922. const String& mouseButton = text->GetText();
  923. PopulateMouseButtonBindingMap(mouseButtonBindingMap);
  924. HashMap<String, int>::Iterator i = mouseButtonBindingMap.Find(mouseButton);
  925. if (i != mouseButtonBindingMap.End())
  926. element->SetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING, i->second_);
  927. else
  928. URHO3D_LOGERRORF("Unsupported mouse button binding: %s", mouseButton.CString());
  929. }
  930. }
  931. else if (name.StartsWith("Axis"))
  932. {
  933. ++numAxes;
  934. ///\todo Axis emulation for screen joystick is not fully supported yet.
  935. URHO3D_LOGWARNING("Axis emulation for screen joystick is not fully supported yet");
  936. }
  937. else if (name.StartsWith("Hat"))
  938. {
  939. ++numHats;
  940. auto* text = element->GetChildDynamicCast<Text>("KeyBinding", false);
  941. if (text)
  942. {
  943. text->SetVisible(false);
  944. String keyBinding = text->GetText();
  945. int mappedKeyBinding[4] = {KEY_W, KEY_S, KEY_A, KEY_D};
  946. Vector<String> keyBindings;
  947. if (keyBinding.Contains(' ')) // e.g.: "UP DOWN LEFT RIGHT"
  948. keyBindings = keyBinding.Split(' '); // Attempt to split the text using ' ' as separator
  949. else if (keyBinding.Length() == 4)
  950. {
  951. keyBindings.Resize(4); // e.g.: "WSAD"
  952. for (unsigned i = 0; i < 4; ++i)
  953. keyBindings[i] = keyBinding.Substring(i, 1);
  954. }
  955. if (keyBindings.Size() == 4)
  956. {
  957. PopulateKeyBindingMap(keyBindingMap);
  958. for (unsigned j = 0; j < 4; ++j)
  959. {
  960. if (keyBindings[j].Length() == 1)
  961. mappedKeyBinding[j] = keyBindings[j][0];
  962. else
  963. {
  964. HashMap<String, int>::Iterator i = keyBindingMap.Find(keyBindings[j]);
  965. if (i != keyBindingMap.End())
  966. mappedKeyBinding[j] = i->second_;
  967. else
  968. URHO3D_LOGERRORF("%s - %s cannot be mapped, fallback to '%c'", name.CString(), keyBindings[j].CString(),
  969. mappedKeyBinding[j]);
  970. }
  971. }
  972. }
  973. else
  974. URHO3D_LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  975. element->SetVar(VAR_BUTTON_KEY_BINDING, IntRect(mappedKeyBinding));
  976. }
  977. }
  978. element->SetVar(VAR_SCREEN_JOYSTICK_ID, joystickID);
  979. }
  980. // Make sure all the children are non-focusable so they do not mistakenly to be considered as active UI input controls by application
  981. PODVector<UIElement*> allChildren;
  982. state.screenJoystick_->GetChildren(allChildren, true);
  983. for (PODVector<UIElement*>::Iterator iter = allChildren.Begin(); iter != allChildren.End(); ++iter)
  984. (*iter)->SetFocusMode(FM_NOTFOCUSABLE);
  985. state.Initialize(numButtons, numAxes, numHats);
  986. // There could be potentially more than one screen joystick, however they all will be handled by a same handler method
  987. // So there is no harm to replace the old handler with the new handler in each call to SubscribeToEvent()
  988. SubscribeToEvent(E_TOUCHBEGIN, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  989. SubscribeToEvent(E_TOUCHMOVE, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  990. SubscribeToEvent(E_TOUCHEND, URHO3D_HANDLER(Input, HandleScreenJoystickTouch));
  991. return joystickID;
  992. }
  993. bool Input::RemoveScreenJoystick(SDL_JoystickID id)
  994. {
  995. if (!joysticks_.Contains(id))
  996. {
  997. URHO3D_LOGERRORF("Failed to remove non-existing screen joystick ID #%d", id);
  998. return false;
  999. }
  1000. JoystickState& state = joysticks_[id];
  1001. if (!state.screenJoystick_)
  1002. {
  1003. URHO3D_LOGERRORF("Failed to remove joystick with ID #%d which is not a screen joystick", id);
  1004. return false;
  1005. }
  1006. state.screenJoystick_->Remove();
  1007. joysticks_.Erase(id);
  1008. return true;
  1009. }
  1010. void Input::SetScreenJoystickVisible(SDL_JoystickID id, bool enable)
  1011. {
  1012. if (joysticks_.Contains(id))
  1013. {
  1014. JoystickState& state = joysticks_[id];
  1015. if (state.screenJoystick_)
  1016. state.screenJoystick_->SetVisible(enable);
  1017. }
  1018. }
  1019. void Input::SetScreenKeyboardVisible(bool enable)
  1020. {
  1021. if (enable != SDL_IsTextInputActive())
  1022. {
  1023. if (enable)
  1024. SDL_StartTextInput();
  1025. else
  1026. SDL_StopTextInput();
  1027. }
  1028. }
  1029. void Input::SetTouchEmulation(bool enable)
  1030. {
  1031. #if !defined(__ANDROID__) && !defined(IOS)
  1032. if (enable != touchEmulation_)
  1033. {
  1034. if (enable)
  1035. {
  1036. // Touch emulation needs the mouse visible
  1037. if (!mouseVisible_)
  1038. SetMouseVisible(true);
  1039. // Add a virtual touch device the first time we are enabling emulated touch
  1040. if (!SDL_GetNumTouchDevices())
  1041. SDL_AddTouch(0, SDL_TOUCH_DEVICE_INDIRECT_RELATIVE, "Emulated Touch");
  1042. }
  1043. else
  1044. ResetTouches();
  1045. touchEmulation_ = enable;
  1046. }
  1047. #endif
  1048. }
  1049. bool Input::RecordGesture()
  1050. {
  1051. // If have no touch devices, fail
  1052. if (!SDL_GetNumTouchDevices())
  1053. {
  1054. URHO3D_LOGERROR("Can not record gesture: no touch devices");
  1055. return false;
  1056. }
  1057. return SDL_RecordGesture(-1) != 0;
  1058. }
  1059. bool Input::SaveGestures(Serializer& dest)
  1060. {
  1061. RWOpsWrapper<Serializer> wrapper(dest);
  1062. return SDL_SaveAllDollarTemplates(wrapper.GetRWOps()) != 0;
  1063. }
  1064. bool Input::SaveGesture(Serializer& dest, unsigned gestureID)
  1065. {
  1066. RWOpsWrapper<Serializer> wrapper(dest);
  1067. return SDL_SaveDollarTemplate(gestureID, wrapper.GetRWOps()) != 0;
  1068. }
  1069. unsigned Input::LoadGestures(Deserializer& source)
  1070. {
  1071. // If have no touch devices, fail
  1072. if (!SDL_GetNumTouchDevices())
  1073. {
  1074. URHO3D_LOGERROR("Can not load gestures: no touch devices");
  1075. return 0;
  1076. }
  1077. RWOpsWrapper<Deserializer> wrapper(source);
  1078. return (unsigned)SDL_LoadDollarTemplates(-1, wrapper.GetRWOps());
  1079. }
  1080. bool Input::RemoveGesture(unsigned gestureID)
  1081. {
  1082. #ifdef __EMSCRIPTEN__
  1083. return false;
  1084. #else
  1085. return SDL_RemoveDollarTemplate(gestureID) != 0;
  1086. #endif
  1087. }
  1088. void Input::RemoveAllGestures()
  1089. {
  1090. #ifndef __EMSCRIPTEN__
  1091. SDL_RemoveAllDollarTemplates();
  1092. #endif
  1093. }
  1094. SDL_JoystickID Input::OpenJoystick(unsigned index)
  1095. {
  1096. SDL_Joystick* joystick = SDL_JoystickOpen(index);
  1097. if (!joystick)
  1098. {
  1099. URHO3D_LOGERRORF("Cannot open joystick #%d", index);
  1100. return -1;
  1101. }
  1102. // Create joystick state for the new joystick
  1103. int joystickID = SDL_JoystickInstanceID(joystick);
  1104. JoystickState& state = joysticks_[joystickID];
  1105. state.joystick_ = joystick;
  1106. state.joystickID_ = joystickID;
  1107. state.name_ = SDL_JoystickName(joystick);
  1108. if (SDL_IsGameController(index))
  1109. state.controller_ = SDL_GameControllerOpen(index);
  1110. auto numButtons = (unsigned)SDL_JoystickNumButtons(joystick);
  1111. auto numAxes = (unsigned)SDL_JoystickNumAxes(joystick);
  1112. auto numHats = (unsigned)SDL_JoystickNumHats(joystick);
  1113. // When the joystick is a controller, make sure there's enough axes & buttons for the standard controller mappings
  1114. if (state.controller_)
  1115. {
  1116. if (numButtons < SDL_CONTROLLER_BUTTON_MAX)
  1117. numButtons = SDL_CONTROLLER_BUTTON_MAX;
  1118. if (numAxes < SDL_CONTROLLER_AXIS_MAX)
  1119. numAxes = SDL_CONTROLLER_AXIS_MAX;
  1120. }
  1121. state.Initialize(numButtons, numAxes, numHats);
  1122. return joystickID;
  1123. }
  1124. Key Input::GetKeyFromName(const String& name) const
  1125. {
  1126. return (Key)SDL_GetKeyFromName(name.CString());
  1127. }
  1128. Key Input::GetKeyFromScancode(Scancode scancode) const
  1129. {
  1130. return (Key)SDL_GetKeyFromScancode((SDL_Scancode)scancode);
  1131. }
  1132. String Input::GetKeyName(Key key) const
  1133. {
  1134. return String(SDL_GetKeyName(key));
  1135. }
  1136. Scancode Input::GetScancodeFromKey(Key key) const
  1137. {
  1138. return (Scancode)SDL_GetScancodeFromKey(key);
  1139. }
  1140. Scancode Input::GetScancodeFromName(const String& name) const
  1141. {
  1142. return (Scancode)SDL_GetScancodeFromName(name.CString());
  1143. }
  1144. String Input::GetScancodeName(Scancode scancode) const
  1145. {
  1146. return SDL_GetScancodeName((SDL_Scancode)scancode);
  1147. }
  1148. bool Input::GetKeyDown(Key key) const
  1149. {
  1150. return keyDown_.Contains(SDL_tolower(key));
  1151. }
  1152. bool Input::GetKeyPress(Key key) const
  1153. {
  1154. return keyPress_.Contains(SDL_tolower(key));
  1155. }
  1156. bool Input::GetScancodeDown(Scancode scancode) const
  1157. {
  1158. return scancodeDown_.Contains(scancode);
  1159. }
  1160. bool Input::GetScancodePress(Scancode scancode) const
  1161. {
  1162. return scancodePress_.Contains(scancode);
  1163. }
  1164. bool Input::GetMouseButtonDown(MouseButtonFlags button) const
  1165. {
  1166. return mouseButtonDown_ & button;
  1167. }
  1168. bool Input::GetMouseButtonPress(MouseButtonFlags button) const
  1169. {
  1170. return mouseButtonPress_ & button;
  1171. }
  1172. bool Input::GetQualifierDown(Qualifier qualifier) const
  1173. {
  1174. if (qualifier == QUAL_SHIFT)
  1175. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  1176. if (qualifier == QUAL_CTRL)
  1177. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  1178. if (qualifier == QUAL_ALT)
  1179. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  1180. return false;
  1181. }
  1182. bool Input::GetQualifierPress(Qualifier qualifier) const
  1183. {
  1184. if (qualifier == QUAL_SHIFT)
  1185. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  1186. if (qualifier == QUAL_CTRL)
  1187. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  1188. if (qualifier == QUAL_ALT)
  1189. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  1190. return false;
  1191. }
  1192. QualifierFlags Input::GetQualifiers() const
  1193. {
  1194. QualifierFlags ret;
  1195. if (GetQualifierDown(QUAL_SHIFT))
  1196. ret |= QUAL_SHIFT;
  1197. if (GetQualifierDown(QUAL_CTRL))
  1198. ret |= QUAL_CTRL;
  1199. if (GetQualifierDown(QUAL_ALT))
  1200. ret |= QUAL_ALT;
  1201. return ret;
  1202. }
  1203. IntVector2 Input::GetMousePosition() const
  1204. {
  1205. IntVector2 ret = IntVector2::ZERO;
  1206. if (!initialized_)
  1207. return ret;
  1208. SDL_GetMouseState(&ret.x_, &ret.y_);
  1209. ret.x_ = (int)(ret.x_ * inputScale_.x_);
  1210. ret.y_ = (int)(ret.y_ * inputScale_.y_);
  1211. return ret;
  1212. }
  1213. IntVector2 Input::GetMouseMove() const
  1214. {
  1215. if (!suppressNextMouseMove_)
  1216. return mouseMoveScaled_ ? mouseMove_ : IntVector2((int)(mouseMove_.x_ * inputScale_.x_), (int)(mouseMove_.y_ * inputScale_.y_));
  1217. else
  1218. return IntVector2::ZERO;
  1219. }
  1220. int Input::GetMouseMoveX() const
  1221. {
  1222. if (!suppressNextMouseMove_)
  1223. return mouseMoveScaled_ ? mouseMove_.x_ : (int)(mouseMove_.x_ * inputScale_.x_);
  1224. else
  1225. return 0;
  1226. }
  1227. int Input::GetMouseMoveY() const
  1228. {
  1229. if (!suppressNextMouseMove_)
  1230. return mouseMoveScaled_ ? mouseMove_.y_ : mouseMove_.y_ * inputScale_.y_;
  1231. else
  1232. return 0;
  1233. }
  1234. TouchState* Input::GetTouch(unsigned index) const
  1235. {
  1236. if (index >= touches_.Size())
  1237. return nullptr;
  1238. HashMap<int, TouchState>::ConstIterator i = touches_.Begin();
  1239. while (index--)
  1240. ++i;
  1241. return const_cast<TouchState*>(&i->second_);
  1242. }
  1243. JoystickState* Input::GetJoystickByIndex(unsigned index)
  1244. {
  1245. unsigned compare = 0;
  1246. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1247. {
  1248. if (compare++ == index)
  1249. return &(i->second_);
  1250. }
  1251. return nullptr;
  1252. }
  1253. JoystickState* Input::GetJoystickByName(const String& name)
  1254. {
  1255. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1256. {
  1257. if (i->second_.name_ == name)
  1258. return &(i->second_);
  1259. }
  1260. return nullptr;
  1261. }
  1262. JoystickState* Input::GetJoystick(SDL_JoystickID id)
  1263. {
  1264. HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Find(id);
  1265. return i != joysticks_.End() ? &(i->second_) : nullptr;
  1266. }
  1267. bool Input::IsScreenJoystickVisible(SDL_JoystickID id) const
  1268. {
  1269. HashMap<SDL_JoystickID, JoystickState>::ConstIterator i = joysticks_.Find(id);
  1270. return i != joysticks_.End() && i->second_.screenJoystick_ && i->second_.screenJoystick_->IsVisible();
  1271. }
  1272. bool Input::GetScreenKeyboardSupport() const
  1273. {
  1274. return SDL_HasScreenKeyboardSupport();
  1275. }
  1276. bool Input::IsScreenKeyboardVisible() const
  1277. {
  1278. return SDL_IsTextInputActive();
  1279. }
  1280. bool Input::IsMouseLocked() const
  1281. {
  1282. #ifdef __EMSCRIPTEN__
  1283. return emscriptenPointerLock_;
  1284. #else
  1285. return !((mouseMode_ == MM_ABSOLUTE && mouseVisible_) || mouseMode_ == MM_FREE);
  1286. #endif
  1287. }
  1288. bool Input::IsMinimized() const
  1289. {
  1290. // Return minimized state also when unfocused in fullscreen
  1291. if (!inputFocus_ && graphics_ && graphics_->GetFullscreen())
  1292. return true;
  1293. else
  1294. return minimized_;
  1295. }
  1296. void Input::Initialize()
  1297. {
  1298. auto* graphics = GetSubsystem<Graphics>();
  1299. if (!graphics || !graphics->IsInitialized())
  1300. return;
  1301. graphics_ = graphics;
  1302. // In external window mode only visible mouse is supported
  1303. if (graphics_->GetExternalWindow())
  1304. mouseVisible_ = true;
  1305. // Set the initial activation
  1306. initialized_ = true;
  1307. #ifndef __EMSCRIPTEN__
  1308. GainFocus();
  1309. #else
  1310. // Note: Page visibility and focus are slightly different, however we can't query last focus with Emscripten (1.29.0)
  1311. if (emscriptenInput_->IsVisible())
  1312. GainFocus();
  1313. else
  1314. LoseFocus();
  1315. #endif
  1316. ResetJoysticks();
  1317. ResetState();
  1318. SubscribeToEvent(E_BEGINFRAME, URHO3D_HANDLER(Input, HandleBeginFrame));
  1319. #ifdef __EMSCRIPTEN__
  1320. SubscribeToEvent(E_ENDFRAME, URHO3D_HANDLER(Input, HandleEndFrame));
  1321. #endif
  1322. #ifdef _WIN32
  1323. // Register callback for resizing in order to repaint.
  1324. if (SDL_Window* window = graphics_->GetWindow())
  1325. {
  1326. SDL_SetWindowData(window, "URHO3D_CONTEXT", GetContext());
  1327. SDL_AddEventWatch(Win32_ResizingEventWatcher, window);
  1328. }
  1329. #endif
  1330. URHO3D_LOGINFO("Initialized input");
  1331. }
  1332. void Input::ResetJoysticks()
  1333. {
  1334. joysticks_.Clear();
  1335. // Open each detected joystick automatically on startup
  1336. auto size = static_cast<unsigned>(SDL_NumJoysticks());
  1337. for (unsigned i = 0; i < size; ++i)
  1338. OpenJoystick(i);
  1339. }
  1340. void Input::ResetInputAccumulation()
  1341. {
  1342. // Reset input accumulation for this frame
  1343. keyPress_.Clear();
  1344. scancodePress_.Clear();
  1345. mouseButtonPress_ = MOUSEB_NONE;
  1346. mouseMove_ = IntVector2::ZERO;
  1347. mouseMoveWheel_ = 0;
  1348. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1349. {
  1350. for (unsigned j = 0; j < i->second_.buttonPress_.Size(); ++j)
  1351. i->second_.buttonPress_[j] = false;
  1352. }
  1353. // Reset touch delta movement
  1354. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1355. {
  1356. TouchState& state = i->second_;
  1357. state.lastPosition_ = state.position_;
  1358. state.delta_ = IntVector2::ZERO;
  1359. }
  1360. }
  1361. void Input::GainFocus()
  1362. {
  1363. ResetState();
  1364. inputFocus_ = true;
  1365. focusedThisFrame_ = false;
  1366. // Restore mouse mode
  1367. #ifndef __EMSCRIPTEN__
  1368. const MouseMode mm = mouseMode_;
  1369. mouseMode_ = MM_FREE;
  1370. SetMouseMode(mm, true);
  1371. #endif
  1372. SuppressNextMouseMove();
  1373. // Re-establish mouse cursor hiding as necessary
  1374. if (!mouseVisible_)
  1375. SDL_ShowCursor(SDL_FALSE);
  1376. SendInputFocusEvent();
  1377. }
  1378. void Input::LoseFocus()
  1379. {
  1380. ResetState();
  1381. inputFocus_ = false;
  1382. focusedThisFrame_ = false;
  1383. // Show the mouse cursor when inactive
  1384. SDL_ShowCursor(SDL_TRUE);
  1385. // Change mouse mode -- removing any cursor grabs, etc.
  1386. #ifndef __EMSCRIPTEN__
  1387. const MouseMode mm = mouseMode_;
  1388. SetMouseMode(MM_FREE, true);
  1389. // Restore flags to reflect correct mouse state.
  1390. mouseMode_ = mm;
  1391. #endif
  1392. SendInputFocusEvent();
  1393. }
  1394. void Input::ResetState()
  1395. {
  1396. keyDown_.Clear();
  1397. keyPress_.Clear();
  1398. scancodeDown_.Clear();
  1399. scancodePress_.Clear();
  1400. /// \todo Check if resetting joystick state on input focus loss is even necessary
  1401. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  1402. i->second_.Reset();
  1403. ResetTouches();
  1404. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  1405. SetMouseButton(MOUSEB_LEFT, false, 0);
  1406. SetMouseButton(MOUSEB_RIGHT, false, 0);
  1407. SetMouseButton(MOUSEB_MIDDLE, false, 0);
  1408. mouseMove_ = IntVector2::ZERO;
  1409. mouseMoveWheel_ = 0;
  1410. mouseButtonPress_ = MOUSEB_NONE;
  1411. }
  1412. void Input::ResetTouches()
  1413. {
  1414. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  1415. {
  1416. TouchState& state = i->second_;
  1417. using namespace TouchEnd;
  1418. VariantMap& eventData = GetEventDataMap();
  1419. eventData[P_TOUCHID] = state.touchID_;
  1420. eventData[P_X] = state.position_.x_;
  1421. eventData[P_Y] = state.position_.y_;
  1422. SendEvent(E_TOUCHEND, eventData);
  1423. }
  1424. touches_.Clear();
  1425. touchIDMap_.Clear();
  1426. availableTouchIDs_.Clear();
  1427. for (int i = 0; i < TOUCHID_MAX; i++)
  1428. availableTouchIDs_.Push(i);
  1429. }
  1430. unsigned Input::GetTouchIndexFromID(int touchID)
  1431. {
  1432. HashMap<int, int>::ConstIterator i = touchIDMap_.Find(touchID);
  1433. if (i != touchIDMap_.End())
  1434. {
  1435. return (unsigned)i->second_;
  1436. }
  1437. unsigned index = PopTouchIndex();
  1438. touchIDMap_[touchID] = index;
  1439. return index;
  1440. }
  1441. unsigned Input::PopTouchIndex()
  1442. {
  1443. if (availableTouchIDs_.Empty())
  1444. return 0;
  1445. auto index = (unsigned)availableTouchIDs_.Front();
  1446. availableTouchIDs_.PopFront();
  1447. return index;
  1448. }
  1449. void Input::PushTouchIndex(int touchID)
  1450. {
  1451. HashMap<int, int>::ConstIterator ci = touchIDMap_.Find(touchID);
  1452. if (ci == touchIDMap_.End())
  1453. return;
  1454. int index = touchIDMap_[touchID];
  1455. touchIDMap_.Erase(touchID);
  1456. // Sorted insertion
  1457. bool inserted = false;
  1458. for (List<int>::Iterator i = availableTouchIDs_.Begin(); i != availableTouchIDs_.End(); ++i)
  1459. {
  1460. if (*i == index)
  1461. {
  1462. // This condition can occur when TOUCHID_MAX is reached.
  1463. inserted = true;
  1464. break;
  1465. }
  1466. if (*i > index)
  1467. {
  1468. availableTouchIDs_.Insert(i, index);
  1469. inserted = true;
  1470. break;
  1471. }
  1472. }
  1473. // If empty, or the lowest value then insert at end.
  1474. if (!inserted)
  1475. availableTouchIDs_.Push(index);
  1476. }
  1477. void Input::SendInputFocusEvent()
  1478. {
  1479. using namespace InputFocus;
  1480. VariantMap& eventData = GetEventDataMap();
  1481. eventData[P_FOCUS] = HasFocus();
  1482. eventData[P_MINIMIZED] = IsMinimized();
  1483. SendEvent(E_INPUTFOCUS, eventData);
  1484. }
  1485. void Input::SetMouseButton(MouseButton button, bool newState, int clicks)
  1486. {
  1487. if (newState)
  1488. {
  1489. if (!(mouseButtonDown_ & button))
  1490. mouseButtonPress_ |= button;
  1491. mouseButtonDown_ |= button;
  1492. }
  1493. else
  1494. {
  1495. if (!(mouseButtonDown_ & button))
  1496. return;
  1497. mouseButtonDown_ &= ~button;
  1498. }
  1499. using namespace MouseButtonDown;
  1500. VariantMap& eventData = GetEventDataMap();
  1501. eventData[P_BUTTON] = button;
  1502. eventData[P_BUTTONS] = (unsigned)mouseButtonDown_;
  1503. eventData[P_QUALIFIERS] = (unsigned)GetQualifiers();
  1504. eventData[P_CLICKS] = clicks;
  1505. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  1506. }
  1507. void Input::SetKey(Key key, Scancode scancode, bool newState)
  1508. {
  1509. bool repeat = false;
  1510. if (newState)
  1511. {
  1512. scancodeDown_.Insert(scancode);
  1513. scancodePress_.Insert(scancode);
  1514. if (!keyDown_.Contains(key))
  1515. {
  1516. keyDown_.Insert(key);
  1517. keyPress_.Insert(key);
  1518. }
  1519. else
  1520. repeat = true;
  1521. }
  1522. else
  1523. {
  1524. scancodeDown_.Erase(scancode);
  1525. if (!keyDown_.Erase(key))
  1526. return;
  1527. }
  1528. using namespace KeyDown;
  1529. VariantMap& eventData = GetEventDataMap();
  1530. eventData[P_KEY] = key;
  1531. eventData[P_SCANCODE] = scancode;
  1532. eventData[P_BUTTONS] = (unsigned)mouseButtonDown_;
  1533. eventData[P_QUALIFIERS] = (unsigned)GetQualifiers();
  1534. if (newState)
  1535. eventData[P_REPEAT] = repeat;
  1536. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  1537. if ((key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER) && newState && !repeat && toggleFullscreen_ &&
  1538. (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  1539. graphics_->ToggleFullscreen();
  1540. }
  1541. void Input::SetMouseWheel(int delta)
  1542. {
  1543. if (delta)
  1544. {
  1545. mouseMoveWheel_ += delta;
  1546. using namespace MouseWheel;
  1547. VariantMap& eventData = GetEventDataMap();
  1548. eventData[P_WHEEL] = delta;
  1549. eventData[P_BUTTONS] = (unsigned)mouseButtonDown_;
  1550. eventData[P_QUALIFIERS] = (unsigned)GetQualifiers();
  1551. SendEvent(E_MOUSEWHEEL, eventData);
  1552. }
  1553. }
  1554. void Input::SetMousePosition(const IntVector2& position)
  1555. {
  1556. if (!graphics_)
  1557. return;
  1558. SDL_WarpMouseInWindow(graphics_->GetWindow(), (int)(position.x_ / inputScale_.x_), (int)(position.y_ / inputScale_.y_));
  1559. }
  1560. void Input::CenterMousePosition()
  1561. {
  1562. const IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  1563. if (GetMousePosition() != center)
  1564. {
  1565. SetMousePosition(center);
  1566. lastMousePosition_ = center;
  1567. }
  1568. }
  1569. void Input::SuppressNextMouseMove()
  1570. {
  1571. suppressNextMouseMove_ = true;
  1572. mouseMove_ = IntVector2::ZERO;
  1573. }
  1574. void Input::UnsuppressMouseMove()
  1575. {
  1576. suppressNextMouseMove_ = false;
  1577. mouseMove_ = IntVector2::ZERO;
  1578. lastMousePosition_ = GetMousePosition();
  1579. }
  1580. void Input::HandleSDLEvent(void* sdlEvent)
  1581. {
  1582. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  1583. // While not having input focus, skip key/mouse/touch/joystick events, except for the "click to focus" mechanism
  1584. if (!inputFocus_ && evt.type >= SDL_KEYDOWN && evt.type <= SDL_MULTIGESTURE)
  1585. {
  1586. #ifdef REQUIRE_CLICK_TO_FOCUS
  1587. // Require the click to be at least 1 pixel inside the window to disregard clicks in the title bar
  1588. if (evt.type == SDL_MOUSEBUTTONDOWN && evt.button.x > 0 && evt.button.y > 0 && evt.button.x < graphics_->GetWidth() - 1 &&
  1589. evt.button.y < graphics_->GetHeight() - 1)
  1590. {
  1591. focusedThisFrame_ = true;
  1592. // Do not cause the click to actually go throughfin
  1593. return;
  1594. }
  1595. else if (evt.type == SDL_FINGERDOWN)
  1596. {
  1597. // When focusing by touch, call GainFocus() immediately as it resets the state; a touch has sustained state
  1598. // which should be kept
  1599. GainFocus();
  1600. }
  1601. else
  1602. #endif
  1603. return;
  1604. }
  1605. // Possibility for custom handling or suppression of default handling for the SDL event
  1606. {
  1607. using namespace SDLRawInput;
  1608. VariantMap eventData = GetEventDataMap();
  1609. eventData[P_SDLEVENT] = &evt;
  1610. eventData[P_CONSUMED] = false;
  1611. SendEvent(E_SDLRAWINPUT, eventData);
  1612. if (eventData[P_CONSUMED].GetBool())
  1613. return;
  1614. }
  1615. switch (evt.type)
  1616. {
  1617. case SDL_KEYDOWN:
  1618. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), (Scancode)evt.key.keysym.scancode, true);
  1619. break;
  1620. case SDL_KEYUP:
  1621. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), (Scancode)evt.key.keysym.scancode, false);
  1622. break;
  1623. case SDL_TEXTINPUT:
  1624. {
  1625. using namespace TextInput;
  1626. VariantMap textInputEventData;
  1627. textInputEventData[P_TEXT] = textInput_ = &evt.text.text[0];
  1628. SendEvent(E_TEXTINPUT, textInputEventData);
  1629. }
  1630. break;
  1631. case SDL_TEXTEDITING:
  1632. {
  1633. using namespace TextEditing;
  1634. VariantMap textEditingEventData;
  1635. textEditingEventData[P_COMPOSITION] = &evt.edit.text[0];
  1636. textEditingEventData[P_CURSOR] = evt.edit.start;
  1637. textEditingEventData[P_SELECTION_LENGTH] = evt.edit.length;
  1638. SendEvent(E_TEXTEDITING, textEditingEventData);
  1639. }
  1640. break;
  1641. case SDL_MOUSEBUTTONDOWN:
  1642. if (!touchEmulation_)
  1643. {
  1644. const auto mouseButton = static_cast<MouseButton>(1u << (evt.button.button - 1u)); // NOLINT(misc-misplaced-widening-cast)
  1645. SetMouseButton(mouseButton, true, evt.button.clicks);
  1646. }
  1647. else
  1648. {
  1649. int x, y;
  1650. SDL_GetMouseState(&x, &y);
  1651. x = (int)(x * inputScale_.x_);
  1652. y = (int)(y * inputScale_.y_);
  1653. SDL_Event event;
  1654. event.type = SDL_FINGERDOWN;
  1655. event.tfinger.touchId = 0;
  1656. event.tfinger.fingerId = evt.button.button - 1;
  1657. event.tfinger.pressure = 1.0f;
  1658. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1659. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1660. event.tfinger.dx = 0;
  1661. event.tfinger.dy = 0;
  1662. SDL_PushEvent(&event);
  1663. }
  1664. break;
  1665. case SDL_MOUSEBUTTONUP:
  1666. if (!touchEmulation_)
  1667. {
  1668. const auto mouseButton = static_cast<MouseButton>(1u << (evt.button.button - 1u)); // NOLINT(misc-misplaced-widening-cast)
  1669. SetMouseButton(mouseButton, false, evt.button.clicks);
  1670. }
  1671. else
  1672. {
  1673. int x, y;
  1674. SDL_GetMouseState(&x, &y);
  1675. x = (int)(x * inputScale_.x_);
  1676. y = (int)(y * inputScale_.y_);
  1677. SDL_Event event;
  1678. event.type = SDL_FINGERUP;
  1679. event.tfinger.touchId = 0;
  1680. event.tfinger.fingerId = evt.button.button - 1;
  1681. event.tfinger.pressure = 0.0f;
  1682. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1683. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1684. event.tfinger.dx = 0;
  1685. event.tfinger.dy = 0;
  1686. SDL_PushEvent(&event);
  1687. }
  1688. break;
  1689. case SDL_MOUSEMOTION:
  1690. #ifndef __EMSCRIPTEN__
  1691. if ((sdlMouseRelative_ || mouseVisible_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1692. #else
  1693. if ((mouseVisible_ || emscriptenPointerLock_ || mouseMode_ == MM_FREE) && !touchEmulation_)
  1694. #endif
  1695. {
  1696. #ifdef __EMSCRIPTEN__
  1697. if (emscriptenExitingPointerLock_)
  1698. {
  1699. SuppressNextMouseMove();
  1700. break;
  1701. }
  1702. #endif
  1703. // Accumulate without scaling for accuracy, needs to be scaled to backbuffer coordinates when asked
  1704. mouseMove_.x_ += evt.motion.xrel;
  1705. mouseMove_.y_ += evt.motion.yrel;
  1706. mouseMoveScaled_ = false;
  1707. if (!suppressNextMouseMove_)
  1708. {
  1709. using namespace MouseMove;
  1710. VariantMap& eventData = GetEventDataMap();
  1711. eventData[P_X] = (int)(evt.motion.x * inputScale_.x_);
  1712. eventData[P_Y] = (int)(evt.motion.y * inputScale_.y_);
  1713. // The "on-the-fly" motion data needs to be scaled now, though this may reduce accuracy
  1714. eventData[P_DX] = (int)(evt.motion.xrel * inputScale_.x_);
  1715. eventData[P_DY] = (int)(evt.motion.yrel * inputScale_.y_);
  1716. eventData[P_BUTTONS] = (unsigned)mouseButtonDown_;
  1717. eventData[P_QUALIFIERS] = (unsigned)GetQualifiers();
  1718. SendEvent(E_MOUSEMOVE, eventData);
  1719. }
  1720. }
  1721. // Only the left mouse button "finger" moves along with the mouse movement
  1722. else if (touchEmulation_ && touches_.Contains(0))
  1723. {
  1724. int x, y;
  1725. SDL_GetMouseState(&x, &y);
  1726. x = (int)(x * inputScale_.x_);
  1727. y = (int)(y * inputScale_.y_);
  1728. SDL_Event event;
  1729. event.type = SDL_FINGERMOTION;
  1730. event.tfinger.touchId = 0;
  1731. event.tfinger.fingerId = 0;
  1732. event.tfinger.pressure = 1.0f;
  1733. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  1734. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  1735. event.tfinger.dx = (float)evt.motion.xrel * inputScale_.x_ / (float)graphics_->GetWidth();
  1736. event.tfinger.dy = (float)evt.motion.yrel * inputScale_.y_ / (float)graphics_->GetHeight();
  1737. SDL_PushEvent(&event);
  1738. }
  1739. break;
  1740. case SDL_MOUSEWHEEL:
  1741. if (!touchEmulation_)
  1742. SetMouseWheel(evt.wheel.y);
  1743. break;
  1744. case SDL_FINGERDOWN:
  1745. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1746. {
  1747. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffffu);
  1748. TouchState& state = touches_[touchID];
  1749. state.touchID_ = touchID;
  1750. state.lastPosition_ = state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1751. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1752. state.delta_ = IntVector2::ZERO;
  1753. state.pressure_ = evt.tfinger.pressure;
  1754. using namespace TouchBegin;
  1755. VariantMap& eventData = GetEventDataMap();
  1756. eventData[P_TOUCHID] = touchID;
  1757. eventData[P_X] = state.position_.x_;
  1758. eventData[P_Y] = state.position_.y_;
  1759. eventData[P_PRESSURE] = state.pressure_;
  1760. SendEvent(E_TOUCHBEGIN, eventData);
  1761. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1762. if (!mouseVisible_)
  1763. SuppressNextMouseMove();
  1764. }
  1765. break;
  1766. case SDL_FINGERUP:
  1767. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1768. {
  1769. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffffu);
  1770. TouchState& state = touches_[touchID];
  1771. using namespace TouchEnd;
  1772. VariantMap& eventData = GetEventDataMap();
  1773. // Do not trust the position in the finger up event. Instead use the last position stored in the
  1774. // touch structure
  1775. eventData[P_TOUCHID] = touchID;
  1776. eventData[P_X] = state.position_.x_;
  1777. eventData[P_Y] = state.position_.y_;
  1778. SendEvent(E_TOUCHEND, eventData);
  1779. // Add touch index back to list of available touch Ids
  1780. PushTouchIndex(evt.tfinger.fingerId & 0x7ffffffu);
  1781. touches_.Erase(touchID);
  1782. }
  1783. break;
  1784. case SDL_FINGERMOTION:
  1785. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1786. {
  1787. int touchID = GetTouchIndexFromID(evt.tfinger.fingerId & 0x7ffffffu);
  1788. // We don't want this event to create a new touches_ event if it doesn't exist (touchEmulation)
  1789. if (touchEmulation_ && !touches_.Contains(touchID))
  1790. break;
  1791. TouchState& state = touches_[touchID];
  1792. state.touchID_ = touchID;
  1793. state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1794. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1795. state.delta_ = state.position_ - state.lastPosition_;
  1796. state.pressure_ = evt.tfinger.pressure;
  1797. using namespace TouchMove;
  1798. VariantMap& eventData = GetEventDataMap();
  1799. eventData[P_TOUCHID] = touchID;
  1800. eventData[P_X] = state.position_.x_;
  1801. eventData[P_Y] = state.position_.y_;
  1802. eventData[P_DX] = (int)(evt.tfinger.dx * graphics_->GetWidth());
  1803. eventData[P_DY] = (int)(evt.tfinger.dy * graphics_->GetHeight());
  1804. eventData[P_PRESSURE] = state.pressure_;
  1805. SendEvent(E_TOUCHMOVE, eventData);
  1806. // Finger touch may move the mouse cursor. Suppress next mouse move when cursor hidden to prevent jumps
  1807. if (!mouseVisible_)
  1808. SuppressNextMouseMove();
  1809. }
  1810. break;
  1811. case SDL_DOLLARRECORD:
  1812. {
  1813. using namespace GestureRecorded;
  1814. VariantMap& eventData = GetEventDataMap();
  1815. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1816. SendEvent(E_GESTURERECORDED, eventData);
  1817. }
  1818. break;
  1819. case SDL_DOLLARGESTURE:
  1820. {
  1821. using namespace GestureInput;
  1822. VariantMap& eventData = GetEventDataMap();
  1823. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1824. eventData[P_CENTERX] = (int)(evt.dgesture.x * graphics_->GetWidth());
  1825. eventData[P_CENTERY] = (int)(evt.dgesture.y * graphics_->GetHeight());
  1826. eventData[P_NUMFINGERS] = (int)evt.dgesture.numFingers;
  1827. eventData[P_ERROR] = evt.dgesture.error;
  1828. SendEvent(E_GESTUREINPUT, eventData);
  1829. }
  1830. break;
  1831. case SDL_MULTIGESTURE:
  1832. {
  1833. using namespace MultiGesture;
  1834. VariantMap& eventData = GetEventDataMap();
  1835. eventData[P_CENTERX] = (int)(evt.mgesture.x * graphics_->GetWidth());
  1836. eventData[P_CENTERY] = (int)(evt.mgesture.y * graphics_->GetHeight());
  1837. eventData[P_NUMFINGERS] = (int)evt.mgesture.numFingers;
  1838. eventData[P_DTHETA] = M_RADTODEG * evt.mgesture.dTheta;
  1839. eventData[P_DDIST] = evt.mgesture.dDist;
  1840. SendEvent(E_MULTIGESTURE, eventData);
  1841. }
  1842. break;
  1843. case SDL_JOYDEVICEADDED:
  1844. {
  1845. using namespace JoystickConnected;
  1846. SDL_JoystickID joystickID = OpenJoystick((unsigned)evt.jdevice.which);
  1847. VariantMap& eventData = GetEventDataMap();
  1848. eventData[P_JOYSTICKID] = joystickID;
  1849. SendEvent(E_JOYSTICKCONNECTED, eventData);
  1850. }
  1851. break;
  1852. case SDL_JOYDEVICEREMOVED:
  1853. {
  1854. using namespace JoystickDisconnected;
  1855. joysticks_.Erase(evt.jdevice.which);
  1856. VariantMap& eventData = GetEventDataMap();
  1857. eventData[P_JOYSTICKID] = evt.jdevice.which;
  1858. SendEvent(E_JOYSTICKDISCONNECTED, eventData);
  1859. }
  1860. break;
  1861. case SDL_JOYBUTTONDOWN:
  1862. {
  1863. using namespace JoystickButtonDown;
  1864. unsigned button = evt.jbutton.button;
  1865. SDL_JoystickID joystickID = evt.jbutton.which;
  1866. JoystickState& state = joysticks_[joystickID];
  1867. // Skip ordinary joystick event for a controller
  1868. if (!state.controller_)
  1869. {
  1870. VariantMap& eventData = GetEventDataMap();
  1871. eventData[P_JOYSTICKID] = joystickID;
  1872. eventData[P_BUTTON] = button;
  1873. if (button < state.buttons_.Size())
  1874. {
  1875. state.buttons_[button] = true;
  1876. state.buttonPress_[button] = true;
  1877. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1878. }
  1879. }
  1880. }
  1881. break;
  1882. case SDL_JOYBUTTONUP:
  1883. {
  1884. using namespace JoystickButtonUp;
  1885. unsigned button = evt.jbutton.button;
  1886. SDL_JoystickID joystickID = evt.jbutton.which;
  1887. JoystickState& state = joysticks_[joystickID];
  1888. if (!state.controller_)
  1889. {
  1890. VariantMap& eventData = GetEventDataMap();
  1891. eventData[P_JOYSTICKID] = joystickID;
  1892. eventData[P_BUTTON] = button;
  1893. if (button < state.buttons_.Size())
  1894. {
  1895. if (!state.controller_)
  1896. state.buttons_[button] = false;
  1897. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1898. }
  1899. }
  1900. }
  1901. break;
  1902. case SDL_JOYAXISMOTION:
  1903. {
  1904. using namespace JoystickAxisMove;
  1905. SDL_JoystickID joystickID = evt.jaxis.which;
  1906. JoystickState& state = joysticks_[joystickID];
  1907. if (!state.controller_)
  1908. {
  1909. VariantMap& eventData = GetEventDataMap();
  1910. eventData[P_JOYSTICKID] = joystickID;
  1911. eventData[P_AXIS] = evt.jaxis.axis;
  1912. eventData[P_POSITION] = Clamp((float)evt.jaxis.value / 32767.0f, -1.0f, 1.0f);
  1913. if (evt.jaxis.axis < state.axes_.Size())
  1914. {
  1915. // If the joystick is a controller, only use the controller axis mappings
  1916. // (we'll also get the controller event)
  1917. if (!state.controller_)
  1918. state.axes_[evt.jaxis.axis] = eventData[P_POSITION].GetFloat();
  1919. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1920. }
  1921. }
  1922. }
  1923. break;
  1924. case SDL_JOYHATMOTION:
  1925. {
  1926. using namespace JoystickHatMove;
  1927. SDL_JoystickID joystickID = evt.jaxis.which;
  1928. JoystickState& state = joysticks_[joystickID];
  1929. VariantMap& eventData = GetEventDataMap();
  1930. eventData[P_JOYSTICKID] = joystickID;
  1931. eventData[P_HAT] = evt.jhat.hat;
  1932. eventData[P_POSITION] = evt.jhat.value;
  1933. if (evt.jhat.hat < state.hats_.Size())
  1934. {
  1935. state.hats_[evt.jhat.hat] = evt.jhat.value;
  1936. SendEvent(E_JOYSTICKHATMOVE, eventData);
  1937. }
  1938. }
  1939. break;
  1940. case SDL_CONTROLLERBUTTONDOWN:
  1941. {
  1942. using namespace JoystickButtonDown;
  1943. unsigned button = evt.cbutton.button;
  1944. SDL_JoystickID joystickID = evt.cbutton.which;
  1945. JoystickState& state = joysticks_[joystickID];
  1946. VariantMap& eventData = GetEventDataMap();
  1947. eventData[P_JOYSTICKID] = joystickID;
  1948. eventData[P_BUTTON] = button;
  1949. if (button < state.buttons_.Size())
  1950. {
  1951. state.buttons_[button] = true;
  1952. state.buttonPress_[button] = true;
  1953. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1954. }
  1955. }
  1956. break;
  1957. case SDL_CONTROLLERBUTTONUP:
  1958. {
  1959. using namespace JoystickButtonUp;
  1960. unsigned button = evt.cbutton.button;
  1961. SDL_JoystickID joystickID = evt.cbutton.which;
  1962. JoystickState& state = joysticks_[joystickID];
  1963. VariantMap& eventData = GetEventDataMap();
  1964. eventData[P_JOYSTICKID] = joystickID;
  1965. eventData[P_BUTTON] = button;
  1966. if (button < state.buttons_.Size())
  1967. {
  1968. state.buttons_[button] = false;
  1969. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1970. }
  1971. }
  1972. break;
  1973. case SDL_CONTROLLERAXISMOTION:
  1974. {
  1975. using namespace JoystickAxisMove;
  1976. SDL_JoystickID joystickID = evt.caxis.which;
  1977. JoystickState& state = joysticks_[joystickID];
  1978. VariantMap& eventData = GetEventDataMap();
  1979. eventData[P_JOYSTICKID] = joystickID;
  1980. eventData[P_AXIS] = evt.caxis.axis;
  1981. eventData[P_POSITION] = Clamp((float)evt.caxis.value / 32767.0f, -1.0f, 1.0f);
  1982. if (evt.caxis.axis < state.axes_.Size())
  1983. {
  1984. state.axes_[evt.caxis.axis] = eventData[P_POSITION].GetFloat();
  1985. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1986. }
  1987. }
  1988. break;
  1989. case SDL_WINDOWEVENT:
  1990. {
  1991. switch (evt.window.event)
  1992. {
  1993. case SDL_WINDOWEVENT_MINIMIZED:
  1994. minimized_ = true;
  1995. SendInputFocusEvent();
  1996. break;
  1997. case SDL_WINDOWEVENT_MAXIMIZED:
  1998. case SDL_WINDOWEVENT_RESTORED:
  1999. #if defined(IOS) || defined(TVOS) || defined (__ANDROID__)
  2000. // On iOS/tvOS we never lose the GL context, but may have done GPU object changes that could not be applied yet. Apply them now
  2001. // On Android the old GL context may be lost already, restore GPU objects to the new GL context
  2002. graphics_->Restore();
  2003. #endif
  2004. minimized_ = false;
  2005. SendInputFocusEvent();
  2006. break;
  2007. case SDL_WINDOWEVENT_RESIZED:
  2008. graphics_->OnWindowResized();
  2009. break;
  2010. case SDL_WINDOWEVENT_MOVED:
  2011. graphics_->OnWindowMoved();
  2012. break;
  2013. default: break;
  2014. }
  2015. }
  2016. break;
  2017. case SDL_DROPFILE:
  2018. {
  2019. using namespace DropFile;
  2020. VariantMap& eventData = GetEventDataMap();
  2021. eventData[P_FILENAME] = GetInternalPath(String(evt.drop.file));
  2022. SDL_free(evt.drop.file);
  2023. SendEvent(E_DROPFILE, eventData);
  2024. }
  2025. break;
  2026. case SDL_QUIT:
  2027. SendEvent(E_EXITREQUESTED);
  2028. break;
  2029. default: break;
  2030. }
  2031. }
  2032. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  2033. {
  2034. if (!initialized_)
  2035. Initialize();
  2036. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  2037. // mouse move event. Also get new window ID if it changed
  2038. SDL_Window* window = graphics_->GetWindow();
  2039. windowID_ = SDL_GetWindowID(window);
  2040. // Resize screen joysticks to new screen size
  2041. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  2042. {
  2043. UIElement* screenjoystick = i->second_.screenJoystick_;
  2044. if (screenjoystick)
  2045. screenjoystick->SetSize(graphics_->GetWidth(), graphics_->GetHeight());
  2046. }
  2047. if (graphics_->GetFullscreen() || !mouseVisible_)
  2048. focusedThisFrame_ = true;
  2049. // After setting a new screen mode we should not be minimized
  2050. minimized_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0;
  2051. // Calculate input coordinate scaling from SDL window to backbuffer ratio
  2052. int winWidth, winHeight;
  2053. int gfxWidth = graphics_->GetWidth();
  2054. int gfxHeight = graphics_->GetHeight();
  2055. SDL_GetWindowSize(window, &winWidth, &winHeight);
  2056. if (winWidth > 0 && winHeight > 0 && gfxWidth > 0 && gfxHeight > 0)
  2057. {
  2058. inputScale_.x_ = (float)gfxWidth / (float)winWidth;
  2059. inputScale_.y_ = (float)gfxHeight / (float)winHeight;
  2060. }
  2061. else
  2062. inputScale_ = Vector2::ONE;
  2063. }
  2064. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  2065. {
  2066. // Update input right at the beginning of the frame
  2067. SendEvent(E_INPUTBEGIN);
  2068. Update();
  2069. SendEvent(E_INPUTEND);
  2070. }
  2071. #ifdef __EMSCRIPTEN__
  2072. void Input::HandleEndFrame(StringHash eventType, VariantMap& eventData)
  2073. {
  2074. if (suppressNextMouseMove_ && mouseMove_ != IntVector2::ZERO)
  2075. UnsuppressMouseMove();
  2076. ResetInputAccumulation();
  2077. }
  2078. #endif
  2079. void Input::HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData)
  2080. {
  2081. using namespace TouchBegin;
  2082. // Only interested in events from screen joystick(s)
  2083. TouchState& state = touches_[eventData[P_TOUCHID].GetInt()];
  2084. IntVector2 position(int(state.position_.x_ / GetSubsystem<UI>()->GetScale()), int(state.position_.y_ / GetSubsystem<UI>()->GetScale()));
  2085. UIElement* element = eventType == E_TOUCHBEGIN ? GetSubsystem<UI>()->GetElementAt(position) : state.touchedElement_;
  2086. if (!element)
  2087. return;
  2088. Variant variant = element->GetVar(VAR_SCREEN_JOYSTICK_ID);
  2089. if (variant.IsEmpty())
  2090. return;
  2091. SDL_JoystickID joystickID = variant.GetInt();
  2092. if (eventType == E_TOUCHEND)
  2093. state.touchedElement_.Reset();
  2094. else
  2095. state.touchedElement_ = element;
  2096. // Prepare a fake SDL event
  2097. SDL_Event evt;
  2098. const String& name = element->GetName();
  2099. if (name.StartsWith("Button"))
  2100. {
  2101. if (eventType == E_TOUCHMOVE)
  2102. return;
  2103. // Determine whether to inject a joystick event or keyboard/mouse event
  2104. const Variant& keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2105. const Variant& mouseButtonBindingVar = element->GetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING);
  2106. if (keyBindingVar.IsEmpty() && mouseButtonBindingVar.IsEmpty())
  2107. {
  2108. evt.type = eventType == E_TOUCHBEGIN ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
  2109. evt.jbutton.which = joystickID;
  2110. evt.jbutton.button = (Uint8)ToUInt(name.Substring(6));
  2111. }
  2112. else
  2113. {
  2114. if (!keyBindingVar.IsEmpty())
  2115. {
  2116. evt.type = eventType == E_TOUCHBEGIN ? SDL_KEYDOWN : SDL_KEYUP;
  2117. evt.key.keysym.sym = ToLower(keyBindingVar.GetInt());
  2118. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2119. }
  2120. if (!mouseButtonBindingVar.IsEmpty())
  2121. {
  2122. // Mouse button are sent as extra events besides key events
  2123. // Disable touch emulation handling during this to prevent endless loop
  2124. bool oldTouchEmulation = touchEmulation_;
  2125. touchEmulation_ = false;
  2126. SDL_Event mouseEvent;
  2127. mouseEvent.type = eventType == E_TOUCHBEGIN ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP;
  2128. mouseEvent.button.button = (Uint8)mouseButtonBindingVar.GetInt();
  2129. HandleSDLEvent(&mouseEvent);
  2130. touchEmulation_ = oldTouchEmulation;
  2131. }
  2132. }
  2133. }
  2134. else if (name.StartsWith("Hat"))
  2135. {
  2136. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  2137. if (keyBindingVar.IsEmpty())
  2138. {
  2139. evt.type = SDL_JOYHATMOTION;
  2140. evt.jaxis.which = joystickID;
  2141. evt.jhat.hat = (Uint8)ToUInt(name.Substring(3));
  2142. evt.jhat.value = HAT_CENTER;
  2143. if (eventType != E_TOUCHEND)
  2144. {
  2145. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2146. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2147. evt.jhat.value |= HAT_UP;
  2148. if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2149. evt.jhat.value |= HAT_DOWN;
  2150. if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2151. evt.jhat.value |= HAT_LEFT;
  2152. if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2153. evt.jhat.value |= HAT_RIGHT;
  2154. }
  2155. }
  2156. else
  2157. {
  2158. // Hat is binded by 4 integers representing keysyms for 'w', 's', 'a', 'd' or something similar
  2159. IntRect keyBinding = keyBindingVar.GetIntRect();
  2160. if (eventType == E_TOUCHEND)
  2161. {
  2162. evt.type = SDL_KEYUP;
  2163. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2164. if (!evt.key.keysym.sym)
  2165. return;
  2166. element->SetVar(VAR_LAST_KEYSYM, 0);
  2167. }
  2168. else
  2169. {
  2170. evt.type = SDL_KEYDOWN;
  2171. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  2172. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2173. evt.key.keysym.sym = keyBinding.left_; // The integers are encoded in WSAD order to l-t-r-b
  2174. else if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  2175. evt.key.keysym.sym = keyBinding.top_;
  2176. else if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2177. evt.key.keysym.sym = keyBinding.right_;
  2178. else if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  2179. evt.key.keysym.sym = keyBinding.bottom_;
  2180. else
  2181. return;
  2182. if (eventType == E_TOUCHMOVE && evt.key.keysym.sym != element->GetVar(VAR_LAST_KEYSYM).GetInt())
  2183. {
  2184. // Dragging past the directional boundary will cause an additional key up event for previous key symbol
  2185. SDL_Event keyEvent;
  2186. keyEvent.type = SDL_KEYUP;
  2187. keyEvent.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  2188. if (keyEvent.key.keysym.sym)
  2189. {
  2190. keyEvent.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2191. HandleSDLEvent(&keyEvent);
  2192. }
  2193. element->SetVar(VAR_LAST_KEYSYM, 0);
  2194. }
  2195. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  2196. element->SetVar(VAR_LAST_KEYSYM, evt.key.keysym.sym);
  2197. }
  2198. }
  2199. }
  2200. else
  2201. return;
  2202. // Handle the fake SDL event to turn it into Urho3D genuine event
  2203. HandleSDLEvent(&evt);
  2204. }
  2205. }