2
0

Input.cpp 86 KB

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