Merge pull request #149 from ludovic111/feat/controllers-rumble

Controllers: rumble
This commit is contained in:
Ludovic Marie
2026-10-14 19:43:33 +02:00
committed by GitHub
8 changed files with 226 additions and 2 deletions
+2
View File
@@ -1996,6 +1996,7 @@ impl Game<'_> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
fn break_block_as_player(&mut self, pos: [i32; 3]) -> Result<()> {
self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken);
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state).clone();
@@ -2652,6 +2653,7 @@ impl Game<'_> {
}
self.previous_position = feet;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
self.eye = 1.62;
+1
View File
@@ -485,6 +485,7 @@ impl Game<'_> {
player.fall_distance = 0.0;
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
@@ -335,6 +335,15 @@ impl Game<'_> {
interaction: BlockInteraction,
fire: bool,
) -> Result<()> {
if let Some(p) = &self.player {
let d = [
p.position.x - center[0],
p.position.y - center[1],
p.position.z - center[2],
];
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius });
}
let mut targets = self.exploded_positions(center, radius);
// Explosion.explode: the blast is heard.
let ctx = horizon_client::sculk::Context::default();
@@ -361,6 +361,7 @@ impl Game<'_> {
player.velocity = rotate_y(player.velocity, -rotation);
self.previous_position = player.position;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.apply_equipment();
let pitch = self.world.random.next_float() * 0.4 + 0.8;
+79 -2
View File
@@ -6,12 +6,12 @@
use super::{Game, Screen};
use horizon_client::{
Result,
gamepad::{self, Button, Edges, GlyphStyle, PadState},
gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble},
keybinds::{KeyBinds, key_code, mouse_button},
mouse::Rotation,
};
use serde_json::{Value, json};
use std::time::Instant;
use std::time::{Duration, Instant};
use winit::{event_loop::ActiveEventLoop, keyboard::KeyCode};
pub(super) const HELP: &[&str] = &[
@@ -48,6 +48,12 @@ pub(super) struct Pads {
pub(super) style: GlyphStyle,
/// The cursor the pad drives in menus.
pub(super) menu: super::pad_menu::MenuCursor,
/// Vibrations playing (an effect stops when dropped) and when they end.
rumbles: Vec<(gilrs::ff::Effect, Instant)>,
/// The last vibration asked for, for `pad status`.
last_rumble: Option<(&'static str, gamepad::Pulse)>,
/// The player's health between polls (a drop is damage taken).
health: HealthWatch,
}
fn gilrs_button(button: Button) -> gilrs::Button {
@@ -73,6 +79,11 @@ fn gilrs_button(button: Button) -> gilrs::Button {
}
impl Pads {
/// A new player entity took over (spawn, respawn, a server joined, a
/// dimension change): its health is not compared with the old one's.
pub(super) fn player_replaced(&mut self) {
self.health.forget();
}
/// Open gilrs on first use. A platform without it (or a Linux without
/// udev) leaves controllers off; the game runs as before.
fn start(&mut self) {
@@ -181,6 +192,18 @@ impl Game<'_> {
self.pad.in_use = true;
}
self.pad.state = state;
// Damage from any source, here or on a server; nothing counts on
// the title screen.
let health = self
.player
.as_ref()
.filter(|_| self.title.is_none())
.map(|p| p.health.health());
if let Some(damage) = self.pad.health.observe(health) {
self.pad_rumble(Rumble::Hurt(damage));
}
let now = Instant::now();
self.pad.rumbles.retain(|(_, end)| *end > now);
let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause;
for button in std::mem::take(&mut self.pad.late_releases) {
if !ticking || self.pad.pressed_at[button as usize] != Some(self.ticks) {
@@ -359,6 +382,57 @@ impl Game<'_> {
self.pitch = rotation.x_rot;
}
/// Vibrate the active pad, when vibration is on and the pad is the one
/// playing (a pad lying idle while the mouse plays stays still).
/// Platforms without force feedback (gilrs on macOS) skip it.
pub(super) fn pad_rumble(&mut self, rumble: Rumble) {
let settings = &self.settings.controller;
if !settings.enabled || !settings.vibration || !self.pad.in_use {
return;
}
let Some(pulse) = rumble.pulse() else {
return;
};
self.pad.last_rumble = Some((rumble.name(), pulse));
let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else {
return;
};
if !gilrs
.connected_gamepad(id)
.is_some_and(|g| g.is_ff_supported())
{
return;
}
use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks};
let length = Ticks::from_ms(pulse.millis);
let motor = |kind| BaseEffect {
kind,
scheduling: Replay {
play_for: length,
..Default::default()
},
envelope: Default::default(),
};
let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16;
let effect = EffectBuilder::new()
.add_effect(motor(BaseEffectType::Strong {
magnitude: magnitude(pulse.strong),
}))
.add_effect(motor(BaseEffectType::Weak {
magnitude: magnitude(pulse.weak),
}))
.repeat(Repeat::For(length))
.gamepads(&[id])
.finish(gilrs);
match effect.and_then(|e| e.play().map(|()| e)) {
Ok(effect) => {
let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50);
self.pad.rumbles.push((effect, end));
}
Err(e) => log::debug!("Horizon: controller vibration: {e}"),
}
}
/// `horizon-ctl pad ...`.
pub(super) fn pad_command(&mut self, words: &[&str]) -> Result<Value> {
let arg = |i: usize| -> Result<&str> {
@@ -400,6 +474,9 @@ impl Game<'_> {
"backend": self.pad.gilrs.is_some(),
"controllers": pads,
"glyphs": self.pad.style.name(),
"last_rumble": self.pad.last_rumble.map(|(why, p)| json!({
"reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis,
})),
"in_use": self.pad.in_use,
"held": held,
"left": s.left,
+1
View File
@@ -1571,6 +1571,7 @@ impl Game<'_> {
let mut player = PlayerMotion::new(self.motion, position)?;
player.velocity = delta;
self.player = Some(player);
self.pad.player_replaced();
self.sway = Default::default();
self.eye = 1.62;
self.previous_eye = 1.62;
+1
View File
@@ -71,5 +71,6 @@ impl Game<'_> {
height,
30,
);
self.pad_rumble(horizon_client::gamepad::Rumble::Totem);
}
}
+132
View File
@@ -589,6 +589,92 @@ pub fn nearest(at: (f32, f32), targets: &[(f32, f32)], radius: f32) -> Option<us
.map(|(i, _)| i)
}
/// Damage taken, from the player's health between polls. The baseline is
/// forgotten whenever there is no player or a new player entity replaces
/// the old one (a world loaded, a respawn, a server joined, a dimension
/// change), so arriving with less health than before isn't damage.
#[derive(Clone, Copy, Debug, Default)]
pub struct HealthWatch {
last: Option<f32>,
}
impl HealthWatch {
/// The health now (`None` without a player); returns the damage taken
/// since the last call.
pub fn observe(&mut self, health: Option<f32>) -> Option<f32> {
let before = std::mem::replace(&mut self.last, health);
match (before, health) {
(Some(before), Some(now)) if now < before => Some(before - now),
_ => None,
}
}
pub fn forget(&mut self) {
self.last = None;
}
}
/// What makes the pad vibrate (Bedrock-like: short, light pulses).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Rumble {
/// The player lost this much health.
Hurt(f32),
BlockBroken,
/// An explosion this far away (blocks) with this power.
Explosion {
distance: f64,
radius: f32,
},
Totem,
}
/// A vibration: the heavy (low-frequency) and light motors, 0..1, and how
/// long it lasts.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pulse {
pub strong: f32,
pub weak: f32,
pub millis: u32,
}
impl Rumble {
pub fn name(self) -> &'static str {
match self {
Rumble::Hurt(_) => "hurt",
Rumble::BlockBroken => "block",
Rumble::Explosion { .. } => "explosion",
Rumble::Totem => "totem",
}
}
/// The pulse, or `None` when it is too faint to feel.
pub fn pulse(self) -> Option<Pulse> {
match self {
Rumble::Hurt(amount) if amount > 0.0 => Some(Pulse {
strong: (0.2 + 0.06 * amount).min(0.8),
weak: 0.3,
millis: (150.0 + 20.0 * amount).min(400.0) as u32,
}),
Rumble::Hurt(_) => None,
Rumble::BlockBroken => Some(Pulse {
strong: 0.0,
weak: 0.25,
millis: 60,
}),
Rumble::Explosion { distance, radius } => {
// Felt up to four times the blast radius, fading with distance.
let reach = f64::from(radius.max(1.0)) * 4.0;
let near = (1.0 - distance / reach) as f32;
(near > 0.05).then_some(Pulse {
strong: 0.9 * near,
weak: 0.6 * near,
millis: 350,
})
}
Rumble::Totem => Some(Pulse {
strong: 0.7,
weak: 0.7,
millis: 500,
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -758,6 +844,52 @@ mod tests {
assert_eq!(action_caption("key.jump"), "key.jump");
}
#[test]
fn health_watch_only_counts_damage_in_one_life() {
let mut w = HealthWatch::default();
assert_eq!(w.observe(Some(20.0)), None);
assert_eq!(w.observe(Some(15.0)), Some(5.0));
assert_eq!(w.observe(Some(18.0)), None, "healing");
// A new player entity (world, respawn, server, dimension).
w.forget();
assert_eq!(w.observe(Some(6.0)), None);
// No player in between (title, loading) forgets too.
assert_eq!(w.observe(None), None);
assert_eq!(w.observe(Some(2.0)), None);
assert_eq!(w.observe(Some(1.0)), Some(1.0));
}
#[test]
fn rumble_pulses() {
let small = Rumble::Hurt(1.0).pulse().unwrap();
let big = Rumble::Hurt(10.0).pulse().unwrap();
assert!(big.strong > small.strong && big.millis > small.millis);
assert!(Rumble::Hurt(100.0).pulse().unwrap().strong <= 0.8);
assert_eq!(Rumble::Hurt(0.0).pulse(), None);
let near = Rumble::Explosion {
distance: 2.0,
radius: 4.0,
}
.pulse()
.unwrap();
let far = Rumble::Explosion {
distance: 12.0,
radius: 4.0,
}
.pulse()
.unwrap();
assert!(near.strong > far.strong);
assert_eq!(
Rumble::Explosion {
distance: 20.0,
radius: 4.0
}
.pulse(),
None
);
assert_eq!(Rumble::BlockBroken.pulse().unwrap().strong, 0.0);
}
#[test]
fn hotbar_wraps_and_glyphs_follow_the_vendor() {
assert_eq!(hotbar_step(8, true), 0);