sim_logic/application/input/
pointer.rs1use std::{
4 error::Error,
5 fmt,
6 hash::{Hash, Hasher},
7};
8
9use sim_engine::{Camera2d, Camera2dError, LogicalScreenPosition, LogicalViewport, Vec2};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum MouseButton {
15 Left,
17 Right,
19 Middle,
21}
22
23pub(super) const ALL_MOUSE_BUTTONS: [MouseButton; 3] =
24 [MouseButton::Left, MouseButton::Right, MouseButton::Middle];
25
26pub(super) const fn mouse_button_index(button: MouseButton) -> usize {
27 match button {
28 MouseButton::Left => 0,
29 MouseButton::Right => 1,
30 MouseButton::Middle => 2,
31 }
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct DuplicateMouseBinding {
37 pub(super) button: MouseButton,
38}
39
40impl DuplicateMouseBinding {
41 pub const fn button(self) -> MouseButton {
43 self.button
44 }
45}
46
47impl fmt::Display for DuplicateMouseBinding {
48 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(formatter, "mouse button {:?} is already bound", self.button)
50 }
51}
52
53impl Error for DuplicateMouseBinding {}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct PointerSampleError;
58
59impl fmt::Display for PointerSampleError {
60 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61 formatter.write_str("pointer coordinates must be finite logical pixels")
62 }
63}
64
65impl Error for PointerSampleError {}
66
67#[derive(Debug, Clone, Copy, PartialEq)]
74pub struct PointerSample {
75 position: LogicalScreenPosition,
76 viewport: LogicalViewport,
77}
78
79impl PointerSample {
80 pub fn new(
85 position: LogicalScreenPosition,
86 viewport: LogicalViewport,
87 ) -> Result<Self, PointerSampleError> {
88 if !position.is_finite() {
89 return Err(PointerSampleError);
90 }
91 Ok(Self { position, viewport })
92 }
93
94 pub const fn position(self) -> LogicalScreenPosition {
96 self.position
97 }
98
99 pub const fn viewport(self) -> LogicalViewport {
101 self.viewport
102 }
103
104 pub(crate) fn is_inside_viewport(self) -> bool {
105 let point = self.position.to_vec2();
106 point.x() >= 0.0
107 && point.y() >= 0.0
108 && point.x() < self.viewport.width()
109 && point.y() < self.viewport.height()
110 }
111
112 pub fn world_position(self, camera: Camera2d) -> Result<Vec2, Camera2dError> {
118 camera.screen_to_world(self.position, self.viewport)
119 }
120}
121
122impl Eq for PointerSample {}
125
126impl Hash for PointerSample {
127 fn hash<H: Hasher>(&self, state: &mut H) {
128 let position = self.position.to_vec2();
129 for value in [
130 position.x(),
131 position.y(),
132 self.viewport.width(),
133 self.viewport.height(),
134 ] {
135 let bits = if value == 0.0 { 0 } else { value.to_bits() };
136 bits.hash(state);
137 }
138 }
139}