Input.cpp 84 KB

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