aboutsummaryrefslogtreecommitdiff
path: root/src/ctrl/keyboard.h
blob: 4f3b4ef63390d73cfe2ec63b2a235fd92471e8d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#ifndef CTRL_KEYBOARD_H
#define CTRL_KEYBOARD_H

#include <cstdint>
#include "math/vector.h"

using engine::math::Vector2;

namespace engine::controllers {

enum class KeyboardKey {
    fw,
    bw,
    key_left,
    key_right,
    zoom,
};

static constexpr std::size_t keyboard_key_count = 5;

template<typename KeyDownCallback, typename KeyUpCallback>
class Keyboard {
    public:
        constexpr Keyboard(KeyDownCallback key_down_cb, KeyUpCallback key_up_cb) :
            key_down_cb{key_down_cb}, key_up_cb{key_up_cb}, key_down_list{{{}}} {}

        void key_down_event(KeyboardKey key) {
            key_down_list[static_cast<std::size_t>(key) / (sizeof(std::size_t) * 8)]
                |= 1 << (static_cast<std::size_t>(key) % (sizeof(std::size_t) * 8));
            key_down_cb(key);
        }

        void key_up_event(KeyboardKey key) {
            key_down_list[static_cast<std::size_t>(key) / (sizeof(std::size_t) * 8)]
                &= ~(1 << (static_cast<std::size_t>(key) % (sizeof(std::size_t) * 8)));
            key_up_cb(key);
        }

        constexpr bool is_down(KeyboardKey key) const & {
            return (key_down_list[static_cast<std::size_t>(key) / (sizeof(std::size_t) * 8)]
                & (1 << (static_cast<std::size_t>(key) % (sizeof(std::size_t) * 8)))) != 0;
        }

    private:
        KeyDownCallback key_down_cb;
        KeyUpCallback key_up_cb;
        std::array<std::size_t, (keyboard_key_count + sizeof(std::size_t) * 8 - 1) / (sizeof(std::size_t) * 8)> key_down_list;
};

}

#endif // CTRL_KEYBOARD_H