1 /*
2     Input Handling Subsystem
3 
4     Copyright © 2020, Luna Nielsen
5     Distributed under the 2-Clause BSD License, see LICENSE file.
6     
7     Authors: Luna Nielsen
8 */
9 module engine.input;
10 import bindbc.glfw;
11 
12 public import engine.input.keyboard;
13 public import engine.input.mouse;
14 
15 /**
16     Initializes input system
17 */
18 void initInput(GLFWwindow* window) {
19 
20     // Initialize keyboard
21     Keyboard.initialize(window);
22 
23     // Initialize mouse
24     Mouse.initialize(window);
25 }
26 
27 private struct Keybinding {
28     Key key;
29 
30     bool lstate;
31     bool state;
32 }
33 
34 class Input {
35 private static:
36     Keybinding*[string] keybindings;
37 
38 public static:
39 
40     /**
41         Register a key and a default binding for a keybinding
42     */
43     void registerKey(string name, Key binding) {
44         keybindings[name] = new Keybinding(binding, false, false);
45     }
46 
47     /**
48         Load keybindings from a list of bindings
49     */
50     void loadBindings(Key[string] bindings) {
51         foreach(name, binding; bindings) {
52             registerKey(name, binding);
53         }
54     }
55 
56     /**
57         Gets the key attached to a keybinding
58     */
59     Key getKeyFor(string name) {
60         return keybindings[name].key;
61     }
62 
63     /**
64         Whether a user pressed the specified binding button
65     */
66     bool isPressed(string name) {
67         return keybindings[name].state && keybindings[name].state != keybindings[name].lstate;
68     }
69 
70     /**
71         Whether a user pressed the specified binding button the last frame
72     */
73     bool wasPressed(string name) {
74         return !keybindings[name].state && keybindings[name].state != keybindings[name].lstate;
75     }
76 
77     /**
78         Whether a user pressed the specified binding button
79     */
80     bool isDown(string name) {
81         return keybindings[name].state;
82     }
83 
84     /**
85         Whether a user pressed the specified binding button
86     */
87     bool isUp(string name) {
88         return !keybindings[name].state;
89     }
90 
91     /**
92         Updates the keybinding states
93     */
94     void update() {
95 
96         // Update keybindings
97         foreach(binding; keybindings) {
98             binding.lstate = binding.state;
99             binding.state = Keyboard.isKeyPressed(binding.key);
100         }
101     }
102 }