Input.cpp 69 KB

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