Input.cpp 69 KB

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