Input.cpp 83 KB

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