Input.h 19 KB

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