Input.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. //
  2. // Copyright (c) 2008-2020 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. /// \file
  23. #pragma once
  24. #include "../Container/FlagSet.h"
  25. #include "../Container/HashSet.h"
  26. #include "../Core/Mutex.h"
  27. #include "../Core/Object.h"
  28. #include "../Container/List.h"
  29. #include "../Input/InputEvents.h"
  30. #include "../UI/Cursor.h"
  31. namespace Urho3D
  32. {
  33. /// %Input Mouse Modes.
  34. enum MouseMode
  35. {
  36. MM_ABSOLUTE = 0,
  37. MM_RELATIVE,
  38. MM_WRAP,
  39. MM_FREE,
  40. MM_INVALID
  41. };
  42. class Deserializer;
  43. class Graphics;
  44. class Serializer;
  45. class UIElement;
  46. class XMLFile;
  47. const IntVector2 MOUSE_POSITION_OFFSCREEN = IntVector2(M_MIN_INT, M_MIN_INT);
  48. /// %Input state for a finger touch.
  49. /// @fakeref
  50. struct TouchState
  51. {
  52. /// Return last touched UI element, used by scripting integration.
  53. /// @property
  54. UIElement* GetTouchedElement();
  55. /// Touch (finger) ID.
  56. int touchID_;
  57. /// Position in screen coordinates.
  58. IntVector2 position_;
  59. /// Last position in screen coordinates.
  60. IntVector2 lastPosition_;
  61. /// Movement since last frame.
  62. IntVector2 delta_;
  63. /// Finger pressure.
  64. float pressure_;
  65. /// Last touched UI element from screen joystick.
  66. WeakPtr<UIElement> touchedElement_;
  67. };
  68. /// %Input state for a joystick.
  69. /// @fakeref
  70. struct JoystickState
  71. {
  72. /// Initialize the number of buttons, axes and hats and set them to neutral state.
  73. void Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats);
  74. /// Reset button, axis and hat states to neutral.
  75. void Reset();
  76. /// Return whether is a game controller. Game controllers will use standardized axis and button mappings.
  77. /// @property
  78. bool IsController() const { return controller_ != nullptr; }
  79. /// Return number of buttons.
  80. /// @property
  81. unsigned GetNumButtons() const { return buttons_.Size(); }
  82. /// Return number of axes.
  83. /// @property
  84. unsigned GetNumAxes() const { return axes_.Size(); }
  85. /// Return number of hats.
  86. /// @property
  87. unsigned GetNumHats() const { return hats_.Size(); }
  88. /// Check if a button is held down.
  89. /// @property
  90. bool GetButtonDown(unsigned index) const { return index < buttons_.Size() ? buttons_[index] : false; }
  91. /// Check if a button has been pressed on this frame.
  92. /// @property
  93. bool GetButtonPress(unsigned index) const { return index < buttonPress_.Size() ? buttonPress_[index] : false; }
  94. /// Return axis position.
  95. /// @property
  96. float GetAxisPosition(unsigned index) const { return index < axes_.Size() ? axes_[index] : 0.0f; }
  97. /// Return hat position.
  98. /// @property
  99. int GetHatPosition(unsigned index) const { return index < hats_.Size() ? hats_[index] : int(HAT_CENTER); }
  100. /// SDL joystick.
  101. SDL_Joystick* joystick_{};
  102. /// SDL joystick instance ID.
  103. SDL_JoystickID joystickID_{};
  104. /// SDL game controller.
  105. SDL_GameController* controller_{};
  106. /// UI element containing the screen joystick.
  107. UIElement* screenJoystick_{};
  108. /// Joystick name.
  109. String name_;
  110. /// Button up/down state.
  111. PODVector<bool> buttons_;
  112. /// Button pressed on this frame.
  113. PODVector<bool> buttonPress_;
  114. /// Axis position from -1 to 1.
  115. PODVector<float> axes_;
  116. /// POV hat bits.
  117. PODVector<int> hats_;
  118. };
  119. #ifdef __EMSCRIPTEN__
  120. class EmscriptenInput;
  121. #endif
  122. /// %Input subsystem. Converts operating system window messages to input state and events.
  123. class URHO3D_API Input : public Object
  124. {
  125. URHO3D_OBJECT(Input, Object);
  126. #ifdef __EMSCRIPTEN__
  127. friend class EmscriptenInput;
  128. #endif
  129. public:
  130. /// Construct.
  131. explicit Input(Context* context);
  132. /// Destruct.
  133. ~Input() override;
  134. /// Poll for window messages. Called by HandleBeginFrame().
  135. void Update();
  136. /// Set whether ALT-ENTER fullscreen toggle is enabled.
  137. /// @property
  138. void SetToggleFullscreen(bool enable);
  139. /// Set whether the operating system mouse cursor is visible. When not visible (default), is kept centered to prevent leaving the window. Mouse visibility event can be suppressed-- this also recalls any unsuppressed SetMouseVisible which can be returned by ResetMouseVisible().
  140. void SetMouseVisible(bool enable, bool suppressEvent = false);
  141. /// Reset last mouse visibility that was not suppressed in SetMouseVisible.
  142. void ResetMouseVisible();
  143. /// Set whether the mouse is currently being grabbed by an operation.
  144. void SetMouseGrabbed(bool grab, bool suppressEvent = false);
  145. /// Reset the mouse grabbed to the last unsuppressed SetMouseGrabbed call.
  146. void ResetMouseGrabbed();
  147. /// Set the mouse mode.
  148. /** Set the mouse mode behaviour.
  149. * MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
  150. * When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
  151. * If the operating system and UI cursors are both invisible, interaction with the Urho UI will be limited (eg: drag move / drag end events will not trigger).
  152. * SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
  153. *
  154. * MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
  155. * The operating system cursor cannot be set to be visible in this mode via SetMouseVisible(), however changes are tracked and will be restored when another mouse mode is set.
  156. * When the virtual cursor is also invisible, UI interaction will still function as normal (eg: drag events will trigger).
  157. * SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
  158. *
  159. * MM_WRAP grabs the mouse from the operating system and confines the operating system cursor to the window, wrapping the cursor when it is near the edges.
  160. * SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
  161. *
  162. * MM_FREE does not grab/confine the mouse cursor even when it is hidden. This can be used for cases where the cursor should render using the operating system
  163. * outside the window, and perform custom rendering (with SetMouseVisible(false)) inside.
  164. */
  165. void SetMouseMode(MouseMode mode, bool suppressEvent = false);
  166. /// Reset the last mouse mode that wasn't suppressed in SetMouseMode.
  167. void ResetMouseMode();
  168. /// Add screen joystick.
  169. /** Return the joystick instance ID when successful or negative on error.
  170. * If layout file is not given, use the default screen joystick layout.
  171. * If style file is not given, use the default style file from root UI element.
  172. *
  173. * This method should only be called in main thread.
  174. */
  175. SDL_JoystickID AddScreenJoystick(XMLFile* layoutFile = nullptr, XMLFile* styleFile = nullptr);
  176. /// Remove screen joystick by instance ID.
  177. /** Return true if successful.
  178. *
  179. * This method should only be called in main thread.
  180. */
  181. bool RemoveScreenJoystick(SDL_JoystickID id);
  182. /// Set whether the virtual joystick is visible.
  183. /// @property
  184. void SetScreenJoystickVisible(SDL_JoystickID id, bool enable);
  185. /// Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
  186. /// @property
  187. void SetScreenKeyboardVisible(bool enable);
  188. /// Set touch emulation by mouse. Only available on desktop platforms. When enabled, actual mouse events are no longer sent and the mouse cursor is forced visible.
  189. /// @property
  190. void SetTouchEmulation(bool enable);
  191. /// Begin recording a touch gesture. Return true if successful. The E_GESTURERECORDED event (which contains the ID for the new gesture) will be sent when recording finishes.
  192. bool RecordGesture();
  193. /// Save all in-memory touch gestures. Return true if successful.
  194. bool SaveGestures(Serializer& dest);
  195. /// Save a specific in-memory touch gesture to a file. Return true if successful.
  196. bool SaveGesture(Serializer& dest, unsigned gestureID);
  197. /// Load touch gestures from a file. Return number of loaded gestures, or 0 on failure.
  198. unsigned LoadGestures(Deserializer& source);
  199. /// Remove an in-memory gesture by ID. Return true if was found.
  200. bool RemoveGesture(unsigned gestureID);
  201. /// Remove all in-memory gestures.
  202. void RemoveAllGestures();
  203. /// Set the mouse cursor position. Uses the backbuffer (Graphics width/height) coordinates.
  204. /// @property
  205. void SetMousePosition(const IntVector2& position);
  206. /// Center the mouse position.
  207. void CenterMousePosition();
  208. /// Return keycode from key name.
  209. Key GetKeyFromName(const String& name) const;
  210. /// Return keycode from scancode.
  211. Key GetKeyFromScancode(Scancode scancode) const;
  212. /// Return name of key from keycode.
  213. String GetKeyName(Key key) const;
  214. /// Return scancode from keycode.
  215. Scancode GetScancodeFromKey(Key key) const;
  216. /// Return scancode from key name.
  217. Scancode GetScancodeFromName(const String& name) const;
  218. /// Return name of key from scancode.
  219. String GetScancodeName(Scancode scancode) const;
  220. /// Check if a key is held down.
  221. /// @property
  222. bool GetKeyDown(Key key) const;
  223. /// Check if a key has been pressed on this frame.
  224. /// @property
  225. bool GetKeyPress(Key key) const;
  226. /// Check if a key is held down by scancode.
  227. /// @property
  228. bool GetScancodeDown(Scancode scancode) const;
  229. /// Check if a key has been pressed on this frame by scancode.
  230. /// @property
  231. bool GetScancodePress(Scancode scancode) const;
  232. /// Check if a mouse button is held down.
  233. /// @property
  234. bool GetMouseButtonDown(MouseButtonFlags button) const;
  235. /// Check if a mouse button has been pressed on this frame.
  236. /// @property
  237. bool GetMouseButtonPress(MouseButtonFlags button) const;
  238. /// Check if a qualifier key is held down.
  239. /// @property
  240. bool GetQualifierDown(Qualifier qualifier) const;
  241. /// Check if a qualifier key has been pressed on this frame.
  242. /// @property
  243. bool GetQualifierPress(Qualifier qualifier) const;
  244. /// Return the currently held down qualifiers.
  245. /// @property
  246. QualifierFlags GetQualifiers() const;
  247. /// Return mouse position within window. Should only be used with a visible mouse cursor. Uses the backbuffer (Graphics width/height) coordinates.
  248. /// @property
  249. IntVector2 GetMousePosition() const;
  250. /// Return mouse movement since last frame.
  251. /// @property
  252. IntVector2 GetMouseMove() const;
  253. /// Return horizontal mouse movement since last frame.
  254. /// @property
  255. int GetMouseMoveX() const;
  256. /// Return vertical mouse movement since last frame.
  257. /// @property
  258. int GetMouseMoveY() const;
  259. /// Return mouse wheel movement since last frame.
  260. /// @property
  261. int GetMouseMoveWheel() const { return mouseMoveWheel_; }
  262. /// Return input coordinate scaling. Should return non-unity on High DPI display.
  263. /// @property
  264. Vector2 GetInputScale() const { return inputScale_; }
  265. /// Return number of active finger touches.
  266. /// @property
  267. unsigned GetNumTouches() const { return touches_.Size(); }
  268. /// Return active finger touch by index.
  269. /// @property{get_touches}
  270. TouchState* GetTouch(unsigned index) const;
  271. /// Return number of connected joysticks.
  272. /// @property
  273. unsigned GetNumJoysticks() const { return joysticks_.Size(); }
  274. /// Return joystick state by ID, or null if does not exist.
  275. /// @property{get_joysticks}
  276. JoystickState* GetJoystick(SDL_JoystickID id);
  277. /// Return joystick state by index, or null if does not exist. 0 = first connected joystick.
  278. /// @property{get_joysticksByIndex}
  279. JoystickState* GetJoystickByIndex(unsigned index);
  280. /// Return joystick state by name, or null if does not exist.
  281. /// @property{get_joysticksByName}
  282. JoystickState* GetJoystickByName(const String& name);
  283. /// Return whether fullscreen toggle is enabled.
  284. /// @property
  285. bool GetToggleFullscreen() const { return toggleFullscreen_; }
  286. /// Return whether a virtual joystick is visible.
  287. /// @property
  288. bool IsScreenJoystickVisible(SDL_JoystickID id) const;
  289. /// Return whether on-screen keyboard is supported.
  290. /// @property
  291. bool GetScreenKeyboardSupport() const;
  292. /// Return whether on-screen keyboard is being shown.
  293. /// @property
  294. bool IsScreenKeyboardVisible() const;
  295. /// Return whether touch emulation is enabled.
  296. /// @property
  297. bool GetTouchEmulation() const { return touchEmulation_; }
  298. /// Return whether the operating system mouse cursor is visible.
  299. /// @property
  300. bool IsMouseVisible() const { return mouseVisible_; }
  301. /// Return whether the mouse is currently being grabbed by an operation.
  302. /// @property
  303. bool IsMouseGrabbed() const { return mouseGrabbed_; }
  304. /// Return whether the mouse is locked to the window.
  305. /// @property
  306. bool IsMouseLocked() const;
  307. /// Return the mouse mode.
  308. /// @property
  309. MouseMode GetMouseMode() const { return mouseMode_; }
  310. /// Return whether application window has input focus.
  311. /// @property{get_focus}
  312. bool HasFocus() { return inputFocus_; }
  313. /// Return whether application window is minimized.
  314. /// @property
  315. bool IsMinimized() const;
  316. private:
  317. /// Initialize when screen mode initially set.
  318. void Initialize();
  319. /// Open a joystick and return its ID. Return -1 if no joystick.
  320. SDL_JoystickID OpenJoystick(unsigned index);
  321. /// Setup internal joystick structures.
  322. void ResetJoysticks();
  323. /// Prepare input state for application gaining input focus.
  324. void GainFocus();
  325. /// Prepare input state for application losing input focus.
  326. void LoseFocus();
  327. /// Clear input state.
  328. void ResetState();
  329. /// Clear touch states and send touch end events.
  330. void ResetTouches();
  331. /// Reset input accumulation.
  332. void ResetInputAccumulation();
  333. /// Get the index of a touch based on the touch ID.
  334. unsigned GetTouchIndexFromID(int touchID);
  335. /// Used internally to return and remove the next available touch index.
  336. unsigned PopTouchIndex();
  337. /// Push a touch index back into the list of available when finished with it.
  338. void PushTouchIndex(int touchID);
  339. /// Send an input focus or window minimization change event.
  340. void SendInputFocusEvent();
  341. /// Handle a mouse button change.
  342. void SetMouseButton(MouseButton button, bool newState, int clicks);
  343. /// Handle a key change.
  344. void SetKey(Key key, Scancode scancode, bool newState);
  345. /// Handle mouse wheel change.
  346. void SetMouseWheel(int delta);
  347. /// Suppress next mouse movement.
  348. void SuppressNextMouseMove();
  349. /// Unsuppress mouse movement.
  350. void UnsuppressMouseMove();
  351. /// Handle screen mode event.
  352. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  353. /// Handle frame start event.
  354. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  355. /// Handle touch events from the controls of screen joystick(s).
  356. void HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData);
  357. /// Handle SDL event.
  358. void HandleSDLEvent(void* sdlEvent);
  359. #ifndef __EMSCRIPTEN__
  360. /// Set SDL mouse mode relative.
  361. void SetMouseModeRelative(SDL_bool enable);
  362. /// Set SDL mouse mode absolute.
  363. void SetMouseModeAbsolute(SDL_bool enable);
  364. #else
  365. /// Set whether the operating system mouse cursor is visible (Emscripten platform only).
  366. void SetMouseVisibleEmscripten(bool enable, bool suppressEvent = false);
  367. /// Set mouse mode final resolution (Emscripten platform only).
  368. void SetMouseModeEmscriptenFinal(MouseMode mode, bool suppressEvent = false);
  369. /// SetMouseMode (Emscripten platform only).
  370. void SetMouseModeEmscripten(MouseMode mode, bool suppressEvent);
  371. /// Handle frame end event.
  372. void HandleEndFrame(StringHash eventType, VariantMap& eventData);
  373. #endif
  374. /// Graphics subsystem.
  375. WeakPtr<Graphics> graphics_;
  376. /// Key down state.
  377. HashSet<int> keyDown_;
  378. /// Key pressed state.
  379. HashSet<int> keyPress_;
  380. /// Key down state by scancode.
  381. HashSet<int> scancodeDown_;
  382. /// Key pressed state by scancode.
  383. HashSet<int> scancodePress_;
  384. /// Active finger touches.
  385. HashMap<int, TouchState> touches_;
  386. /// List that maps between event touch IDs and normalised touch IDs.
  387. List<int> availableTouchIDs_;
  388. /// Mapping of touch indices.
  389. HashMap<int, int> touchIDMap_;
  390. /// String for text input.
  391. String textInput_;
  392. /// Opened joysticks.
  393. HashMap<SDL_JoystickID, JoystickState> joysticks_;
  394. /// Mouse buttons' down state.
  395. MouseButtonFlags mouseButtonDown_;
  396. /// Mouse buttons' pressed state.
  397. MouseButtonFlags mouseButtonPress_;
  398. /// Last mouse position for calculating movement.
  399. IntVector2 lastMousePosition_;
  400. /// Last mouse position before being set to not visible.
  401. IntVector2 lastVisibleMousePosition_;
  402. /// Mouse movement since last frame.
  403. IntVector2 mouseMove_;
  404. /// Mouse wheel movement since last frame.
  405. int mouseMoveWheel_;
  406. /// Input coordinate scaling. Non-unity when window and backbuffer have different sizes (e.g. Retina display).
  407. Vector2 inputScale_;
  408. /// SDL window ID.
  409. unsigned windowID_;
  410. /// Fullscreen toggle flag.
  411. bool toggleFullscreen_;
  412. /// Operating system mouse cursor visible flag.
  413. bool mouseVisible_;
  414. /// The last operating system mouse cursor visible flag set by end use call to SetMouseVisible.
  415. bool lastMouseVisible_;
  416. /// Flag to indicate the mouse is being grabbed by an operation. Subsystems like UI that uses mouse should temporarily ignore the mouse hover or click events.
  417. bool mouseGrabbed_;
  418. /// The last mouse grabbed set by SetMouseGrabbed.
  419. bool lastMouseGrabbed_;
  420. /// Determines the mode of mouse behaviour.
  421. MouseMode mouseMode_;
  422. /// The last mouse mode set by SetMouseMode.
  423. MouseMode lastMouseMode_;
  424. #ifndef __EMSCRIPTEN__
  425. /// Flag to determine whether SDL mouse relative was used.
  426. bool sdlMouseRelative_;
  427. #endif
  428. /// Touch emulation mode flag.
  429. bool touchEmulation_;
  430. /// Input focus flag.
  431. bool inputFocus_;
  432. /// Minimized flag.
  433. bool minimized_;
  434. /// Gained focus on this frame flag.
  435. bool focusedThisFrame_;
  436. /// Next mouse move suppress flag.
  437. bool suppressNextMouseMove_;
  438. /// Whether mouse move is accumulated in backbuffer scale or not (when using events directly).
  439. bool mouseMoveScaled_;
  440. /// Initialized flag.
  441. bool initialized_;
  442. #ifdef __EMSCRIPTEN__
  443. /// Emscripten Input glue instance.
  444. UniquePtr<EmscriptenInput> emscriptenInput_;
  445. /// Flag used to detect mouse jump when exiting pointer-lock.
  446. bool emscriptenExitingPointerLock_;
  447. /// Flag used to detect mouse jump on initial mouse click when entering pointer-lock.
  448. bool emscriptenEnteredPointerLock_;
  449. /// Flag indicating current pointer-lock status.
  450. bool emscriptenPointerLock_;
  451. #endif
  452. };
  453. }