Input.cpp 82 KB

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