Input.cpp 81 KB

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