Skip to main content

repose_platform/
gamepad.rs

1//! Gamepad hardware backends.
2//!
3//! Platform-agnostic types live in [`repose_core::input`] (`GamepadEvent`,
4//! `GamepadButton`, `GamepadAxis`); UI routing lives in
5//! [`repose_app::ReposeRuntime::handle_gamepad`]. This module only feeds
6//! hardware into events. Backends implement [`GamepadBackend`]:
7//! - desktop (Linux/macOS/Windows) and web: gilrs driver (evdev / HID /
8//!   XInput-WGI / Web Gamepad API), `gamepad` feature.
9//! - android: [`AndroidBackend`] (non-joystick).
10
11#[cfg(feature = "gamepad")]
12use repose_core::input::{GamepadAxis, GamepadButton};
13use repose_core::input::{GamepadEvent, GamepadId};
14
15/// Hardware poller: drain pending events since the last call.
16pub trait GamepadBackend {
17    fn poll(&mut self) -> Vec<GamepadEvent>;
18    /// Start rumble on `id`. Returns `true` when the backend accepted it
19    /// (device connected + FF supported). Default: unsupported.
20    fn set_rumble(
21        &mut self,
22        _id: GamepadId,
23        _low_freq: f32,
24        _high_freq: f32,
25        _duration_ms: u32,
26    ) -> bool {
27        false
28    }
29    /// Stop any active rumble on `id`. Default: no-op.
30    fn stop_rumble(&mut self, _id: GamepadId) {}
31    /// Whether `id` currently supports rumble. Default: false.
32    fn is_rumble_supported(&self, _id: GamepadId) -> bool {
33        false
34    }
35}
36
37/// Stick deadzone applied by all backends before emitting axis events.
38#[cfg(any(all(feature = "gamepad", not(target_os = "android")), test))]
39pub const STICK_DEADZONE: f32 = 0.2;
40
41#[cfg(any(all(feature = "gamepad", not(target_os = "android")), test))]
42pub(crate) fn apply_stick_deadzone(v: f32) -> f32 {
43    if v.abs() < STICK_DEADZONE {
44        0.0
45    } else {
46        v.signum() * (v.abs() - STICK_DEADZONE) / (1.0 - STICK_DEADZONE)
47    }
48}
49
50/// Desktop backend driven by gilrs (its mapping database is the reference
51/// implementation; repose owns the types and routing above it).
52#[cfg(all(feature = "gamepad", not(target_os = "android")))]
53pub struct GilrsBackend {
54    gilrs: gilrs::Gilrs,
55    ff_effects: std::collections::HashMap<u32, gilrs::ff::Effect>,
56    /// Boot synthesis ran (see `poll`): pads already plugged in never
57    /// produce gilrs `Connected` events, so the first poll reports them.
58    boot_done: bool,
59}
60
61#[cfg(all(feature = "gamepad", not(target_os = "android")))]
62impl GilrsBackend {
63    pub fn new() -> Option<Self> {
64        match gilrs::Gilrs::new() {
65            Ok(gilrs) => Some(Self {
66                gilrs,
67                ff_effects: std::collections::HashMap::new(),
68                boot_done: false,
69            }),
70            Err(e) => {
71                log::warn!("gamepad: gilrs init failed ({e}); gamepad input disabled");
72                None
73            }
74        }
75    }
76
77    fn map_button(b: gilrs::Button) -> Option<GamepadButton> {
78        use gilrs::Button as G;
79        Some(match b {
80            G::South => GamepadButton::South,
81            G::East => GamepadButton::East,
82            G::West => GamepadButton::West,
83            G::North => GamepadButton::North,
84            G::Start => GamepadButton::Start,
85            G::Select => GamepadButton::Select,
86            G::LeftTrigger => GamepadButton::LeftShoulder,
87            G::RightTrigger => GamepadButton::RightShoulder,
88            G::LeftThumb => GamepadButton::LeftStick,
89            G::RightThumb => GamepadButton::RightStick,
90            G::DPadUp => GamepadButton::DPadUp,
91            G::DPadDown => GamepadButton::DPadDown,
92            G::DPadLeft => GamepadButton::DPadLeft,
93            G::DPadRight => GamepadButton::DPadRight,
94            _ => return None,
95        })
96    }
97
98    fn map_axis(a: gilrs::Axis) -> Option<GamepadAxis> {
99        use gilrs::Axis as G;
100        Some(match a {
101            G::LeftStickX => GamepadAxis::LeftStickX,
102            G::LeftStickY => GamepadAxis::LeftStickY,
103            G::RightStickX => GamepadAxis::RightStickX,
104            G::RightStickY => GamepadAxis::RightStickY,
105            _ => return None,
106        })
107    }
108}
109
110#[cfg(all(feature = "gamepad", not(target_os = "android")))]
111impl GamepadBackend for GilrsBackend {
112    fn poll(&mut self) -> Vec<GamepadEvent> {
113        use gilrs::EventType as E;
114        let mut out = Vec::new();
115        while let Some(ev) = self.gilrs.next_event() {
116            let id = GamepadId(usize::from(ev.id) as u32);
117            match ev.event {
118                E::Connected => {
119                    let pad = self.gilrs.gamepad(ev.id);
120                    let name = pad.name().to_string();
121                    let vendor_id = pad.vendor_id().unwrap_or(0);
122                    let product_id = pad.product_id().unwrap_or(0);
123                    out.push(GamepadEvent::Connected {
124                        id,
125                        name,
126                        vendor_id,
127                        product_id,
128                    });
129                }
130                E::Disconnected => out.push(GamepadEvent::Disconnected { id }),
131                E::ButtonPressed(b, _) | E::ButtonRepeated(b, _) => {
132                    if let Some(button) = Self::map_button(b) {
133                        out.push(GamepadEvent::Button {
134                            id,
135                            button,
136                            pressed: true,
137                        });
138                    }
139                }
140                E::ButtonReleased(b, _) => {
141                    if let Some(button) = Self::map_button(b) {
142                        out.push(GamepadEvent::Button {
143                            id,
144                            button,
145                            pressed: false,
146                        });
147                    }
148                }
149                E::ButtonChanged(b, v, _) => {
150                    let axis = match b {
151                        gilrs::Button::LeftTrigger2 => Some(GamepadAxis::LeftTrigger),
152                        gilrs::Button::RightTrigger2 => Some(GamepadAxis::RightTrigger),
153                        _ => None,
154                    };
155                    if let Some(axis) = axis {
156                        out.push(GamepadEvent::Axis {
157                            id,
158                            axis,
159                            value: v.clamp(0.0, 1.0),
160                        });
161                    }
162                }
163                E::AxisChanged(a, v, _) => {
164                    if let Some(axis) = Self::map_axis(a) {
165                        out.push(GamepadEvent::Axis {
166                            id,
167                            axis,
168                            value: apply_stick_deadzone(v),
169                        });
170                    }
171                }
172                E::Dropped | E::ForceFeedbackEffectCompleted => {}
173                _ => {}
174            }
175        }
176        if !self.boot_done {
177            self.boot_done = true;
178            let live: Vec<(GamepadId, String, u16, u16)> = self
179                .gilrs
180                .gamepads()
181                .map(|(gid, pad)| {
182                    (
183                        GamepadId(usize::from(gid) as u32),
184                        pad.name().to_string(),
185                        pad.vendor_id().unwrap_or(0),
186                        pad.product_id().unwrap_or(0),
187                    )
188                })
189                .collect();
190            let mut synth = synthesize_boot(live.into_iter(), &out);
191            synth.append(&mut out);
192            out = synth;
193        }
194        out
195    }
196
197    fn is_rumble_supported(&self, id: GamepadId) -> bool {
198        let want = id.0 as usize;
199        self.gilrs
200            .gamepads()
201            .find(|(gid, _)| usize::from(*gid) == want)
202            .map(|(_, pad)| pad.is_ff_supported())
203            .unwrap_or(false)
204    }
205
206    fn set_rumble(
207        &mut self,
208        id: GamepadId,
209        low_freq: f32,
210        high_freq: f32,
211        duration_ms: u32,
212    ) -> bool {
213        use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks};
214        let low = low_freq.clamp(0.0, 1.0);
215        let high = high_freq.clamp(0.0, 1.0);
216        if low <= 0.0 && high <= 0.0 {
217            self.stop_rumble(id);
218            return true;
219        }
220        let want = id.0 as usize;
221        let gid = match self
222            .gilrs
223            .gamepads()
224            .find(|(gid, _)| usize::from(*gid) == want)
225            .map(|(gid, _)| gid)
226        {
227            Some(g) => g,
228            None => return false,
229        };
230        if !self
231            .gilrs
232            .connected_gamepad(gid)
233            .map(|p| p.is_ff_supported())
234            .unwrap_or(false)
235        {
236            return false;
237        }
238        let duration = Ticks::from_ms(duration_ms.max(1));
239        let mut builder = EffectBuilder::new();
240        builder
241            .add_effect(BaseEffect {
242                kind: BaseEffectType::Strong {
243                    magnitude: (low * u16::MAX as f32) as u16,
244                },
245                scheduling: Replay {
246                    play_for: duration,
247                    ..Default::default()
248                },
249                ..Default::default()
250            })
251            .add_effect(BaseEffect {
252                kind: BaseEffectType::Weak {
253                    magnitude: (high * u16::MAX as f32) as u16,
254                },
255                scheduling: Replay {
256                    play_for: duration,
257                    ..Default::default()
258                },
259                ..Default::default()
260            })
261            .repeat(Repeat::For(duration))
262            .gamepads(&[gid]);
263        match builder.finish(&mut self.gilrs) {
264            Ok(effect) => {
265                let _ = effect.play();
266                self.ff_effects.insert(id.0, effect);
267                true
268            }
269            Err(e) => {
270                log::warn!("gamepad: rumble failed for pad {} ({e:?})", id.0);
271                false
272            }
273        }
274    }
275
276    fn stop_rumble(&mut self, id: GamepadId) {
277        if let Some(effect) = self.ff_effects.remove(&id.0) {
278            let _ = effect.stop();
279        }
280    }
281}
282
283/// Create the platform backend, or `None` when the `gamepad` feature is off.
284///
285/// One labeled arm per target (see module docs for the gilrs-Android swap).
286pub fn create_backend() -> Option<impl GamepadBackend> {
287    // Android: native-keycode backend (buttons via winit key path).
288    #[cfg(all(feature = "gamepad", target_os = "android"))]
289    {
290        AndroidBackend::new()
291    }
292    // Desktop + web: gilrs driver.
293    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
294    {
295        GilrsBackend::new()
296    }
297    #[cfg(not(feature = "gamepad"))]
298    {
299        None::<NoBackend>
300    }
301}
302
303/// Android backend constructor with a concrete return type (for runners
304/// that need [`AndroidBackend::key_button`], which is not on the trait).
305#[cfg(all(feature = "gamepad", target_os = "android"))]
306pub fn create_android_backend() -> Option<AndroidBackend> {
307    AndroidBackend::new()
308}
309
310/// Android controller backend: buttons arrive as native keycodes through
311/// winit (`Key::Unidentified(NativeKeyCode::Android(code))`  - winit maps
312/// `AKEYCODE_BUTTON_*` there deliberately), so there is nothing to poll;
313/// [`AndroidBackend::key_button`] translates at the key-event site.
314/// Sticks/triggers need a future Paddleboat/JNI driver on this trait.
315#[cfg(all(feature = "gamepad", target_os = "android"))]
316pub struct AndroidBackend {
317    connected: bool,
318}
319
320#[cfg(all(feature = "gamepad", target_os = "android"))]
321impl AndroidBackend {
322    pub fn new() -> Option<Self> {
323        Some(Self { connected: false })
324    }
325
326    /// Translate a native Android keycode press/release into gamepad events.
327    /// Emits a synthetic `Connected` (virtual pad id 0) on first sight.
328    /// NOTE: Since Android offers no hotplug event through winit, it returns empty
329    /// for non-controller codes so callers can fall through to keyboard.
330    pub fn key_button(&mut self, code: u32, pressed: bool) -> Vec<GamepadEvent> {
331        let Some(button) = android_code_to_button(code) else {
332            return Vec::new();
333        };
334        let mut out = Vec::with_capacity(2);
335        if !self.connected {
336            self.connected = true;
337            out.push(GamepadEvent::Connected {
338                id: GamepadId(0),
339                name: "Android controller".to_string(),
340                vendor_id: 0,
341                product_id: 0,
342            });
343        }
344        out.push(GamepadEvent::Button {
345            id: GamepadId(0),
346            button,
347            pressed,
348        });
349        out
350    }
351}
352
353#[cfg(all(feature = "gamepad", target_os = "android"))]
354impl GamepadBackend for AndroidBackend {
355    fn poll(&mut self) -> Vec<GamepadEvent> {
356        Vec::new()
357    }
358
359    fn set_rumble(
360        &mut self,
361        _id: GamepadId,
362        low_freq: f32,
363        high_freq: f32,
364        duration_ms: u32,
365    ) -> bool {
366        // Android has ONE device vibrator shared by every pad, so a
367        // per-pad request shakes the whole device; that is why Aurora
368        // exposes this as device-level haptics.
369        if duration_ms == 0 {
370            rlobkit_app_events::vibrator::stop();
371        } else {
372            rlobkit_app_events::vibrator::rumble(low_freq, high_freq, duration_ms);
373        }
374        true
375    }
376
377    fn stop_rumble(&mut self, _id: GamepadId) {
378        rlobkit_app_events::vibrator::stop();
379    }
380
381    fn is_rumble_supported(&self, _id: GamepadId) -> bool {
382        true
383    }
384}
385
386#[cfg(feature = "gamepad")]
387pub fn android_code_to_button(code: u32) -> Option<GamepadButton> {
388    Some(match code {
389        19 => GamepadButton::DPadUp,
390        20 => GamepadButton::DPadDown,
391        21 => GamepadButton::DPadLeft,
392        22 => GamepadButton::DPadRight,
393        23 => GamepadButton::South,          // DPAD_CENTER
394        96 => GamepadButton::South,          // BUTTON_A
395        97 => GamepadButton::East,           // BUTTON_B
396        99 => GamepadButton::West,           // BUTTON_X
397        100 => GamepadButton::North,         // BUTTON_Y
398        102 => GamepadButton::LeftShoulder,  // BUTTON_L1
399        103 => GamepadButton::RightShoulder, // BUTTON_R1
400        106 => GamepadButton::LeftStick,     // BUTTON_THUMBL
401        107 => GamepadButton::RightStick,    // BUTTON_THUMBR
402        108 => GamepadButton::Start,         // BUTTON_START
403        109 => GamepadButton::Select,        // BUTTON_SELECT
404        _ => return None,
405    })
406}
407
408/// First-poll boot synthesis, pure for tests: `Connected` per live
409/// device, skipping ids this poll already reported, enumeration order
410/// kept so device 0 sorts first for "Press Start" flows.
411#[cfg(all(feature = "gamepad", not(target_os = "android")))]
412fn synthesize_boot(
413    live: impl Iterator<Item = (GamepadId, String, u16, u16)>,
414    reported: &[GamepadEvent],
415) -> Vec<GamepadEvent> {
416    live.filter(|(id, _, _, _)| {
417        !reported
418            .iter()
419            .any(|ev| matches!(ev, GamepadEvent::Connected { id: eid, .. } if eid == id))
420    })
421    .map(
422        |(id, name, vendor_id, product_id)| GamepadEvent::Connected {
423            id,
424            name,
425            vendor_id,
426            product_id,
427        },
428    )
429    .collect()
430}
431
432/// Placeholder backend for targets without a driver yet.
433pub struct NoBackend;
434
435impl GamepadBackend for NoBackend {
436    fn poll(&mut self) -> Vec<GamepadEvent> {
437        Vec::new()
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    #[test]
445    fn stick_deadzone_snaps_and_rescales() {
446        assert_eq!(apply_stick_deadzone(0.0), 0.0);
447        assert_eq!(apply_stick_deadzone(0.19), 0.0);
448        assert_eq!(apply_stick_deadzone(-0.19), 0.0);
449        assert_eq!(apply_stick_deadzone(1.0), 1.0);
450        assert_eq!(apply_stick_deadzone(-1.0), -1.0);
451        let mid = apply_stick_deadzone(0.6);
452        assert!((mid - 0.5).abs() < 1e-6);
453    }
454
455    #[test]
456    fn rumble_unsupported_by_default() {
457        let mut backend = NoBackend;
458        assert!(!backend.is_rumble_supported(GamepadId(0)));
459        assert!(!backend.set_rumble(GamepadId(0), 1.0, 1.0, 100));
460        backend.stop_rumble(GamepadId(0));
461    }
462
463    #[cfg(feature = "gamepad")]
464    #[test]
465    fn android_codes_map_to_standard_layout() {
466        assert_eq!(android_code_to_button(96), Some(GamepadButton::South));
467        assert_eq!(android_code_to_button(97), Some(GamepadButton::East));
468        assert_eq!(android_code_to_button(99), Some(GamepadButton::West));
469        assert_eq!(android_code_to_button(100), Some(GamepadButton::North));
470        assert_eq!(
471            android_code_to_button(102),
472            Some(GamepadButton::LeftShoulder)
473        );
474        assert_eq!(android_code_to_button(108), Some(GamepadButton::Start));
475        assert_eq!(android_code_to_button(19), Some(GamepadButton::DPadUp));
476        assert_eq!(android_code_to_button(23), Some(GamepadButton::South));
477        // Non-controller codes fall through to keyboard.
478        assert_eq!(android_code_to_button(29), None); // KEYCODE_A
479        assert_eq!(android_code_to_button(98), None); // BUTTON_C
480        assert_eq!(android_code_to_button(110), None); // BUTTON_MODE
481    }
482
483    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
484    #[test]
485    fn boot_synthesis_reports_all_live_devices() {
486        let live = vec![
487            (GamepadId(0), "Pad A".to_string(), 0x045e, 0x028e),
488            (GamepadId(1), "Pad B".to_string(), 0x057e, 0x2009),
489        ];
490        let synth = synthesize_boot(live.into_iter(), &[]);
491        assert_eq!(synth.len(), 2);
492        assert!(matches!(
493            &synth[0],
494            GamepadEvent::Connected { id, name, vendor_id, product_id }
495            if *id == GamepadId(0) && name == "Pad A" && *vendor_id == 0x045e && *product_id == 0x028e
496        ));
497    }
498
499    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
500    #[test]
501    fn boot_synthesis_skips_self_reported_ids() {
502        let live = vec![
503            (GamepadId(0), "Pad A".to_string(), 0, 0),
504            (GamepadId(1), "Pad B".to_string(), 0, 0),
505        ];
506        let reported = vec![GamepadEvent::Connected {
507            id: GamepadId(1),
508            name: "Pad B".to_string(),
509            vendor_id: 0,
510            product_id: 0,
511        }];
512        let synth = synthesize_boot(live.into_iter(), &reported);
513        assert_eq!(synth.len(), 1);
514        assert!(matches!(
515            &synth[0],
516            GamepadEvent::Connected { id, .. } if *id == GamepadId(0)
517        ));
518        let reported = vec![GamepadEvent::Button {
519            id: GamepadId(0),
520            button: GamepadButton::South,
521            pressed: true,
522        }];
523        let live = vec![(GamepadId(0), "Pad A".to_string(), 0, 0)];
524        assert_eq!(synthesize_boot(live.into_iter(), &reported).len(), 1);
525    }
526
527    #[cfg(all(feature = "gamepad", not(target_os = "android")))]
528    #[test]
529    fn first_poll_is_empty_without_hardware() {
530        if let Some(mut backend) = GilrsBackend::new() {
531            assert!(backend.poll().is_empty());
532            assert!(backend.poll().is_empty());
533        }
534    }
535}