1 /*
2     Copyright © 2020, Luna Nielsen
3     Distributed under the 2-Clause BSD License, see LICENSE file.
4     
5     Authors: Luna Nielsen
6 */
7 module engine.input.mouse;
8 import engine.input;
9 import bindbc.glfw;
10 import gl3n.linalg;
11 
12 /**
13     The buttons on a mouse
14 */
15 enum MouseButton {
16     Left = GLFW_MOUSE_BUTTON_LEFT,
17     Middle = GLFW_MOUSE_BUTTON_MIDDLE,
18     Right = GLFW_MOUSE_BUTTON_RIGHT
19 }
20 
21 /**
22     Mouse
23 */
24 class Mouse {
25 private static:
26     GLFWwindow* window;
27 
28     bool[MouseButton] lastState;
29 
30 public static:
31 
32     /**
33         Constructs the underlying data needed
34     */
35     void initialize(GLFWwindow* window) {
36         this.window = window;
37     }
38 
39     /**
40         Gets mouse position
41     */
42     vec2 position() {
43         double x, y;
44         glfwGetCursorPos(window, &x, &y);
45         return vec2(cast(float)x, cast(float)y);
46     }
47 
48     /**
49         Gets if a mouse button is pressed
50     */
51     bool isButtonPressed(MouseButton button) {
52         return glfwGetMouseButton(window, button) == GLFW_PRESS;
53     }
54 
55     /**
56         Gets if a mouse button is released
57     */
58     bool isButtonReleased(MouseButton button) {
59         return glfwGetMouseButton(window, button) == GLFW_RELEASE;
60     }
61 
62     /**
63         Gets whether the button was clicked
64     */
65     bool isButtonClicked(MouseButton button) {
66         return !lastState[button] && isButtonPressed(button);
67     }
68 
69     /**
70         Gets whether the button was clicked
71     */
72     bool isButtonUnclicked(MouseButton button) {
73         return lastState[button] && isButtonReleased(button);
74     }
75 
76     /**
77         Updates the mouse state for single-clicking
78     */
79     void update() {
80         lastState[MouseButton.Left] = glfwGetMouseButton(window, MouseButton.Left) == GLFW_PRESS;
81         lastState[MouseButton.Middle] = glfwGetMouseButton(window, MouseButton.Middle) == GLFW_PRESS;
82         lastState[MouseButton.Right] = glfwGetMouseButton(window, MouseButton.Right) == GLFW_PRESS;
83     }
84 }