2
0

Input.cpp 71 KB

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