Input.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "CoreEvents.h"
  25. #include "FileSystem.h"
  26. #include "Graphics.h"
  27. #include "GraphicsEvents.h"
  28. #include "GraphicsImpl.h"
  29. #include "Input.h"
  30. #include "Log.h"
  31. #include "Mutex.h"
  32. #include "ProcessUtils.h"
  33. #include "Profiler.h"
  34. #include "ResourceCache.h"
  35. #include "RWOpsWrapper.h"
  36. #include "StringUtils.h"
  37. #include "Text.h"
  38. #include "UI.h"
  39. #include <cstring>
  40. #include <SDL.h>
  41. #include "DebugNew.h"
  42. extern "C" int SDL_AddTouch(SDL_TouchID touchID, const char *name);
  43. // Require a click inside window before re-hiding mouse cursor on OSX, otherwise dragging the window
  44. // can be incorrectly interpreted as mouse movement inside the window
  45. #if defined(__APPLE__) && !defined(IOS)
  46. #define REQUIRE_CLICK_TO_FOCUS
  47. #endif
  48. namespace Urho3D
  49. {
  50. const int SCREEN_JOYSTICK_START_ID = 0x40000000;
  51. const ShortStringHash VAR_BUTTON_KEY_BINDING("VAR_BUTTON_KEY_BINDING");
  52. const ShortStringHash VAR_BUTTON_MOUSE_BUTTON_BINDING("VAR_BUTTON_MOUSE_BUTTON_BINDING");
  53. const ShortStringHash VAR_LAST_KEYSYM("VAR_LAST_KEYSYM");
  54. const ShortStringHash VAR_SCREEN_JOYSTICK_ID("VAR_SCREEN_JOYSTICK_ID");
  55. /// Convert SDL keycode if necessary.
  56. int ConvertSDLKeyCode(int keySym, int scanCode)
  57. {
  58. if (scanCode == SCANCODE_AC_BACK)
  59. return KEY_ESC;
  60. else
  61. return SDL_toupper(keySym);
  62. }
  63. void JoystickState::Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats)
  64. {
  65. buttons_.Resize(numButtons);
  66. buttonPress_.Resize(numButtons);
  67. axes_.Resize(numAxes);
  68. hats_.Resize(numHats);
  69. Reset();
  70. }
  71. void JoystickState::Reset()
  72. {
  73. for (unsigned i = 0; i < buttons_.Size(); ++i)
  74. {
  75. buttons_[i] = false;
  76. buttonPress_[i] = false;
  77. }
  78. for (unsigned i = 0; i < axes_.Size(); ++i)
  79. axes_[i] = 0.0f;
  80. for (unsigned i = 0; i < hats_.Size(); ++i)
  81. hats_[i] = HAT_CENTER;
  82. }
  83. Input::Input(Context* context) :
  84. Object(context),
  85. mouseButtonDown_(0),
  86. mouseButtonPress_(0),
  87. mouseMoveWheel_(0),
  88. windowID_(0),
  89. toggleFullscreen_(true),
  90. mouseVisible_(false),
  91. mouseGrabbed_(false),
  92. touchEmulation_(false),
  93. inputFocus_(false),
  94. minimized_(false),
  95. focusedThisFrame_(false),
  96. suppressNextMouseMove_(false),
  97. initialized_(false)
  98. {
  99. SubscribeToEvent(E_SCREENMODE, HANDLER(Input, HandleScreenMode));
  100. // Try to initialize right now, but skip if screen mode is not yet set
  101. Initialize();
  102. }
  103. Input::~Input()
  104. {
  105. }
  106. void Input::Update()
  107. {
  108. assert(initialized_);
  109. PROFILE(UpdateInput);
  110. // Reset input accumulation for this frame
  111. keyPress_.Clear();
  112. scancodePress_.Clear();
  113. mouseButtonPress_ = 0;
  114. mouseMove_ = IntVector2::ZERO;
  115. mouseMoveWheel_ = 0;
  116. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  117. {
  118. for (unsigned j = 0; j < i->second_.buttonPress_.Size(); ++j)
  119. i->second_.buttonPress_[j] = false;
  120. }
  121. // Reset touch delta movement
  122. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  123. {
  124. TouchState& state = i->second_;
  125. state.lastPosition_ = state.position_;
  126. state.delta_ = IntVector2::ZERO;
  127. }
  128. // Check and handle SDL events
  129. SDL_PumpEvents();
  130. SDL_Event evt;
  131. while (SDL_PeepEvents(&evt, 1, SDL_GETEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) > 0)
  132. HandleSDLEvent(&evt);
  133. // Check for activation and inactivation from SDL window flags. Must nullcheck the window pointer because it may have
  134. // been closed due to input events
  135. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  136. unsigned flags = window ? SDL_GetWindowFlags(window) & (SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS) : 0;
  137. if (window)
  138. {
  139. #ifdef REQUIRE_CLICK_TO_FOCUS
  140. if (!inputFocus_ && (graphics_->GetFullscreen() || mouseVisible_) && flags == (SDL_WINDOW_INPUT_FOCUS |
  141. SDL_WINDOW_MOUSE_FOCUS))
  142. #else
  143. if (!inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS))
  144. #endif
  145. focusedThisFrame_ = true;
  146. if (focusedThisFrame_)
  147. GainFocus();
  148. if (inputFocus_ && (flags & SDL_WINDOW_INPUT_FOCUS) == 0)
  149. LoseFocus();
  150. }
  151. else
  152. return;
  153. // Check for relative mode mouse move
  154. if (!touchEmulation_ && (graphics_->GetExternalWindow() || (!mouseVisible_ && inputFocus_ && (flags & SDL_WINDOW_MOUSE_FOCUS))))
  155. {
  156. IntVector2 mousePosition = GetMousePosition();
  157. mouseMove_ = mousePosition - lastMousePosition_;
  158. if (graphics_->GetExternalWindow())
  159. lastMousePosition_ = mousePosition;
  160. else
  161. {
  162. // Recenter the mouse cursor manually after move
  163. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  164. if (mousePosition != center)
  165. {
  166. SetMousePosition(center);
  167. lastMousePosition_ = center;
  168. }
  169. }
  170. // Send mouse move event if necessary
  171. if (mouseMove_ != IntVector2::ZERO)
  172. {
  173. if (suppressNextMouseMove_)
  174. {
  175. mouseMove_ = IntVector2::ZERO;
  176. suppressNextMouseMove_ = false;
  177. }
  178. else
  179. {
  180. using namespace MouseMove;
  181. VariantMap& eventData = GetEventDataMap();
  182. if (mouseVisible_)
  183. {
  184. eventData[P_X] = mousePosition.x_;
  185. eventData[P_Y] = mousePosition.y_;
  186. }
  187. eventData[P_DX] = mouseMove_.x_;
  188. eventData[P_DY] = mouseMove_.y_;
  189. eventData[P_BUTTONS] = mouseButtonDown_;
  190. eventData[P_QUALIFIERS] = GetQualifiers();
  191. SendEvent(E_MOUSEMOVE, eventData);
  192. }
  193. }
  194. }
  195. }
  196. void Input::SetMouseVisible(bool enable)
  197. {
  198. // In touch emulation mode only enabled mouse is allowed
  199. if (touchEmulation_)
  200. enable = true;
  201. // SDL Raspberry Pi "video driver" does not have proper OS mouse support yet, so no-op for now
  202. #ifndef RASPI
  203. if (enable != mouseVisible_)
  204. {
  205. mouseVisible_ = enable;
  206. if (initialized_)
  207. {
  208. // External windows can only support visible mouse cursor
  209. if (graphics_->GetExternalWindow())
  210. {
  211. mouseVisible_ = true;
  212. return;
  213. }
  214. if (!mouseVisible_ && inputFocus_)
  215. {
  216. SDL_ShowCursor(SDL_FALSE);
  217. // Recenter the mouse cursor manually when hiding it to avoid erratic mouse move for one frame
  218. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  219. SetMousePosition(center);
  220. lastMousePosition_ = center;
  221. }
  222. else
  223. SDL_ShowCursor(SDL_TRUE);
  224. }
  225. using namespace MouseVisibleChanged;
  226. VariantMap& eventData = GetEventDataMap();
  227. eventData[P_VISIBLE] = mouseVisible_;
  228. SendEvent(E_MOUSEVISIBLECHANGED, eventData);
  229. }
  230. #endif
  231. }
  232. void Input::SetMouseGrabbed(bool grab)
  233. {
  234. mouseGrabbed_ = grab;
  235. }
  236. void Input::SetToggleFullscreen(bool enable)
  237. {
  238. toggleFullscreen_ = enable;
  239. }
  240. static void PopulateKeyBindingMap(HashMap<String, int>& keyBindingMap)
  241. {
  242. if (keyBindingMap.Empty())
  243. {
  244. keyBindingMap.Insert(MakePair<String, int>("SPACE", KEY_SPACE));
  245. keyBindingMap.Insert(MakePair<String, int>("LCTRL", KEY_LCTRL));
  246. keyBindingMap.Insert(MakePair<String, int>("RCTRL", KEY_RCTRL));
  247. keyBindingMap.Insert(MakePair<String, int>("LSHIFT", KEY_LSHIFT));
  248. keyBindingMap.Insert(MakePair<String, int>("RSHIFT", KEY_RSHIFT));
  249. keyBindingMap.Insert(MakePair<String, int>("LALT", KEY_LALT));
  250. keyBindingMap.Insert(MakePair<String, int>("RALT", KEY_RALT));
  251. keyBindingMap.Insert(MakePair<String, int>("LGUI", KEY_LGUI));
  252. keyBindingMap.Insert(MakePair<String, int>("RGUI", KEY_RGUI));
  253. keyBindingMap.Insert(MakePair<String, int>("TAB", KEY_TAB));
  254. keyBindingMap.Insert(MakePair<String, int>("RETURN", KEY_RETURN));
  255. keyBindingMap.Insert(MakePair<String, int>("RETURN2", KEY_RETURN2));
  256. keyBindingMap.Insert(MakePair<String, int>("ENTER", KEY_KP_ENTER));
  257. keyBindingMap.Insert(MakePair<String, int>("SELECT", KEY_SELECT));
  258. keyBindingMap.Insert(MakePair<String, int>("LEFT", KEY_LEFT));
  259. keyBindingMap.Insert(MakePair<String, int>("RIGHT", KEY_RIGHT));
  260. keyBindingMap.Insert(MakePair<String, int>("UP", KEY_UP));
  261. keyBindingMap.Insert(MakePair<String, int>("DOWN", KEY_DOWN));
  262. keyBindingMap.Insert(MakePair<String, int>("PAGEUP", KEY_PAGEUP));
  263. keyBindingMap.Insert(MakePair<String, int>("PAGEDOWN", KEY_PAGEDOWN));
  264. keyBindingMap.Insert(MakePair<String, int>("F1", KEY_F1));
  265. keyBindingMap.Insert(MakePair<String, int>("F2", KEY_F2));
  266. keyBindingMap.Insert(MakePair<String, int>("F3", KEY_F3));
  267. keyBindingMap.Insert(MakePair<String, int>("F4", KEY_F4));
  268. keyBindingMap.Insert(MakePair<String, int>("F5", KEY_F5));
  269. keyBindingMap.Insert(MakePair<String, int>("F6", KEY_F6));
  270. keyBindingMap.Insert(MakePair<String, int>("F7", KEY_F7));
  271. keyBindingMap.Insert(MakePair<String, int>("F8", KEY_F8));
  272. keyBindingMap.Insert(MakePair<String, int>("F9", KEY_F9));
  273. keyBindingMap.Insert(MakePair<String, int>("F10", KEY_F10));
  274. keyBindingMap.Insert(MakePair<String, int>("F11", KEY_F11));
  275. keyBindingMap.Insert(MakePair<String, int>("F12", KEY_F12));
  276. }
  277. }
  278. static void PopulateMouseButtonBindingMap(HashMap<String, int>& mouseButtonBindingMap)
  279. {
  280. if (mouseButtonBindingMap.Empty())
  281. {
  282. mouseButtonBindingMap.Insert(MakePair<String, int>("LEFT", SDL_BUTTON_LEFT));
  283. mouseButtonBindingMap.Insert(MakePair<String, int>("MIDDLE", SDL_BUTTON_MIDDLE));
  284. mouseButtonBindingMap.Insert(MakePair<String, int>("RIGHT", SDL_BUTTON_RIGHT));
  285. mouseButtonBindingMap.Insert(MakePair<String, int>("X1", SDL_BUTTON_X1));
  286. mouseButtonBindingMap.Insert(MakePair<String, int>("X2", SDL_BUTTON_X2));
  287. }
  288. }
  289. SDL_JoystickID Input::AddScreenJoystick(XMLFile* layoutFile, XMLFile* styleFile)
  290. {
  291. static HashMap<String, int> keyBindingMap;
  292. static HashMap<String, int> mouseButtonBindingMap;
  293. if (!graphics_)
  294. {
  295. LOGWARNING("Cannot add screen joystick in headless mode");
  296. return -1;
  297. }
  298. // If layout file is not given, use the default screen joystick layout
  299. if (!layoutFile)
  300. {
  301. ResourceCache* cache = GetSubsystem<ResourceCache>();
  302. layoutFile = cache->GetResource<XMLFile>("UI/ScreenJoystick.xml");
  303. if (!layoutFile) // Error is already logged
  304. return -1;
  305. }
  306. UI* ui = GetSubsystem<UI>();
  307. SharedPtr<UIElement> screenJoystick = ui->LoadLayout(layoutFile, styleFile);
  308. if (!screenJoystick) // Error is already logged
  309. return -1;
  310. screenJoystick->SetSize(ui->GetRoot()->GetSize());
  311. ui->GetRoot()->AddChild(screenJoystick);
  312. // Get an unused ID for the screen joystick
  313. /// \todo After a real joystick has been plugged in 1073741824 times, the ranges will overlap
  314. SDL_JoystickID joystickID = SCREEN_JOYSTICK_START_ID;
  315. while (joysticks_.Contains(joystickID))
  316. ++joystickID;
  317. JoystickState& state = joysticks_[joystickID];
  318. state.joystickID_ = joystickID;
  319. state.name_ = screenJoystick->GetName();
  320. state.screenJoystick_ = screenJoystick;
  321. unsigned numButtons = 0;
  322. unsigned numAxes = 0;
  323. unsigned numHats = 0;
  324. const Vector<SharedPtr<UIElement> >& children = state.screenJoystick_->GetChildren();
  325. for (Vector<SharedPtr<UIElement> >::ConstIterator iter = children.Begin(); iter != children.End(); ++iter)
  326. {
  327. UIElement* element = iter->Get();
  328. String name = element->GetName();
  329. if (name.StartsWith("Button"))
  330. {
  331. ++numButtons;
  332. // Check whether the button has key binding
  333. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  334. if (text)
  335. {
  336. text->SetVisible(false);
  337. const String& key = text->GetText();
  338. int keyBinding;
  339. if (key.Length() == 1)
  340. keyBinding = key[0];
  341. else
  342. {
  343. PopulateKeyBindingMap(keyBindingMap);
  344. HashMap<String, int>::Iterator i = keyBindingMap.Find(key);
  345. if (i != keyBindingMap.End())
  346. keyBinding = i->second_;
  347. else
  348. {
  349. LOGERRORF("Unsupported key binding: %s", key.CString());
  350. keyBinding = M_MAX_INT;
  351. }
  352. }
  353. if (keyBinding != M_MAX_INT)
  354. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  355. }
  356. // Check whether the button has mouse button binding
  357. text = dynamic_cast<Text*>(element->GetChild("MouseButtonBinding", false));
  358. if (text)
  359. {
  360. text->SetVisible(false);
  361. const String& mouseButton = text->GetText();
  362. PopulateMouseButtonBindingMap(mouseButtonBindingMap);
  363. HashMap<String, int>::Iterator i = mouseButtonBindingMap.Find(mouseButton);
  364. if (i != mouseButtonBindingMap.End())
  365. element->SetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING, i->second_);
  366. else
  367. LOGERRORF("Unsupported mouse button binding: %s", mouseButton.CString());
  368. }
  369. }
  370. else if (name.StartsWith("Axis"))
  371. {
  372. ++numAxes;
  373. ///\todo Axis emulation for screen joystick is not fully supported yet.
  374. LOGWARNING("Axis emulation for screen joystick is not fully supported yet");
  375. }
  376. else if (name.StartsWith("Hat"))
  377. {
  378. ++numHats;
  379. Text* text = dynamic_cast<Text*>(element->GetChild("KeyBinding", false));
  380. if (text)
  381. {
  382. text->SetVisible(false);
  383. String keyBinding = text->GetText();
  384. if (keyBinding.Contains(' ')) // e.g.: "UP DOWN LEFT RIGHT"
  385. {
  386. // Attempt to split the text using ' ' as separator
  387. Vector<String>keyBindings(keyBinding.Split(' '));
  388. String mappedKeyBinding;
  389. if (keyBindings.Size() == 4)
  390. {
  391. PopulateKeyBindingMap(keyBindingMap);
  392. for (unsigned j = 0; j < 4; ++j)
  393. {
  394. if (keyBindings[j].Length() == 1)
  395. mappedKeyBinding.Append(keyBindings[j][0]);
  396. else
  397. {
  398. HashMap<String, int>::Iterator i = keyBindingMap.Find(keyBindings[j]);
  399. if (i != keyBindingMap.End())
  400. mappedKeyBinding.Append(i->second_);
  401. else
  402. break;
  403. }
  404. }
  405. }
  406. if (mappedKeyBinding.Length() != 4)
  407. {
  408. LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  409. keyBinding = "WSAD";
  410. }
  411. else
  412. keyBinding = mappedKeyBinding;
  413. }
  414. else if (keyBinding.Length() != 4)
  415. {
  416. LOGERRORF("%s has invalid key binding %s, fallback to WSAD", name.CString(), keyBinding.CString());
  417. keyBinding = "WSAD";
  418. }
  419. element->SetVar(VAR_BUTTON_KEY_BINDING, keyBinding);
  420. }
  421. }
  422. element->SetVar(VAR_SCREEN_JOYSTICK_ID, joystickID);
  423. }
  424. // Make sure all the children are non-focusable so they do not mistakenly to be considered as active UI input controls by application
  425. PODVector<UIElement*> allChildren;
  426. state.screenJoystick_->GetChildren(allChildren, true);
  427. for (PODVector<UIElement*>::Iterator iter = allChildren.Begin(); iter != allChildren.End(); ++iter)
  428. (*iter)->SetFocusMode(FM_NOTFOCUSABLE);
  429. state.Initialize(numButtons, numAxes, numHats);
  430. // There could be potentially more than one screen joystick, however they all will be handled by a same handler method
  431. // So there is no harm to replace the old handler with the new handler in each call to SubscribeToEvent()
  432. SubscribeToEvent(E_TOUCHBEGIN, HANDLER(Input, HandleScreenJoystickTouch));
  433. SubscribeToEvent(E_TOUCHMOVE, HANDLER(Input, HandleScreenJoystickTouch));
  434. SubscribeToEvent(E_TOUCHEND, HANDLER(Input, HandleScreenJoystickTouch));
  435. return joystickID;
  436. }
  437. bool Input::RemoveScreenJoystick(SDL_JoystickID id)
  438. {
  439. if (!joysticks_.Contains(id))
  440. {
  441. LOGERRORF("Failed to remove non-existing screen joystick ID #%d", id);
  442. return false;
  443. }
  444. JoystickState& state = joysticks_[id];
  445. if (!state.screenJoystick_)
  446. {
  447. LOGERRORF("Failed to remove joystick with ID #%d which is not a screen joystick", id);
  448. return false;
  449. }
  450. state.screenJoystick_->Remove();
  451. joysticks_.Erase(id);
  452. return true;
  453. }
  454. void Input::SetScreenJoystickVisible(SDL_JoystickID id, bool enable)
  455. {
  456. if (joysticks_.Contains(id))
  457. {
  458. JoystickState& state = joysticks_[id];
  459. if (state.screenJoystick_)
  460. state.screenJoystick_->SetVisible(enable);
  461. }
  462. }
  463. void Input::SetScreenKeyboardVisible(bool enable)
  464. {
  465. if (!graphics_)
  466. return;
  467. if (enable != IsScreenKeyboardVisible())
  468. {
  469. if (enable)
  470. SDL_StartTextInput();
  471. else
  472. SDL_StopTextInput();
  473. }
  474. }
  475. void Input::SetTouchEmulation(bool enable)
  476. {
  477. #if !defined(ANDROID) && !defined(IOS)
  478. if (enable != touchEmulation_)
  479. {
  480. // Touch emulation needs the mouse visible
  481. if (enable)
  482. {
  483. if (!mouseVisible_)
  484. SetMouseVisible(true);
  485. // Add a virtual touch device the first time we are enabling emulated touch
  486. if (enable && !SDL_GetNumTouchDevices())
  487. SDL_AddTouch(0, "Emulated Touch");
  488. }
  489. else
  490. ResetTouches();
  491. touchEmulation_ = enable;
  492. }
  493. #endif
  494. }
  495. bool Input::RecordGesture()
  496. {
  497. // If have no touch devices, fail
  498. if (!SDL_GetNumTouchDevices())
  499. {
  500. LOGERROR("Can not record gesture: no touch devices");
  501. return false;
  502. }
  503. return SDL_RecordGesture(-1);
  504. }
  505. bool Input::SaveGestures(Serializer& dest)
  506. {
  507. RWOpsWrapper<Serializer> wrapper(dest);
  508. return SDL_SaveAllDollarTemplates(wrapper.GetRWOps());
  509. }
  510. bool Input::SaveGesture(Serializer& dest, unsigned gestureID)
  511. {
  512. RWOpsWrapper<Serializer> wrapper(dest);
  513. return SDL_SaveDollarTemplate(gestureID, wrapper.GetRWOps());
  514. }
  515. unsigned Input::LoadGestures(Deserializer& source)
  516. {
  517. // If have no touch devices, fail
  518. if (!SDL_GetNumTouchDevices())
  519. {
  520. LOGERROR("Can not load gestures: no touch devices");
  521. return 0;
  522. }
  523. RWOpsWrapper<Deserializer> wrapper(source);
  524. return SDL_LoadDollarTemplates(-1, wrapper.GetRWOps());
  525. }
  526. SDL_JoystickID Input::OpenJoystick(unsigned index)
  527. {
  528. SDL_Joystick* joystick = SDL_JoystickOpen(index);
  529. if (!joystick)
  530. {
  531. LOGERRORF("Cannot open joystick #%d", index);
  532. return -1;
  533. }
  534. // Create joystick state for the new joystick
  535. int joystickID = SDL_JoystickInstanceID(joystick);
  536. JoystickState& state = joysticks_[joystickID];
  537. state.joystick_ = joystick;
  538. state.joystickID_ = joystickID;
  539. state.name_ = SDL_JoystickName(joystick);
  540. if (SDL_IsGameController(index))
  541. state.controller_ = SDL_GameControllerOpen(index);
  542. unsigned numButtons = SDL_JoystickNumButtons(joystick);
  543. unsigned numAxes = SDL_JoystickNumAxes(joystick);
  544. unsigned numHats = SDL_JoystickNumHats(joystick);
  545. // When the joystick is a controller, make sure there's enough axes & buttons for the standard controller mappings
  546. if (state.controller_)
  547. {
  548. if (numButtons < SDL_CONTROLLER_BUTTON_MAX)
  549. numButtons = SDL_CONTROLLER_BUTTON_MAX;
  550. if (numAxes < SDL_CONTROLLER_AXIS_MAX)
  551. numAxes = SDL_CONTROLLER_AXIS_MAX;
  552. }
  553. state.Initialize(numButtons, numAxes, numHats);
  554. return joystickID;
  555. }
  556. int Input::GetKeyFromName(const String& name) const
  557. {
  558. return SDL_GetKeyFromName(name.CString());
  559. }
  560. int Input::GetKeyFromScancode(int scancode) const
  561. {
  562. return SDL_GetKeyFromScancode((SDL_Scancode)scancode);
  563. }
  564. String Input::GetKeyName(int key) const
  565. {
  566. return String(SDL_GetKeyName(key));
  567. }
  568. int Input::GetScancodeFromKey(int key) const
  569. {
  570. return SDL_GetScancodeFromKey(key);
  571. }
  572. int Input::GetScancodeFromName(const String& name) const
  573. {
  574. return SDL_GetScancodeFromName(name.CString());
  575. }
  576. String Input::GetScancodeName(int scancode) const
  577. {
  578. return SDL_GetScancodeName((SDL_Scancode)scancode);
  579. }
  580. bool Input::GetKeyDown(int key) const
  581. {
  582. return keyDown_.Contains(SDL_toupper(key));
  583. }
  584. bool Input::GetKeyPress(int key) const
  585. {
  586. return keyPress_.Contains(SDL_toupper(key));
  587. }
  588. bool Input::GetScancodeDown(int scancode) const
  589. {
  590. return scancodeDown_.Contains(scancode);
  591. }
  592. bool Input::GetScancodePress(int scancode) const
  593. {
  594. return scancodePress_.Contains(scancode);
  595. }
  596. bool Input::GetMouseButtonDown(int button) const
  597. {
  598. return (mouseButtonDown_ & button) != 0;
  599. }
  600. bool Input::GetMouseButtonPress(int button) const
  601. {
  602. return (mouseButtonPress_ & button) != 0;
  603. }
  604. bool Input::GetQualifierDown(int qualifier) const
  605. {
  606. if (qualifier == QUAL_SHIFT)
  607. return GetKeyDown(KEY_LSHIFT) || GetKeyDown(KEY_RSHIFT);
  608. if (qualifier == QUAL_CTRL)
  609. return GetKeyDown(KEY_LCTRL) || GetKeyDown(KEY_RCTRL);
  610. if (qualifier == QUAL_ALT)
  611. return GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT);
  612. return false;
  613. }
  614. bool Input::GetQualifierPress(int qualifier) const
  615. {
  616. if (qualifier == QUAL_SHIFT)
  617. return GetKeyPress(KEY_LSHIFT) || GetKeyPress(KEY_RSHIFT);
  618. if (qualifier == QUAL_CTRL)
  619. return GetKeyPress(KEY_LCTRL) || GetKeyPress(KEY_RCTRL);
  620. if (qualifier == QUAL_ALT)
  621. return GetKeyPress(KEY_LALT) || GetKeyPress(KEY_RALT);
  622. return false;
  623. }
  624. int Input::GetQualifiers() const
  625. {
  626. int ret = 0;
  627. if (GetQualifierDown(QUAL_SHIFT))
  628. ret |= QUAL_SHIFT;
  629. if (GetQualifierDown(QUAL_CTRL))
  630. ret |= QUAL_CTRL;
  631. if (GetQualifierDown(QUAL_ALT))
  632. ret |= QUAL_ALT;
  633. return ret;
  634. }
  635. IntVector2 Input::GetMousePosition() const
  636. {
  637. IntVector2 ret = IntVector2::ZERO;
  638. if (!initialized_)
  639. return ret;
  640. SDL_GetMouseState(&ret.x_, &ret.y_);
  641. return ret;
  642. }
  643. TouchState* Input::GetTouch(unsigned index) const
  644. {
  645. if (index >= touches_.Size())
  646. return 0;
  647. HashMap<int, TouchState>::ConstIterator i = touches_.Begin();
  648. while (index--)
  649. ++i;
  650. return const_cast<TouchState*>(&i->second_);
  651. }
  652. JoystickState* Input::GetJoystickByIndex(unsigned index)
  653. {
  654. unsigned compare = 0;
  655. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  656. {
  657. if (compare++ == index)
  658. return &(i->second_);
  659. }
  660. return 0;
  661. }
  662. JoystickState* Input::GetJoystick(SDL_JoystickID id)
  663. {
  664. HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Find(id);
  665. return i != joysticks_.End() ? &(i->second_) : 0;
  666. }
  667. bool Input::IsScreenJoystickVisible(SDL_JoystickID id) const
  668. {
  669. HashMap<SDL_JoystickID, JoystickState>::ConstIterator i = joysticks_.Find(id);
  670. return i != joysticks_.End() && i->second_.screenJoystick_ && i->second_.screenJoystick_->IsVisible();
  671. }
  672. bool Input::GetScreenKeyboardSupport() const
  673. {
  674. return graphics_ ? SDL_HasScreenKeyboardSupport() : false;
  675. }
  676. bool Input::IsScreenKeyboardVisible() const
  677. {
  678. if (graphics_)
  679. {
  680. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  681. return SDL_IsScreenKeyboardShown(window);
  682. }
  683. else
  684. return false;
  685. }
  686. bool Input::IsMinimized() const
  687. {
  688. // Return minimized state also when unfocused in fullscreen
  689. if (!inputFocus_ && graphics_ && graphics_->GetFullscreen())
  690. return true;
  691. else
  692. return minimized_;
  693. }
  694. void Input::Initialize()
  695. {
  696. Graphics* graphics = GetSubsystem<Graphics>();
  697. if (!graphics || !graphics->IsInitialized())
  698. return;
  699. graphics_ = graphics;
  700. // In external window mode only visible mouse is supported
  701. if (graphics_->GetExternalWindow())
  702. mouseVisible_ = true;
  703. // Set the initial activation
  704. focusedThisFrame_ = true;
  705. initialized_ = true;
  706. ResetJoysticks();
  707. ResetState();
  708. SubscribeToEvent(E_BEGINFRAME, HANDLER(Input, HandleBeginFrame));
  709. LOGINFO("Initialized input");
  710. }
  711. void Input::ResetJoysticks()
  712. {
  713. joysticks_.Clear();
  714. // Open each detected joystick automatically on startup
  715. int size = SDL_NumJoysticks();
  716. for (int i = 0; i < size; ++i)
  717. OpenJoystick(i);
  718. }
  719. void Input::GainFocus()
  720. {
  721. ResetState();
  722. inputFocus_ = true;
  723. focusedThisFrame_ = false;
  724. // Re-establish mouse cursor hiding as necessary
  725. if (!mouseVisible_)
  726. {
  727. SDL_ShowCursor(SDL_FALSE);
  728. suppressNextMouseMove_ = true;
  729. }
  730. else
  731. lastMousePosition_ = GetMousePosition();
  732. SendInputFocusEvent();
  733. }
  734. void Input::LoseFocus()
  735. {
  736. ResetState();
  737. inputFocus_ = false;
  738. focusedThisFrame_ = false;
  739. // Show the mouse cursor when inactive
  740. SDL_ShowCursor(SDL_TRUE);
  741. SendInputFocusEvent();
  742. }
  743. void Input::ResetState()
  744. {
  745. keyDown_.Clear();
  746. keyPress_.Clear();
  747. scancodeDown_.Clear();
  748. scancodePress_.Clear();
  749. /// \todo Check if resetting joystick state on input focus loss is even necessary
  750. for (HashMap<SDL_JoystickID, JoystickState>::Iterator i = joysticks_.Begin(); i != joysticks_.End(); ++i)
  751. i->second_.Reset();
  752. ResetTouches();
  753. // Use SetMouseButton() to reset the state so that mouse events will be sent properly
  754. SetMouseButton(MOUSEB_LEFT, false);
  755. SetMouseButton(MOUSEB_RIGHT, false);
  756. SetMouseButton(MOUSEB_MIDDLE, false);
  757. mouseMove_ = IntVector2::ZERO;
  758. mouseMoveWheel_ = 0;
  759. mouseButtonPress_ = 0;
  760. }
  761. void Input::ResetTouches()
  762. {
  763. for (HashMap<int, TouchState>::Iterator i = touches_.Begin(); i != touches_.End(); ++i)
  764. {
  765. TouchState& state = i->second_;
  766. using namespace TouchEnd;
  767. VariantMap& eventData = GetEventDataMap();
  768. eventData[P_TOUCHID] = state.touchID_;
  769. eventData[P_X] = state.position_.x_;
  770. eventData[P_Y] = state.position_.y_;
  771. SendEvent(E_TOUCHEND, eventData);
  772. }
  773. touches_.Clear();
  774. }
  775. void Input::SendInputFocusEvent()
  776. {
  777. using namespace InputFocus;
  778. VariantMap& eventData = GetEventDataMap();
  779. eventData[P_FOCUS] = HasFocus();
  780. eventData[P_MINIMIZED] = IsMinimized();
  781. SendEvent(E_INPUTFOCUS, eventData);
  782. }
  783. void Input::SetMouseButton(int button, bool newState)
  784. {
  785. #ifdef REQUIRE_CLICK_TO_FOCUS
  786. if (!mouseVisible_ && !graphics_->GetFullscreen())
  787. {
  788. if (!inputFocus_ && newState && button == MOUSEB_LEFT)
  789. focusedThisFrame_ = true;
  790. }
  791. #endif
  792. // If we do not have focus yet, do not react to the mouse button down
  793. if (!graphics_->GetExternalWindow() && newState && !inputFocus_)
  794. return;
  795. if (newState)
  796. {
  797. if (!(mouseButtonDown_ & button))
  798. mouseButtonPress_ |= button;
  799. mouseButtonDown_ |= button;
  800. }
  801. else
  802. {
  803. if (!(mouseButtonDown_ & button))
  804. return;
  805. mouseButtonDown_ &= ~button;
  806. }
  807. using namespace MouseButtonDown;
  808. VariantMap& eventData = GetEventDataMap();
  809. eventData[P_BUTTON] = button;
  810. eventData[P_BUTTONS] = mouseButtonDown_;
  811. eventData[P_QUALIFIERS] = GetQualifiers();
  812. SendEvent(newState ? E_MOUSEBUTTONDOWN : E_MOUSEBUTTONUP, eventData);
  813. }
  814. void Input::SetKey(int key, int scancode, unsigned raw, bool newState)
  815. {
  816. // If we do not have focus yet, do not react to the key down
  817. if (!graphics_->GetExternalWindow() && newState && !inputFocus_)
  818. return;
  819. bool repeat = false;
  820. if (newState)
  821. {
  822. scancodeDown_.Insert(scancode);
  823. scancodePress_.Insert(scancode);
  824. if (!keyDown_.Contains(key))
  825. {
  826. keyDown_.Insert(key);
  827. keyPress_.Insert(key);
  828. }
  829. else
  830. repeat = true;
  831. }
  832. else
  833. {
  834. scancodeDown_.Erase(scancode);
  835. if (!keyDown_.Erase(key))
  836. return;
  837. }
  838. using namespace KeyDown;
  839. VariantMap& eventData = GetEventDataMap();
  840. eventData[P_KEY] = key;
  841. eventData[P_SCANCODE] = scancode;
  842. eventData[P_RAW] = raw;
  843. eventData[P_BUTTONS] = mouseButtonDown_;
  844. eventData[P_QUALIFIERS] = GetQualifiers();
  845. if (newState)
  846. eventData[P_REPEAT] = repeat;
  847. SendEvent(newState ? E_KEYDOWN : E_KEYUP, eventData);
  848. if ((key == KEY_RETURN || key == KEY_RETURN2 || key == KEY_KP_ENTER) && newState && !repeat && toggleFullscreen_ &&
  849. (GetKeyDown(KEY_LALT) || GetKeyDown(KEY_RALT)))
  850. graphics_->ToggleFullscreen();
  851. }
  852. void Input::SetMouseWheel(int delta)
  853. {
  854. // If we do not have focus yet, do not react to the wheel
  855. if (!graphics_->GetExternalWindow() && !inputFocus_)
  856. return;
  857. if (delta)
  858. {
  859. mouseMoveWheel_ += delta;
  860. using namespace MouseWheel;
  861. VariantMap& eventData = GetEventDataMap();
  862. eventData[P_WHEEL] = delta;
  863. eventData[P_BUTTONS] = mouseButtonDown_;
  864. eventData[P_QUALIFIERS] = GetQualifiers();
  865. SendEvent(E_MOUSEWHEEL, eventData);
  866. }
  867. }
  868. void Input::SetMousePosition(const IntVector2& position)
  869. {
  870. if (!graphics_)
  871. return;
  872. SDL_WarpMouseInWindow(graphics_->GetImpl()->GetWindow(), position.x_, position.y_);
  873. }
  874. void Input::HandleSDLEvent(void* sdlEvent)
  875. {
  876. SDL_Event& evt = *static_cast<SDL_Event*>(sdlEvent);
  877. switch (evt.type)
  878. {
  879. case SDL_KEYDOWN:
  880. // Convert to uppercase to match Win32 virtual key codes
  881. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, evt.key.keysym.raw, true);
  882. break;
  883. case SDL_KEYUP:
  884. SetKey(ConvertSDLKeyCode(evt.key.keysym.sym, evt.key.keysym.scancode), evt.key.keysym.scancode, evt.key.keysym.raw, false);
  885. break;
  886. case SDL_TEXTINPUT:
  887. {
  888. textInput_ = &evt.text.text[0];
  889. unsigned unicode = textInput_.AtUTF8(0);
  890. if (unicode)
  891. {
  892. using namespace TextInput;
  893. VariantMap textInputEventData;
  894. textInputEventData[P_TEXT] = textInput_;
  895. textInputEventData[P_BUTTONS] = mouseButtonDown_;
  896. textInputEventData[P_QUALIFIERS] = GetQualifiers();
  897. SendEvent(E_TEXTINPUT, textInputEventData);
  898. }
  899. }
  900. break;
  901. case SDL_MOUSEBUTTONDOWN:
  902. if (!touchEmulation_)
  903. SetMouseButton(1 << (evt.button.button - 1), true);
  904. else if (touchEmulation_ && evt.button.button == 1)
  905. {
  906. int x, y;
  907. SDL_GetMouseState(&x, &y);
  908. SDL_Event event;
  909. event.type = SDL_FINGERDOWN;
  910. event.tfinger.touchId = 0;
  911. event.tfinger.fingerId = 0;
  912. event.tfinger.pressure = 1.0f;
  913. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  914. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  915. event.tfinger.dx = 0;
  916. event.tfinger.dy = 0;
  917. SDL_PushEvent(&event);
  918. }
  919. break;
  920. case SDL_MOUSEBUTTONUP:
  921. if (!touchEmulation_)
  922. SetMouseButton(1 << (evt.button.button - 1), false);
  923. else if (touchEmulation_ && evt.button.button == 1)
  924. {
  925. int x, y;
  926. SDL_GetMouseState(&x, &y);
  927. SDL_Event event;
  928. event.type = SDL_FINGERUP;
  929. event.tfinger.touchId = 0;
  930. event.tfinger.fingerId = 0;
  931. event.tfinger.pressure = 0.0f;
  932. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  933. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  934. event.tfinger.dx = 0;
  935. event.tfinger.dy = 0;
  936. SDL_PushEvent(&event);
  937. }
  938. break;
  939. case SDL_MOUSEMOTION:
  940. if (mouseVisible_ && !touchEmulation_)
  941. {
  942. mouseMove_.x_ += evt.motion.xrel;
  943. mouseMove_.y_ += evt.motion.yrel;
  944. using namespace MouseMove;
  945. VariantMap& eventData = GetEventDataMap();
  946. if (mouseVisible_)
  947. {
  948. eventData[P_X] = evt.motion.x;
  949. eventData[P_Y] = evt.motion.y;
  950. }
  951. eventData[P_DX] = evt.motion.xrel;
  952. eventData[P_DY] = evt.motion.yrel;
  953. eventData[P_BUTTONS] = mouseButtonDown_;
  954. eventData[P_QUALIFIERS] = GetQualifiers();
  955. SendEvent(E_MOUSEMOVE, eventData);
  956. }
  957. else if (touchEmulation_ && touches_.Contains(0))
  958. {
  959. int x, y;
  960. SDL_GetMouseState(&x, &y);
  961. SDL_Event event;
  962. event.type = SDL_FINGERMOTION;
  963. event.tfinger.touchId = 0;
  964. event.tfinger.fingerId = 0;
  965. event.tfinger.pressure = 1.0f;
  966. event.tfinger.x = (float)x / (float)graphics_->GetWidth();
  967. event.tfinger.y = (float)y / (float)graphics_->GetHeight();
  968. event.tfinger.dx = (float)evt.motion.xrel / (float)graphics_->GetWidth();
  969. event.tfinger.dy = (float)evt.motion.yrel / (float)graphics_->GetHeight();
  970. SDL_PushEvent(&event);
  971. }
  972. break;
  973. case SDL_MOUSEWHEEL:
  974. if (!touchEmulation_)
  975. SetMouseWheel(evt.wheel.y);
  976. break;
  977. case SDL_FINGERDOWN:
  978. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  979. {
  980. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  981. TouchState& state = touches_[touchID];
  982. state.touchID_ = touchID;
  983. state.lastPosition_ = state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  984. (int)(evt.tfinger.y * graphics_->GetHeight()));
  985. state.delta_ = IntVector2::ZERO;
  986. state.pressure_ = evt.tfinger.pressure;
  987. using namespace TouchBegin;
  988. VariantMap& eventData = GetEventDataMap();
  989. eventData[P_TOUCHID] = touchID;
  990. eventData[P_X] = state.position_.x_;
  991. eventData[P_Y] = state.position_.y_;
  992. eventData[P_PRESSURE] = state.pressure_;
  993. SendEvent(E_TOUCHBEGIN, eventData);
  994. }
  995. break;
  996. case SDL_FINGERUP:
  997. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  998. {
  999. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  1000. TouchState& state = touches_[touchID];
  1001. using namespace TouchEnd;
  1002. VariantMap& eventData = GetEventDataMap();
  1003. // Do not trust the position in the finger up event. Instead use the last position stored in the
  1004. // touch structure
  1005. eventData[P_TOUCHID] = touchID;
  1006. eventData[P_X] = state.position_.x_;
  1007. eventData[P_Y] = state.position_.y_;
  1008. SendEvent(E_TOUCHEND, eventData);
  1009. touches_.Erase(touchID);
  1010. }
  1011. break;
  1012. case SDL_FINGERMOTION:
  1013. if (evt.tfinger.touchId != SDL_TOUCH_MOUSEID)
  1014. {
  1015. int touchID = evt.tfinger.fingerId & 0x7ffffff;
  1016. TouchState& state = touches_[touchID];
  1017. state.touchID_ = touchID;
  1018. state.position_ = IntVector2((int)(evt.tfinger.x * graphics_->GetWidth()),
  1019. (int)(evt.tfinger.y * graphics_->GetHeight()));
  1020. state.delta_ = state.position_ - state.lastPosition_;
  1021. state.pressure_ = evt.tfinger.pressure;
  1022. using namespace TouchMove;
  1023. VariantMap& eventData = GetEventDataMap();
  1024. eventData[P_TOUCHID] = touchID;
  1025. eventData[P_X] = state.position_.x_;
  1026. eventData[P_Y] = state.position_.y_;
  1027. eventData[P_DX] = (int)(evt.tfinger.dx * graphics_->GetWidth());
  1028. eventData[P_DY] = (int)(evt.tfinger.dy * graphics_->GetHeight());
  1029. eventData[P_PRESSURE] = state.pressure_;
  1030. SendEvent(E_TOUCHMOVE, eventData);
  1031. }
  1032. break;
  1033. case SDL_DOLLARRECORD:
  1034. {
  1035. using namespace GestureRecorded;
  1036. VariantMap& eventData = GetEventDataMap();
  1037. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1038. SendEvent(E_GESTURERECORDED, eventData);
  1039. }
  1040. break;
  1041. case SDL_DOLLARGESTURE:
  1042. {
  1043. using namespace GestureInput;
  1044. VariantMap& eventData = GetEventDataMap();
  1045. eventData[P_GESTUREID] = (int)evt.dgesture.gestureId;
  1046. eventData[P_CENTERX] = (int)(evt.dgesture.x * graphics_->GetWidth());
  1047. eventData[P_CENTERY] = (int)(evt.dgesture.y * graphics_->GetHeight());
  1048. eventData[P_NUMFINGERS] = (int)evt.dgesture.numFingers;
  1049. eventData[P_ERROR] = evt.dgesture.error;
  1050. SendEvent(E_GESTUREINPUT, eventData);
  1051. }
  1052. break;
  1053. case SDL_MULTIGESTURE:
  1054. {
  1055. using namespace MultiGesture;
  1056. VariantMap& eventData = GetEventDataMap();
  1057. eventData[P_CENTERX] = (int)(evt.mgesture.x * graphics_->GetWidth());
  1058. eventData[P_CENTERY] = (int)(evt.mgesture.y * graphics_->GetHeight());
  1059. eventData[P_NUMFINGERS] = (int)evt.mgesture.numFingers;
  1060. eventData[P_DTHETA] = M_RADTODEG * evt.mgesture.dTheta;
  1061. eventData[P_DDIST] = evt.mgesture.dDist;
  1062. SendEvent(E_MULTIGESTURE, eventData);
  1063. }
  1064. break;
  1065. case SDL_JOYDEVICEADDED:
  1066. {
  1067. using namespace JoystickConnected;
  1068. SDL_JoystickID joystickID = OpenJoystick(evt.jdevice.which);
  1069. VariantMap& eventData = GetEventDataMap();
  1070. eventData[P_JOYSTICKID] = joystickID;
  1071. SendEvent(E_JOYSTICKCONNECTED, eventData);
  1072. }
  1073. break;
  1074. case SDL_JOYDEVICEREMOVED:
  1075. {
  1076. using namespace JoystickDisconnected;
  1077. joysticks_.Erase(evt.jdevice.which);
  1078. VariantMap& eventData = GetEventDataMap();
  1079. eventData[P_JOYSTICKID] = evt.jdevice.which;
  1080. SendEvent(E_JOYSTICKDISCONNECTED, eventData);
  1081. }
  1082. break;
  1083. case SDL_JOYBUTTONDOWN:
  1084. {
  1085. using namespace JoystickButtonDown;
  1086. unsigned button = evt.jbutton.button;
  1087. SDL_JoystickID joystickID = evt.jbutton.which;
  1088. JoystickState& state = joysticks_[joystickID];
  1089. // Skip ordinary joystick event for a controller
  1090. if (!state.controller_)
  1091. {
  1092. VariantMap& eventData = GetEventDataMap();
  1093. eventData[P_JOYSTICKID] = joystickID;
  1094. eventData[P_BUTTON] = button;
  1095. if (button < state.buttons_.Size())
  1096. {
  1097. state.buttons_[button] = true;
  1098. state.buttonPress_[button] = true;
  1099. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1100. }
  1101. }
  1102. }
  1103. break;
  1104. case SDL_JOYBUTTONUP:
  1105. {
  1106. using namespace JoystickButtonUp;
  1107. unsigned button = evt.jbutton.button;
  1108. SDL_JoystickID joystickID = evt.jbutton.which;
  1109. JoystickState& state = joysticks_[joystickID];
  1110. if (!state.controller_)
  1111. {
  1112. VariantMap& eventData = GetEventDataMap();
  1113. eventData[P_JOYSTICKID] = joystickID;
  1114. eventData[P_BUTTON] = button;
  1115. if (button < state.buttons_.Size())
  1116. {
  1117. if (!state.controller_)
  1118. state.buttons_[button] = false;
  1119. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1120. }
  1121. }
  1122. }
  1123. break;
  1124. case SDL_JOYAXISMOTION:
  1125. {
  1126. using namespace JoystickAxisMove;
  1127. SDL_JoystickID joystickID = evt.jaxis.which;
  1128. JoystickState& state = joysticks_[joystickID];
  1129. if (!state.controller_)
  1130. {
  1131. VariantMap& eventData = GetEventDataMap();
  1132. eventData[P_JOYSTICKID] = joystickID;
  1133. eventData[P_AXIS] = evt.jaxis.axis;
  1134. eventData[P_POSITION] = Clamp((float)evt.jaxis.value / 32767.0f, -1.0f, 1.0f);
  1135. if (evt.jaxis.axis < state.axes_.Size())
  1136. {
  1137. // If the joystick is a controller, only use the controller axis mappings
  1138. // (we'll also get the controller event)
  1139. if (!state.controller_)
  1140. state.axes_[evt.jaxis.axis] = eventData[P_POSITION].GetFloat();
  1141. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1142. }
  1143. }
  1144. }
  1145. break;
  1146. case SDL_JOYHATMOTION:
  1147. {
  1148. using namespace JoystickHatMove;
  1149. SDL_JoystickID joystickID = evt.jaxis.which;
  1150. JoystickState& state = joysticks_[joystickID];
  1151. VariantMap& eventData = GetEventDataMap();
  1152. eventData[P_JOYSTICKID] = joystickID;
  1153. eventData[P_HAT] = evt.jhat.hat;
  1154. eventData[P_POSITION] = evt.jhat.value;
  1155. if (evt.jhat.hat < state.hats_.Size())
  1156. {
  1157. state.hats_[evt.jhat.hat] = evt.jhat.value;
  1158. SendEvent(E_JOYSTICKHATMOVE, eventData);
  1159. }
  1160. }
  1161. break;
  1162. case SDL_CONTROLLERBUTTONDOWN:
  1163. {
  1164. using namespace JoystickButtonDown;
  1165. unsigned button = evt.cbutton.button;
  1166. SDL_JoystickID joystickID = evt.cbutton.which;
  1167. JoystickState& state = joysticks_[joystickID];
  1168. VariantMap& eventData = GetEventDataMap();
  1169. eventData[P_JOYSTICKID] = joystickID;
  1170. eventData[P_BUTTON] = button;
  1171. if (button < state.buttons_.Size())
  1172. {
  1173. state.buttons_[button] = true;
  1174. state.buttonPress_[button] = true;
  1175. SendEvent(E_JOYSTICKBUTTONDOWN, eventData);
  1176. }
  1177. }
  1178. break;
  1179. case SDL_CONTROLLERBUTTONUP:
  1180. {
  1181. using namespace JoystickButtonUp;
  1182. unsigned button = evt.cbutton.button;
  1183. SDL_JoystickID joystickID = evt.cbutton.which;
  1184. JoystickState& state = joysticks_[joystickID];
  1185. VariantMap& eventData = GetEventDataMap();
  1186. eventData[P_JOYSTICKID] = joystickID;
  1187. eventData[P_BUTTON] = button;
  1188. if (button < state.buttons_.Size())
  1189. {
  1190. state.buttons_[button] = false;
  1191. SendEvent(E_JOYSTICKBUTTONUP, eventData);
  1192. }
  1193. }
  1194. break;
  1195. case SDL_CONTROLLERAXISMOTION:
  1196. {
  1197. using namespace JoystickAxisMove;
  1198. SDL_JoystickID joystickID = evt.caxis.which;
  1199. JoystickState& state = joysticks_[joystickID];
  1200. VariantMap& eventData = GetEventDataMap();
  1201. eventData[P_JOYSTICKID] = joystickID;
  1202. eventData[P_AXIS] = evt.caxis.axis;
  1203. eventData[P_POSITION] = Clamp((float)evt.caxis.value / 32767.0f, -1.0f, 1.0f);
  1204. if (evt.caxis.axis < state.axes_.Size())
  1205. {
  1206. state.axes_[evt.caxis.axis] = eventData[P_POSITION].GetFloat();
  1207. SendEvent(E_JOYSTICKAXISMOVE, eventData);
  1208. }
  1209. }
  1210. break;
  1211. case SDL_WINDOWEVENT:
  1212. {
  1213. switch (evt.window.event)
  1214. {
  1215. case SDL_WINDOWEVENT_MINIMIZED:
  1216. minimized_ = true;
  1217. SendInputFocusEvent();
  1218. break;
  1219. case SDL_WINDOWEVENT_MAXIMIZED:
  1220. case SDL_WINDOWEVENT_RESTORED:
  1221. minimized_ = false;
  1222. SendInputFocusEvent();
  1223. #ifdef IOS
  1224. // On iOS we never lose the GL context, but may have done GPU object changes that could not be applied yet.
  1225. // Apply them now
  1226. graphics_->Restore();
  1227. #endif
  1228. break;
  1229. #ifdef ANDROID
  1230. case SDL_WINDOWEVENT_FOCUS_GAINED:
  1231. // Restore GPU objects to the new GL context
  1232. graphics_->Restore();
  1233. break;
  1234. #endif
  1235. case SDL_WINDOWEVENT_RESIZED:
  1236. graphics_->WindowResized();
  1237. break;
  1238. }
  1239. }
  1240. break;
  1241. case SDL_DROPFILE:
  1242. {
  1243. using namespace DropFile;
  1244. VariantMap& eventData = GetEventDataMap();
  1245. eventData[P_FILENAME] = GetInternalPath(String(evt.drop.file));
  1246. SDL_free(evt.drop.file);
  1247. SendEvent(E_DROPFILE, eventData);
  1248. }
  1249. break;
  1250. case SDL_QUIT:
  1251. SendEvent(E_EXITREQUESTED);
  1252. break;
  1253. }
  1254. }
  1255. void Input::HandleScreenMode(StringHash eventType, VariantMap& eventData)
  1256. {
  1257. // Reset input state on subsequent initializations
  1258. if (!initialized_)
  1259. Initialize();
  1260. else
  1261. ResetState();
  1262. // Re-enable cursor clipping, and re-center the cursor (if needed) to the new screen size, so that there is no erroneous
  1263. // mouse move event. Also get new window ID if it changed
  1264. SDL_Window* window = graphics_->GetImpl()->GetWindow();
  1265. windowID_ = SDL_GetWindowID(window);
  1266. if (!mouseVisible_)
  1267. {
  1268. IntVector2 center(graphics_->GetWidth() / 2, graphics_->GetHeight() / 2);
  1269. SetMousePosition(center);
  1270. lastMousePosition_ = center;
  1271. }
  1272. focusedThisFrame_ = true;
  1273. // After setting a new screen mode we should not be minimized
  1274. minimized_ = (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED) != 0;
  1275. }
  1276. void Input::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  1277. {
  1278. // Update input right at the beginning of the frame
  1279. Update();
  1280. }
  1281. void Input::HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData)
  1282. {
  1283. using namespace TouchBegin;
  1284. // Only interested in events from screen joystick(s)
  1285. TouchState& state = touches_[eventData[P_TOUCHID].GetInt()];
  1286. IntVector2 position(state.position_.x_, state.position_.y_);
  1287. UIElement* element = eventType == E_TOUCHBEGIN ? GetSubsystem<UI>()->GetElementAt(position) : state.touchedElement_;
  1288. if (!element)
  1289. return;
  1290. Variant variant = element->GetVar(VAR_SCREEN_JOYSTICK_ID);
  1291. if (variant.IsEmpty())
  1292. return;
  1293. SDL_JoystickID joystickID = variant.GetInt();
  1294. if (eventType == E_TOUCHEND)
  1295. state.touchedElement_.Reset();
  1296. else
  1297. state.touchedElement_ = element;
  1298. // Prepare a fake SDL event
  1299. SDL_Event evt;
  1300. const String& name = element->GetName();
  1301. if (name.StartsWith("Button"))
  1302. {
  1303. if (eventType == E_TOUCHMOVE)
  1304. return;
  1305. // Determine whether to inject a joystick event or keyboard/mouse event
  1306. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  1307. Variant mouseButtonBindingVar = element->GetVar(VAR_BUTTON_MOUSE_BUTTON_BINDING);
  1308. if (keyBindingVar.IsEmpty() && mouseButtonBindingVar.IsEmpty())
  1309. {
  1310. evt.type = eventType == E_TOUCHBEGIN ? SDL_JOYBUTTONDOWN : SDL_JOYBUTTONUP;
  1311. evt.jbutton.which = joystickID;
  1312. evt.jbutton.button = ToUInt(name.Substring(6));
  1313. }
  1314. else
  1315. {
  1316. if (!keyBindingVar.IsEmpty())
  1317. {
  1318. evt.type = eventType == E_TOUCHBEGIN ? SDL_KEYDOWN : SDL_KEYUP;
  1319. evt.key.keysym.sym = keyBindingVar.GetInt();
  1320. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1321. }
  1322. if (!mouseButtonBindingVar.IsEmpty() && !touchEmulation_)
  1323. {
  1324. // Mouse button are sent as extra events besides key events
  1325. // Do not send mouse events in touch emulation mode, because those would in turn be re-interpreted as touch
  1326. SDL_Event evt;
  1327. evt.type = eventType == E_TOUCHBEGIN ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP;
  1328. evt.button.button = mouseButtonBindingVar.GetInt();
  1329. HandleSDLEvent(&evt);
  1330. }
  1331. }
  1332. }
  1333. else if (name.StartsWith("Hat"))
  1334. {
  1335. Variant keyBindingVar = element->GetVar(VAR_BUTTON_KEY_BINDING);
  1336. if (keyBindingVar.IsEmpty())
  1337. {
  1338. evt.type = SDL_JOYHATMOTION;
  1339. evt.jaxis.which = joystickID;
  1340. evt.jhat.hat = ToUInt(name.Substring(3));
  1341. evt.jhat.value = HAT_CENTER;
  1342. if (eventType != E_TOUCHEND)
  1343. {
  1344. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  1345. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1346. evt.jhat.value |= HAT_UP;
  1347. if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1348. evt.jhat.value |= HAT_DOWN;
  1349. if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1350. evt.jhat.value |= HAT_LEFT;
  1351. if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1352. evt.jhat.value |= HAT_RIGHT;
  1353. }
  1354. }
  1355. else
  1356. {
  1357. // Hat is binded by 4 keys, like 'WASD'
  1358. String keyBinding = keyBindingVar.GetString();
  1359. if (eventType == E_TOUCHEND)
  1360. {
  1361. evt.type = SDL_KEYUP;
  1362. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  1363. if (!evt.key.keysym.sym)
  1364. return;
  1365. element->SetVar(VAR_LAST_KEYSYM, 0);
  1366. }
  1367. else
  1368. {
  1369. evt.type = SDL_KEYDOWN;
  1370. IntVector2 relPosition = position - element->GetScreenPosition() - element->GetSize() / 2;
  1371. if (relPosition.y_ < 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1372. evt.key.keysym.sym = keyBinding[0];
  1373. else if (relPosition.y_ > 0 && Abs(relPosition.x_ * 3 / 2) < Abs(relPosition.y_))
  1374. evt.key.keysym.sym = keyBinding[1];
  1375. else if (relPosition.x_ < 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1376. evt.key.keysym.sym = keyBinding[2];
  1377. else if (relPosition.x_ > 0 && Abs(relPosition.y_ * 3 / 2) < Abs(relPosition.x_))
  1378. evt.key.keysym.sym = keyBinding[3];
  1379. else
  1380. return;
  1381. if (eventType == E_TOUCHMOVE && evt.key.keysym.sym != element->GetVar(VAR_LAST_KEYSYM).GetInt())
  1382. {
  1383. // Dragging past the directional boundary will cause an additional key up event for previous key symbol
  1384. SDL_Event evt;
  1385. evt.type = SDL_KEYUP;
  1386. evt.key.keysym.sym = element->GetVar(VAR_LAST_KEYSYM).GetInt();
  1387. if (evt.key.keysym.sym)
  1388. {
  1389. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1390. HandleSDLEvent(&evt);
  1391. }
  1392. element->SetVar(VAR_LAST_KEYSYM, 0);
  1393. }
  1394. evt.key.keysym.scancode = SDL_SCANCODE_UNKNOWN;
  1395. element->SetVar(VAR_LAST_KEYSYM, evt.key.keysym.sym);
  1396. }
  1397. }
  1398. }
  1399. else
  1400. return;
  1401. // Handle the fake SDL event to turn it into Urho3D genuine event
  1402. HandleSDLEvent(&evt);
  1403. }
  1404. }