Input.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Core/Mutex.h"
  25. #include "../Core/Object.h"
  26. #include "../Container/List.h"
  27. #include "../Input/InputEvents.h"
  28. #include "../UI/Cursor.h"
  29. namespace Urho3D
  30. {
  31. /// %Input Mouse Modes.
  32. enum MouseMode
  33. {
  34. MM_ABSOLUTE = 0,
  35. MM_RELATIVE,
  36. MM_WRAP,
  37. MM_FREE
  38. };
  39. class Deserializer;
  40. class Graphics;
  41. class Serializer;
  42. class UIElement;
  43. class XMLFile;
  44. const IntVector2 MOUSE_POSITION_OFFSCREEN = IntVector2(M_MIN_INT, M_MIN_INT);
  45. /// %Input state for a finger touch.
  46. struct TouchState
  47. {
  48. /// Return last touched UI element, used by scripting integration.
  49. UIElement* GetTouchedElement();
  50. /// Touch (finger) ID.
  51. int touchID_;
  52. /// Position in screen coordinates.
  53. IntVector2 position_;
  54. /// Last position in screen coordinates.
  55. IntVector2 lastPosition_;
  56. /// Movement since last frame.
  57. IntVector2 delta_;
  58. /// Finger pressure.
  59. float pressure_;
  60. /// Last touched UI element from screen joystick.
  61. WeakPtr<UIElement> touchedElement_;
  62. };
  63. /// %Input state for a joystick.
  64. struct JoystickState
  65. {
  66. /// Construct with defaults.
  67. JoystickState() :
  68. joystick_(0), controller_(0), screenJoystick_(0)
  69. {
  70. }
  71. /// Initialize the number of buttons, axes and hats and set them to neutral state.
  72. void Initialize(unsigned numButtons, unsigned numAxes, unsigned numHats);
  73. /// Reset button, axis and hat states to neutral.
  74. void Reset();
  75. /// Return whether is a game controller. Game controllers will use standardized axis and button mappings.
  76. bool IsController() const { return controller_ != 0; }
  77. /// Return number of buttons.
  78. unsigned GetNumButtons() const { return buttons_.Size(); }
  79. /// Return number of axes.
  80. unsigned GetNumAxes() const { return axes_.Size(); }
  81. /// Return number of hats.
  82. unsigned GetNumHats() const { return hats_.Size(); }
  83. /// Check if a button is held down.
  84. bool GetButtonDown(unsigned index) const { return index < buttons_.Size() ? buttons_[index] : false; }
  85. /// Check if a button has been pressed on this frame.
  86. bool GetButtonPress(unsigned index) const { return index < buttonPress_.Size() ? buttonPress_[index] : false; }
  87. /// Return axis position.
  88. float GetAxisPosition(unsigned index) const { return index < axes_.Size() ? axes_[index] : 0.0f; }
  89. /// Return hat position.
  90. int GetHatPosition(unsigned index) const { return index < hats_.Size() ? hats_[index] : HAT_CENTER; }
  91. /// SDL joystick.
  92. SDL_Joystick* joystick_;
  93. /// SDL joystick instance ID.
  94. SDL_JoystickID joystickID_;
  95. /// SDL game controller.
  96. SDL_GameController* controller_;
  97. /// UI element containing the screen joystick.
  98. UIElement* screenJoystick_;
  99. /// Joystick name.
  100. String name_;
  101. /// Button up/down state.
  102. PODVector<bool> buttons_;
  103. /// Button pressed on this frame.
  104. PODVector<bool> buttonPress_;
  105. /// Axis position from -1 to 1.
  106. PODVector<float> axes_;
  107. /// POV hat bits.
  108. PODVector<int> hats_;
  109. };
  110. #ifdef __EMSCRIPTEN__
  111. class EmscriptenInput;
  112. #endif
  113. /// %Input subsystem. Converts operating system window messages to input state and events.
  114. class URHO3D_API Input : public Object
  115. {
  116. URHO3D_OBJECT(Input, Object);
  117. #ifdef __EMSCRIPTEN__
  118. friend class EmscriptenInput;
  119. #endif
  120. public:
  121. /// Construct.
  122. Input(Context* context);
  123. /// Destruct.
  124. virtual ~Input();
  125. /// Poll for window messages. Called by HandleBeginFrame().
  126. void Update();
  127. /// Set whether ALT-ENTER fullscreen toggle is enabled.
  128. void SetToggleFullscreen(bool enable);
  129. /// 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().
  130. void SetMouseVisible(bool enable, bool suppressEvent = false);
  131. /// Reset last mouse visibility that was not suppressed in SetMouseVisible.
  132. void ResetMouseVisible();
  133. /// Set whether the mouse is currently being grabbed by an operation.
  134. void SetMouseGrabbed(bool grab);
  135. /// Set the mouse mode.
  136. /** Set the mouse mode behaviour.
  137. * MM_ABSOLUTE is the default behaviour, allowing the toggling of operating system cursor visibility and allowing the cursor to escape the window when visible.
  138. * When the operating system cursor is invisible in absolute mouse mode, the mouse is confined to the window.
  139. * 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).
  140. * SetMouseMode(MM_ABSOLUTE) will call SetMouseGrabbed(false).
  141. *
  142. * MM_RELATIVE sets the operating system cursor to invisible and confines the cursor to the window.
  143. * 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.
  144. * When the virtual cursor is also invisible, UI interaction will still function as normal (eg: drag events will trigger).
  145. * SetMouseMode(MM_RELATIVE) will call SetMouseGrabbed(true).
  146. *
  147. * 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.
  148. * SetMouseMode(MM_WRAP) will call SetMouseGrabbed(true).
  149. *
  150. * 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
  151. * outside the window, and perform custom rendering (with SetMouseVisible(false)) inside.
  152. */
  153. void SetMouseMode(MouseMode mode);
  154. /// Add screen joystick.
  155. /** Return the joystick instance ID when successful or negative on error.
  156. * If layout file is not given, use the default screen joystick layout.
  157. * If style file is not given, use the default style file from root UI element.
  158. *
  159. * This method should only be called in main thread.
  160. */
  161. SDL_JoystickID AddScreenJoystick(XMLFile* layoutFile = 0, XMLFile* styleFile = 0);
  162. /// Remove screen joystick by instance ID.
  163. /** Return true if successful.
  164. *
  165. * This method should only be called in main thread.
  166. */
  167. bool RemoveScreenJoystick(SDL_JoystickID id);
  168. /// Set whether the virtual joystick is visible.
  169. void SetScreenJoystickVisible(SDL_JoystickID id, bool enable);
  170. /// Show or hide on-screen keyboard on platforms that support it. When shown, keypresses from it are delivered as key events.
  171. void SetScreenKeyboardVisible(bool enable);
  172. /// 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.
  173. void SetTouchEmulation(bool enable);
  174. /// 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.
  175. bool RecordGesture();
  176. /// Save all in-memory touch gestures. Return true if successful.
  177. bool SaveGestures(Serializer& dest);
  178. /// Save a specific in-memory touch gesture to a file. Return true if successful.
  179. bool SaveGesture(Serializer& dest, unsigned gestureID);
  180. /// Load touch gestures from a file. Return number of loaded gestures, or 0 on failure.
  181. unsigned LoadGestures(Deserializer& source);
  182. /// Remove an in-memory gesture by ID. Return true if was found.
  183. bool RemoveGesture(unsigned gestureID);
  184. /// Remove all in-memory gestures.
  185. void RemoveAllGestures();
  186. /// Return keycode from key name.
  187. int GetKeyFromName(const String& name) const;
  188. /// Return keycode from scancode.
  189. int GetKeyFromScancode(int scancode) const;
  190. /// Return name of key from keycode.
  191. String GetKeyName(int key) const;
  192. /// Return scancode from keycode.
  193. int GetScancodeFromKey(int key) const;
  194. /// Return scancode from key name.
  195. int GetScancodeFromName(const String& name) const;
  196. /// Return name of key from scancode.
  197. String GetScancodeName(int scancode) const;
  198. /// Check if a key is held down.
  199. bool GetKeyDown(int key) const;
  200. /// Check if a key has been pressed on this frame.
  201. bool GetKeyPress(int key) const;
  202. /// Check if a key is held down by scancode.
  203. bool GetScancodeDown(int scancode) const;
  204. /// Check if a key has been pressed on this frame by scancode.
  205. bool GetScancodePress(int scancode) const;
  206. /// Check if a mouse button is held down.
  207. bool GetMouseButtonDown(int button) const;
  208. /// Check if a mouse button has been pressed on this frame.
  209. bool GetMouseButtonPress(int button) const;
  210. /// Check if a qualifier key is held down.
  211. bool GetQualifierDown(int qualifier) const;
  212. /// Check if a qualifier key has been pressed on this frame.
  213. bool GetQualifierPress(int qualifier) const;
  214. /// Return the currently held down qualifiers.
  215. int GetQualifiers() const;
  216. /// Return mouse position within window. Should only be used with a visible mouse cursor.
  217. IntVector2 GetMousePosition() const;
  218. /// Return mouse movement since last frame.
  219. const IntVector2& GetMouseMove() const { return mouseMove_; }
  220. /// Return horizontal mouse movement since last frame.
  221. int GetMouseMoveX() const { return mouseMove_.x_; }
  222. /// Return vertical mouse movement since last frame.
  223. int GetMouseMoveY() const { return mouseMove_.y_; }
  224. /// Return mouse wheel movement since last frame.
  225. int GetMouseMoveWheel() const { return mouseMoveWheel_; }
  226. /// Return number of active finger touches.
  227. unsigned GetNumTouches() const { return touches_.Size(); }
  228. /// Return active finger touch by index.
  229. TouchState* GetTouch(unsigned index) const;
  230. /// Return number of connected joysticks.
  231. unsigned GetNumJoysticks() const { return joysticks_.Size(); }
  232. /// Return joystick state by ID, or null if does not exist.
  233. JoystickState* GetJoystick(SDL_JoystickID id);
  234. /// Return joystick state by index, or null if does not exist. 0 = first connected joystick.
  235. JoystickState* GetJoystickByIndex(unsigned index);
  236. /// Return whether fullscreen toggle is enabled.
  237. bool GetToggleFullscreen() const { return toggleFullscreen_; }
  238. /// Return whether a virtual joystick is visible.
  239. bool IsScreenJoystickVisible(SDL_JoystickID id) const;
  240. /// Return whether on-screen keyboard is supported.
  241. bool GetScreenKeyboardSupport() const;
  242. /// Return whether on-screen keyboard is being shown.
  243. bool IsScreenKeyboardVisible() const;
  244. /// Return whether touch emulation is enabled.
  245. bool GetTouchEmulation() const { return touchEmulation_; }
  246. /// Return whether the operating system mouse cursor is visible.
  247. bool IsMouseVisible() const { return mouseVisible_; }
  248. /// Return whether the mouse is currently being grabbed by an operation.
  249. bool IsMouseGrabbed() const { return mouseGrabbed_; }
  250. /// Return the mouse mode.
  251. MouseMode GetMouseMode() const { return mouseMode_; }
  252. /// Return whether application window has input focus.
  253. bool HasFocus() { return inputFocus_; }
  254. /// Return whether application window is minimized.
  255. bool IsMinimized() const;
  256. private:
  257. /// Initialize when screen mode initially set.
  258. void Initialize();
  259. /// Open a joystick and return its ID. Return -1 if no joystick.
  260. SDL_JoystickID OpenJoystick(unsigned index);
  261. /// Setup internal joystick structures.
  262. void ResetJoysticks();
  263. /// Prepare input state for application gaining input focus.
  264. void GainFocus();
  265. /// Prepare input state for application losing input focus.
  266. void LoseFocus();
  267. /// Clear input state.
  268. void ResetState();
  269. /// Clear touch states and send touch end events.
  270. void ResetTouches();
  271. /// Get the index of a touch based on the touch ID.
  272. unsigned GetTouchIndexFromID(int touchID);
  273. /// Used internally to return and remove the next available touch index.
  274. unsigned PopTouchIndex();
  275. /// Push a touch index back into the list of available when finished with it.
  276. void PushTouchIndex(int touchID);
  277. /// Send an input focus or window minimization change event.
  278. void SendInputFocusEvent();
  279. /// Handle a mouse button change.
  280. void SetMouseButton(int button, bool newState);
  281. /// Handle a key change.
  282. void SetKey(int key, int scancode, unsigned raw, bool newState);
  283. #ifdef __EMSCRIPTEN__
  284. /// Set whether the operating system mouse cursor is visible (Emscripten platform only).
  285. void SetMouseVisibleEmscripten(bool enable);
  286. /// Set mouse mode (Emscripten platform only).
  287. void SetMouseModeEmscripten(MouseMode mode);
  288. #endif
  289. /// Handle mouse wheel change.
  290. void SetMouseWheel(int delta);
  291. /// Internal function to set the mouse cursor position.
  292. void SetMousePosition(const IntVector2& position);
  293. /// Handle screen mode event.
  294. void HandleScreenMode(StringHash eventType, VariantMap& eventData);
  295. /// Handle frame start event.
  296. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  297. /// Handle touch events from the controls of screen joystick(s).
  298. void HandleScreenJoystickTouch(StringHash eventType, VariantMap& eventData);
  299. /// Handle SDL event.
  300. void HandleSDLEvent(void* sdlEvent);
  301. /// Graphics subsystem.
  302. WeakPtr<Graphics> graphics_;
  303. /// Key down state.
  304. HashSet<int> keyDown_;
  305. /// Key pressed state.
  306. HashSet<int> keyPress_;
  307. /// Key down state by scancode.
  308. HashSet<int> scancodeDown_;
  309. /// Key pressed state by scancode.
  310. HashSet<int> scancodePress_;
  311. /// Active finger touches.
  312. HashMap<int, TouchState> touches_;
  313. /// List that maps between event touch IDs and normalised touch IDs
  314. List<int> availableTouchIDs_;
  315. /// Mapping of touch indices
  316. HashMap<int, int> touchIDMap_;
  317. /// String for text input.
  318. String textInput_;
  319. /// Opened joysticks.
  320. HashMap<SDL_JoystickID, JoystickState> joysticks_;
  321. /// Mouse buttons' down state.
  322. unsigned mouseButtonDown_;
  323. /// Mouse buttons' pressed state.
  324. unsigned mouseButtonPress_;
  325. /// Last mouse position for calculating movement.
  326. IntVector2 lastMousePosition_;
  327. /// Last mouse position before being set to not visible.
  328. IntVector2 lastVisibleMousePosition_;
  329. /// Mouse movement since last frame.
  330. IntVector2 mouseMove_;
  331. /// Mouse wheel movement since last frame.
  332. int mouseMoveWheel_;
  333. /// SDL window ID.
  334. unsigned windowID_;
  335. /// Fullscreen toggle flag.
  336. bool toggleFullscreen_;
  337. /// Operating system mouse cursor visible flag.
  338. bool mouseVisible_;
  339. /// The last operating system mouse cursor visible flag set by end use call to SetMouseVisible.
  340. bool lastMouseVisible_;
  341. /// 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.
  342. bool mouseGrabbed_;
  343. /// Determines the mode of mouse behaviour.
  344. MouseMode mouseMode_;
  345. /// Touch emulation mode flag.
  346. bool touchEmulation_;
  347. /// Input focus flag.
  348. bool inputFocus_;
  349. /// Minimized flag.
  350. bool minimized_;
  351. /// Gained focus on this frame flag.
  352. bool focusedThisFrame_;
  353. /// Next mouse move suppress flag.
  354. bool suppressNextMouseMove_;
  355. /// Handling a window resize event flag.
  356. bool inResize_;
  357. /// Flag for automatic focus (without click inside window) after screen mode change, needed on Linux.
  358. bool screenModeChanged_;
  359. /// Initialized flag.
  360. bool initialized_;
  361. #ifdef __EMSCRIPTEN__
  362. /// Emscripten Input glue instance.
  363. EmscriptenInput* emscriptenInput_;
  364. /// Flag used to detect mouse jump when exiting pointer lock.
  365. bool emscriptenExitingPointerLock_;
  366. /// Flag used to detect mouse jump on initial mouse click when entering pointer lock.
  367. bool emscriptenEnteredPointerLock_;
  368. #endif
  369. };
  370. }