Input.cpp 71 KB

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