Input.cpp 69 KB

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