InputSystem.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #pragma once
  9. #include <SDL/SDL_scancode.h>
  10. #include "Math.h"
  11. // The different button states
  12. enum ButtonState
  13. {
  14. ENone,
  15. EPressed,
  16. EReleased,
  17. EHeld
  18. };
  19. // Helper for keyboard input
  20. class KeyboardState
  21. {
  22. public:
  23. // Friend so InputSystem can easily update it
  24. friend class InputSystem;
  25. // Get just the boolean true/false value of key
  26. bool GetKeyValue(int keyCode) const;
  27. // Get a state based on current and previous frame
  28. ButtonState GetKeyState(int keyCode) const;
  29. private:
  30. const Uint8* mCurrState;
  31. Uint8 mPrevState[SDL_NUM_SCANCODES];
  32. };
  33. // Helper for mouse input
  34. class MouseState
  35. {
  36. public:
  37. friend class InputSystem;
  38. // For mouse position
  39. const Vector2& GetPosition() const { return mMousePos; }
  40. const Vector2& GetScrollWheel() const { return mScrollWheel; }
  41. bool IsRelative() const { return mIsRelative; }
  42. // For buttons
  43. bool GetButtonValue(int button) const;
  44. ButtonState GetButtonState(int button) const;
  45. private:
  46. // Store current mouse position
  47. Vector2 mMousePos;
  48. // Motion of scroll wheel
  49. Vector2 mScrollWheel;
  50. // Store button data
  51. Uint32 mCurrButtons;
  52. Uint32 mPrevButtons;
  53. // Are we in relative mouse mode
  54. bool mIsRelative;
  55. };
  56. // Wrapper that contains current state of input
  57. struct InputState
  58. {
  59. KeyboardState Keyboard;
  60. MouseState Mouse;
  61. };
  62. class InputSystem
  63. {
  64. public:
  65. bool Initialize();
  66. void Shutdown();
  67. // Called right before SDL_PollEvents loop
  68. void PrepareForUpdate();
  69. // Called after SDL_PollEvents loop
  70. void Update();
  71. // Called to process an SDL event in input system
  72. void ProcessEvent(union SDL_Event& event);
  73. const InputState& GetState() const { return mState; }
  74. void SetRelativeMouseMode(bool value);
  75. private:
  76. InputState mState;
  77. };