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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use hashbrown::{HashMap, HashSet};

use crate::math::Vec2;
use crate::Context;

pub(crate) struct GamepadState {
    pub platform_id: u32,
    pub buttons_down: HashSet<GamepadButton>,
    pub buttons_pressed: HashSet<GamepadButton>,
    pub buttons_released: HashSet<GamepadButton>,
    pub current_axis_state: HashMap<GamepadAxis, f32>,
}

impl GamepadState {
    pub(crate) fn new(platform_id: u32) -> GamepadState {
        GamepadState {
            platform_id,
            buttons_down: HashSet::new(),
            buttons_pressed: HashSet::new(),
            buttons_released: HashSet::new(),
            current_axis_state: HashMap::new(),
        }
    }

    pub(crate) fn set_button_down(&mut self, btn: GamepadButton) -> bool {
        let was_up = self.buttons_down.insert(btn);

        if was_up {
            self.buttons_pressed.insert(btn);
        }

        was_up
    }

    pub(crate) fn set_button_up(&mut self, btn: GamepadButton) -> bool {
        let was_down = self.buttons_down.remove(&btn);

        if was_down {
            self.buttons_released.insert(btn);
        }

        was_down
    }

    pub(crate) fn set_axis_position(&mut self, axis: GamepadAxis, value: f32) {
        self.current_axis_state.insert(axis, value);
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[allow(missing_docs)]
/// A button on a gamepad.
///
/// # Serde
///
/// Serialization and deserialization of this type (via [Serde](https://serde.rs/))
/// can be enabled via the `serde_support` feature.
pub enum GamepadButton {
    A,
    B,
    X,
    Y,
    Up,
    Down,
    Left,
    Right,
    LeftShoulder,
    LeftTrigger,
    LeftStick,
    RightShoulder,
    RightTrigger,
    RightStick,
    Start,
    Back,
    Guide,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[allow(missing_docs)]
/// An axis of movement on a gamepad.
///
/// # Serde
///
/// Serialization and deserialization of this type (via [Serde](https://serde.rs/))
/// can be enabled via the `serde_support` feature.
pub enum GamepadAxis {
    LeftStickX,
    LeftStickY,
    LeftTrigger,
    RightStickX,
    RightStickY,
    RightTrigger,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde_support",
    derive(serde::Serialize, serde::Deserialize)
)]
#[allow(missing_docs)]
/// A control stick on a gamepad.
///
/// # Serde
///
/// Serialization and deserialization of this type (via [Serde](https://serde.rs/))
/// can be enabled via the `serde_support` feature.
pub enum GamepadStick {
    LeftStick,
    RightStick,
}

/// Returns true if the specified gamepad is currently connected.
pub fn is_gamepad_connected(ctx: &Context, gamepad_id: usize) -> bool {
    get_gamepad(ctx, gamepad_id).is_some()
}

/// Returns the name of the specified gamepad, or `None` if it is not connected.
pub fn get_gamepad_name(ctx: &Context, gamepad_id: usize) -> Option<String> {
    get_gamepad(ctx, gamepad_id)
        .map(|g| g.platform_id)
        .map(|id| ctx.window.get_gamepad_name(id))
}

/// Returns true if the specified gamepad button is currently down.
///
/// If the gamepad is disconnected, this will always return `false`.
pub fn is_gamepad_button_down(ctx: &Context, gamepad_id: usize, button: GamepadButton) -> bool {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        pad.buttons_down.contains(&button)
    } else {
        false
    }
}

/// Returns true if the specified gamepad button is currently up.
///
/// If the gamepad is disconnected, this will always return `true`.
pub fn is_gamepad_button_up(ctx: &Context, gamepad_id: usize, button: GamepadButton) -> bool {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        !pad.buttons_down.contains(&button)
    } else {
        true
    }
}

/// Returns true if the specified gamepad button was pressed since the last update.
///
/// If the gamepad is disconnected, this will always return `false`.
pub fn is_gamepad_button_pressed(ctx: &Context, gamepad_id: usize, button: GamepadButton) -> bool {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        pad.buttons_pressed.contains(&button)
    } else {
        false
    }
}

/// Returns true if the specified gamepad button was released since the last update.
///
/// If the gamepad is disconnected, this will always return `false`.
pub fn is_gamepad_button_released(ctx: &Context, gamepad_id: usize, button: GamepadButton) -> bool {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        pad.buttons_released.contains(&button)
    } else {
        false
    }
}

enum GamepadIterator<T> {
    Disconnected,
    Connected(T),
}

impl<T> Iterator for GamepadIterator<T>
where
    T: Iterator,
{
    type Item = T::Item;

    fn next(&mut self) -> Option<T::Item> {
        match self {
            GamepadIterator::Disconnected => None,
            GamepadIterator::Connected(i) => i.next(),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            GamepadIterator::Disconnected => (0, Some(0)),
            GamepadIterator::Connected(i) => i.size_hint(),
        }
    }
}

/// Returns an iterator of the buttons that are currently down on the specified gamepad.
///
/// If the gamepad is disconnected, an empty iterator will be returned.
pub fn get_gamepad_buttons_down(
    ctx: &Context,
    gamepad_id: usize,
) -> impl Iterator<Item = &GamepadButton> {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        GamepadIterator::Connected(pad.buttons_down.iter())
    } else {
        GamepadIterator::Disconnected
    }
}

/// Returns an iterator of the buttons that were pressed on the specified gamepad since the last update.
///
/// If the gamepad is disconnected, an empty iterator will be returned.
pub fn get_gamepad_buttons_pressed(
    ctx: &Context,
    gamepad_id: usize,
) -> impl Iterator<Item = &GamepadButton> {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        GamepadIterator::Connected(pad.buttons_pressed.iter())
    } else {
        GamepadIterator::Disconnected
    }
}

/// Returns an iterator of the buttons that were released on the specified gamepad since the last update .
///
/// If the gamepad is disconnected, an empty iterator will be returned.
pub fn get_gamepad_buttons_released(
    ctx: &Context,
    gamepad_id: usize,
) -> impl Iterator<Item = &GamepadButton> {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        GamepadIterator::Connected(pad.buttons_released.iter())
    } else {
        GamepadIterator::Disconnected
    }
}

/// Returns the current position of the specified gamepad axis.
///
/// If the gamepad is disconnected, this will always return `0.0`.
pub fn get_gamepad_axis_position(ctx: &Context, gamepad_id: usize, axis: GamepadAxis) -> f32 {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        if let Some(value) = pad.current_axis_state.get(&axis) {
            *value
        } else {
            0.0
        }
    } else {
        0.0
    }
}

/// Returns the current position of the specified gamepad control stick.
///
/// If the gamepad is disconnected, this will always return `(0.0, 0.0)`.
pub fn get_gamepad_stick_position(
    ctx: &Context,
    gamepad_id: usize,
    stick: GamepadStick,
) -> Vec2<f32> {
    let (x_axis, y_axis) = match stick {
        GamepadStick::LeftStick => (GamepadAxis::LeftStickX, GamepadAxis::LeftStickY),
        GamepadStick::RightStick => (GamepadAxis::RightStickX, GamepadAxis::RightStickY),
    };

    Vec2::new(
        get_gamepad_axis_position(ctx, gamepad_id, x_axis),
        get_gamepad_axis_position(ctx, gamepad_id, y_axis),
    )
}

/// Returns true if the specified gamepad supports vibration.
///
/// If the gamepad is disconnected, this will always return `false`.
pub fn is_gamepad_vibration_supported(ctx: &Context, gamepad_id: usize) -> bool {
    if let Some(pad) = get_gamepad(ctx, gamepad_id) {
        ctx.window.is_gamepad_vibration_supported(pad.platform_id)
    } else {
        false
    }
}

/// Sets the specified gamepad's motors to vibrate indefinitely.
pub fn set_gamepad_vibration(ctx: &mut Context, gamepad_id: usize, strength: f32) {
    if let Some(platform_id) = get_gamepad(ctx, gamepad_id).map(|g| g.platform_id) {
        ctx.window.set_gamepad_vibration(platform_id, strength);
    }
}

/// Sets the specified gamepad's motors to vibrate for a set duration, specified in milliseconds.
/// After this time has passed, the vibration will automatically stop.
pub fn start_gamepad_vibration(ctx: &mut Context, gamepad_id: usize, strength: f32, duration: u32) {
    if let Some(platform_id) = get_gamepad(ctx, gamepad_id).map(|g| g.platform_id) {
        ctx.window
            .start_gamepad_vibration(platform_id, strength, duration);
    }
}

/// Stops the specified gamepad's motors from vibrating.
pub fn stop_gamepad_vibration(ctx: &mut Context, gamepad_id: usize) {
    if let Some(platform_id) = get_gamepad(ctx, gamepad_id).map(|g| g.platform_id) {
        ctx.window.stop_gamepad_vibration(platform_id);
    }
}

pub(crate) fn add_gamepad(ctx: &mut Context, platform_id: u32) -> usize {
    for (i, slot) in ctx.input.pads.iter_mut().enumerate() {
        if slot.is_none() {
            *slot = Some(GamepadState::new(platform_id));
            return i;
        }
    }

    // There wasn't an existing free slot...
    let i = ctx.input.pads.len();
    ctx.input.pads.push(Some(GamepadState::new(platform_id)));
    i
}

pub(crate) fn remove_gamepad(ctx: &mut Context, gamepad_id: usize) {
    ctx.input.pads[gamepad_id] = None;
}

pub(crate) fn get_gamepad(ctx: &Context, gamepad_id: usize) -> Option<&GamepadState> {
    if let Some(Some(pad)) = ctx.input.pads.get(gamepad_id) {
        Some(pad)
    } else {
        None
    }
}

pub(crate) fn get_gamepad_mut(ctx: &mut Context, gamepad_id: usize) -> Option<&mut GamepadState> {
    if let Some(Some(pad)) = ctx.input.pads.get_mut(gamepad_id) {
        Some(pad)
    } else {
        None
    }
}