Input.h 17 KB

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