Input.cpp 89 KB

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