Input.cpp 69 KB

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