Kumo

A hand-rolled game engine.

git clone https://git.sentomk.me/Kumo.git

keyboard.h (1623B) · raw


      1 /// @file platform/keyboard.h
      2 /// @brief Tracks held keys and pending key presses.
      3 #pragma once
      4 
      5 #include <array>
      6 #include <limits>
      7 
      8 #include "core/types.h"
      9 
     10 namespace kumo {
     11 
     12 /// @brief Keys tracked by Keyboard. Count is a sentinel.
     13 enum class Key : uint8_t { Left, Right, Up, Down, Space, Count };
     14 
     15 /// @brief Stores the current key state and presses waiting for a tick.
     16 ///
     17 /// A press stays pending even if the key is released before the next tick.
     18 /// Key arguments must be one of Left, Right, Up, Down, or Space.
     19 class Keyboard {
     20  public:
     21   /// @brief Updates a key and records a press when it goes from up to down.
     22   void set_key(Key key, bool down) {
     23     State& state = keys_[static_cast<size_t>(key)];
     24     if (down && !state.down &&
     25         state.presses < std::numeric_limits<uint32_t>::max()) {
     26       ++state.presses;
     27     }
     28     state.down = down;
     29   }
     30 
     31   /// @brief Returns whether the key is currently held.
     32   bool is_down(Key key) const { return keys_[static_cast<size_t>(key)].down; }
     33 
     34   /// @brief Returns and clears the pending presses for the key.
     35   uint32_t take_presses(Key key) {
     36     State& state = keys_[static_cast<size_t>(key)];
     37     const uint32_t presses = state.presses;
     38     state.presses = 0;
     39     return presses;
     40   }
     41 
     42   /// @brief Releases all held keys and keeps pending presses.
     43   ///
     44   /// Call when the window loses keyboard focus.
     45   void release_all() {
     46     for (State& state : keys_) {
     47       state.down = false;
     48     }
     49   }
     50 
     51  private:
     52   struct State {
     53     bool down = false;
     54     uint32_t presses = 0;
     55   };
     56 
     57   std::array<State, static_cast<size_t>(Key::Count)> keys_{};
     58 };
     59 
     60 }  // namespace kumo