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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//! Read inputs: touch pad, buttons, accelerometer.

use crate::{bindings as b, *};

const DPAD_THRESHOLD: i32 = 100;

/// A finger position on the touch pad.
///
/// Both x and y are somewhere the range between -1000 and 1000 (both ends included).
/// The 1000 x is on the right, the 1000 y is on the top.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct Pad {
    pub x: i32,
    pub y: i32,
}

impl Pad {
    pub const MAX: Pad = Pad { x: 1000, y: 1000 };
    pub const MIN: Pad = Pad { x: -1000, y: -1000 };

    /// Represent the pad values as a directional pad.
    #[must_use]
    pub fn as_dpad(&self) -> DPad {
        DPad {
            left:  self.x <= -DPAD_THRESHOLD,
            right: self.x >= DPAD_THRESHOLD,
            down:  self.y <= -DPAD_THRESHOLD,
            up:    self.y >= DPAD_THRESHOLD,
        }
    }

    /// The distance from the pad center to the touch point.
    #[must_use]
    pub fn radius(self) -> f32 {
        let r = self.x * self.x + self.y * self.y;
        #[allow(clippy::cast_precision_loss)]
        math::sqrt(r as f32)
    }

    /// The angle of the [polar coordinate] of the touch point.
    ///
    /// [polar coordinate]: https://en.wikipedia.org/wiki/Polar_coordinate_system
    #[must_use]
    pub fn azimuth(self) -> Angle {
        #[allow(clippy::cast_precision_loss)]
        let r = math::atan(self.y as f32 / self.x as f32);
        Angle::from_radians(r)
    }
}

impl From<Pad> for Point {
    fn from(value: Pad) -> Self {
        Self {
            x: value.x,
            y: value.y,
        }
    }
}

impl From<Point> for Pad {
    fn from(value: Point) -> Self {
        Self {
            x: value.x,
            y: value.y,
        }
    }
}

impl From<Pad> for Size {
    fn from(value: Pad) -> Self {
        Self {
            width:  value.x,
            height: value.y,
        }
    }
}

impl From<Size> for Pad {
    fn from(value: Size) -> Self {
        Self {
            x: value.width,
            y: value.height,
        }
    }
}

/// DPad-like representation of the [`Pad`].
///
/// Constructed with [`Pad::as_dpad`]. Useful for simple games and ports.
/// The middle of the pad is a "dead zone" pressing which will not activate any direction.
///
/// Invariant: it's not possible for opposite directions (left and right, or down and up)
/// to be active at the same time. However, it's possible for heighboring directions
/// (like up and right) to be active at the same time if the player presses a diagonal.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
pub struct DPad {
    pub left:  bool,
    pub right: bool,
    pub up:    bool,
    pub down:  bool,
}

impl From<Pad> for DPad {
    fn from(value: Pad) -> Self {
        value.as_dpad()
    }
}

impl DPad {
    /// Given the old state, get directions that were not pressed but are pressed now.
    #[must_use]
    pub fn just_pressed(&self, old: &Self) -> Self {
        Self {
            left:  self.left && !old.left,
            right: self.right && !old.right,
            up:    self.up && !old.up,
            down:  self.down && !old.down,
        }
    }

    /// Given the old state, get directions that were pressed but aren't pressed now.
    #[must_use]
    pub fn just_released(&self, old: &Self) -> Self {
        Self {
            left:  !self.left && old.left,
            right: !self.right && old.right,
            up:    !self.up && old.up,
            down:  !self.down && old.down,
        }
    }

    /// Given the old state, get directions that were pressed and are still pressed now.
    #[must_use]
    pub fn held(&self, old: &Self) -> Self {
        Self {
            left:  self.left && old.left,
            right: self.right && old.right,
            up:    self.up && old.up,
            down:  self.down && old.down,
        }
    }
}

/// State of the buttons.
#[derive(Default)]
pub struct Buttons {
    /// If `a` button is pressed.
    pub a:    bool,
    /// If `b` button is pressed.
    pub b:    bool,
    /// If `x` button is pressed.
    pub x:    bool,
    /// If `y` button is pressed.
    pub y:    bool,
    /// If `menu` button is pressed.
    ///
    /// For singleplayer games, the button press is always intercepted by the runtime.
    pub menu: bool,
}

impl Buttons {
    /// Check if any button is pressed.
    #[must_use]
    pub fn any(&self) -> bool {
        self.a || self.b || self.x || self.y || self.menu
    }

    /// Given the old state, get buttons that were not pressed but are pressed now.
    #[must_use]
    pub fn just_pressed(&self, old: &Self) -> Self {
        Self {
            a:    self.a && !old.a,
            b:    self.b && !old.b,
            x:    self.x && !old.x,
            y:    self.y && !old.y,
            menu: self.menu && !old.menu,
        }
    }

    /// Given the old state, get buttons that were pressed but aren't pressed now.
    #[must_use]
    pub fn just_released(&self, old: &Self) -> Self {
        Self {
            a:    !self.a && old.a,
            b:    !self.b && old.b,
            x:    !self.x && old.x,
            y:    !self.y && old.y,
            menu: !self.menu && old.menu,
        }
    }

    /// Given the old state, get buttons that were pressed but are still pressed now.
    #[must_use]
    pub fn held(&self, old: &Self) -> Self {
        Self {
            a:    self.a && old.a,
            b:    self.b && old.b,
            x:    self.x && old.x,
            y:    self.y && old.y,
            menu: self.menu && old.menu,
        }
    }
}

/// Get the current touch pad state.
///
/// In singleplayer game, the player ID doesn't matter.
#[must_use]
pub fn read_pad(player: Player) -> Option<Pad> {
    let raw = unsafe { b::read_pad(player.into()) };
    if raw == 0xffff {
        None
    } else {
        Some(Pad {
            x: i32::from((raw >> 16) as i16),
            y: i32::from(raw as i16),
        })
    }
}

/// Get the currently pressed buttons.
///
/// In singleplayer game, the player ID doesn't matter.
#[must_use]
pub fn read_buttons(player: Player) -> Buttons {
    let raw = unsafe { b::read_buttons(player.into()) };
    Buttons {
        a:    has_bit_set(raw, 0),
        b:    has_bit_set(raw, 1),
        x:    has_bit_set(raw, 2),
        y:    has_bit_set(raw, 3),
        menu: has_bit_set(raw, 4),
    }
}

/// Check if the given i32 value has the given bit set.
#[inline]
fn has_bit_set(val: u32, bit: usize) -> bool {
    (val >> bit) & 0b1 != 0
}