Merge pull request #120 from ludovic111/feat/controllers-input

Controllers: design note, gilrs input layer and gameplay
This commit is contained in:
Ludovic Marie
2026-10-14 18:40:10 +02:00
committed by GitHub
21 changed files with 1447 additions and 43 deletions
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
python tools/check_public_tree.py --history
- name: Test offline research tooling
run: python -m unittest discover -s tests -v
- name: Install Rust toolchain and the ALSA headers the client's audio links against
- name: Install Rust toolchain and the ALSA and udev headers the client links against
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
rustup toolchain install stable --profile minimal --component rustfmt --component clippy
- name: Check formatting and lint
run: |
+2 -2
View File
@@ -40,8 +40,8 @@ jobs:
- uses: actions/checkout@v4
- name: Install Rust toolchain
run: rustup toolchain install stable --profile minimal
- name: ALSA headers
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev
- name: ALSA and udev headers
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
- name: Build the client
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare
- name: Standard loader and libraries only
Generated
+110
View File
@@ -648,6 +648,12 @@ dependencies = [
"zlib-rs",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foldhash"
version = "0.1.5"
@@ -754,6 +760,40 @@ dependencies = [
"r-efi 6.0.0",
]
[[package]]
name = "gilrs"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "902fb00d3f6398e635be22e5c837b303c501835cca7ac11a47bba138f7aafdd8"
dependencies = [
"fnv",
"gilrs-core",
"log",
"uuid",
"vec_map",
]
[[package]]
name = "gilrs-core"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc7f0ce6237abcc0523f2a5502b1e3fe5802daaae47ac14e166fe49551301ea9"
dependencies = [
"inotify",
"js-sys",
"libc",
"libudev-sys",
"log",
"nix",
"objc2-core-foundation",
"objc2-io-kit",
"uuid",
"vec_map",
"wasm-bindgen",
"web-sys",
"windows 0.62.2",
]
[[package]]
name = "glam"
version = "0.30.10"
@@ -840,6 +880,7 @@ dependencies = [
"chrono",
"cpal",
"flate2",
"gilrs",
"glam",
"horizon-assets",
"horizon-core",
@@ -932,6 +973,26 @@ dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "inotify"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
dependencies = [
"bitflags 2.13.2",
"inotify-sys",
"libc",
]
[[package]]
name = "inotify-sys"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
dependencies = [
"libc",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1073,6 +1134,16 @@ dependencies = [
"redox_syscall 0.9.4",
]
[[package]]
name = "libudev-sys"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"
dependencies = [
"libc",
"pkg-config",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -1230,6 +1301,18 @@ dependencies = [
"jni-sys 0.3.1",
]
[[package]]
name = "nix"
version = "0.31.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "nom"
version = "8.0.0"
@@ -1486,6 +1569,17 @@ dependencies = [
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-kit"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
dependencies = [
"bitflags 2.13.2",
"libc",
"objc2-core-foundation",
]
[[package]]
name = "objc2-io-surface"
version = "0.3.2"
@@ -2425,6 +2519,22 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "uuid"
version = "1.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.5"
+1 -1
View File
@@ -130,7 +130,7 @@ Commands block until the action is done and reply with what happened; errors are
## Build from source
For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA development headers (`libasound2-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux.
For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA and udev development headers (`libasound2-dev libudev-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux.
Horizon contains no game files and never downloads them. It builds its resources from **your own copy** of Minecraft: Java Edition 26.3, verified against the checksums in `research-lock.json`:
+2
View File
@@ -28,6 +28,8 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
horizon-theme = { path = "../horizon-theme" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input).
gilrs = "0.11"
[features]
# Records the call sites of mob random draws (`mob_ai_probe` traces).
@@ -278,6 +278,7 @@ fn main() -> Result<()> {
jump: mask & 16 != 0,
shift: mask & 32 != 0,
sprint: mask & 64 != 0,
analog: None,
})?;
}
"movement_statistics" => world.check_movement_statistics(vector(&op["value"]))?,
@@ -17,6 +17,7 @@ fn keys(mask: u64) -> Keys {
jump: mask & 16 != 0,
shift: mask & 32 != 0,
sprint: mask & 64 != 0,
analog: None,
}
}
fn main() -> Result<()> {
@@ -252,6 +252,10 @@ pub const COMMANDS: &[Cmd] = &[
["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false),
cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "",
["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false),
cmd!("pad", Act, "pad BUTTON down|up|tap | pad stick left|right X Y | pad trigger left|right V | pad release | pad status", "a virtual controller: buttons, sticks and triggers as a real pad would send them",
"Buttons by position: south east west north lb rb lt rt select start ls rs up down left right (south is Xbox A / PlayStation cross). Sticks run -1..1 with up positive and stay tilted until centred; triggers 0..1. Merged with any real controller; status lists the connected ones and what is held.",
["horizon-ctl pad south tap", "horizon-ctl pad stick left 0 1", "horizon-ctl pad trigger right 1", "horizon-ctl pad status"],
&[p("what", Ty::Str, "a button name, stick, trigger, release or status"), opt("a", Ty::Str, "down|up|tap, or left|right"), opt("b", Ty::Num, "stick X or trigger value"), opt("c", Ty::Num, "stick Y")], mcp: false, local: false),
cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false),
cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false),
// Screens
+48 -32
View File
@@ -73,6 +73,7 @@ mod net_harness;
mod nether_portal;
mod options;
mod packs;
mod pad;
mod paintings;
mod passengers;
mod persist;
@@ -661,6 +662,8 @@ struct Game<'a> {
previous: Instant,
/// FramerateLimitTracker.latestInputTime.
last_input: Instant,
/// Controllers (Horizon's own).
pad: pad::Pads,
frames: u64,
fps: f32,
fps_frames: u64,
@@ -2667,6 +2670,7 @@ impl Game<'_> {
self.update_totem_ready();
self.tick_command_extras();
let camera_eye = self.camera_eye_height();
let stick = self.pad_move();
if self.riding.is_some() && self.player.is_some() {
let playing = self.screen == Screen::Playing;
let held = |k| playing && self.keys.contains(&k);
@@ -2678,7 +2682,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: false,
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
self.tick_riding(keys)?;
}
let riding = self.riding.is_some();
@@ -2707,7 +2713,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: held(KeyCode::ControlLeft),
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
if !riding {
self.previous_position = player.position;
}
@@ -2978,6 +2986,40 @@ impl Game<'_> {
self.keys.remove(&key);
}
}
/// A key event after rebinding, as the default key of its mapping (the
/// keyboard and controllers both end here).
fn mapped_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) -> Result<()> {
// Sneak and sprint are ToggleKeyMappings: a press (or a key
// repeat) flips them when toggling; only releases reach them
// behind a screen (KeyboardHandler.keyPress).
let toggle = match key {
KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)),
KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)),
_ => None,
};
if let Some((slot, option)) = toggle {
let action = match (pressed, repeat) {
(false, _) => KeyAction::Release,
(_, false) => KeyAction::Press,
(_, true) => KeyAction::Repeat,
};
let screen_open = self.screen != Screen::Playing || self.title.is_some();
self.toggles.key(slot, action, screen_open, option);
self.sync_toggle(slot);
if !pressed {
return Ok(());
}
} else if !pressed {
self.keys.remove(&key);
return Ok(());
} else {
self.keys.insert(key);
}
if repeat {
return Ok(());
}
self.key_pressed(key)
}
/// `KeyMapping.releaseAll` when a screen opens and
/// `restoreToggleStatesOnScreenClosed` when it closes.
fn track_toggle_screens(&mut self) {
@@ -8376,36 +8418,7 @@ impl ApplicationHandler for Game<'_> {
}
None => return Ok(()),
};
// Sneak and sprint are ToggleKeyMappings: a press (or a key
// repeat) flips them when toggling; only releases reach them
// behind a screen (KeyboardHandler.keyPress).
let toggle = match key {
KeyCode::ShiftLeft => Some((0, self.settings.toggle_crouch)),
KeyCode::ControlLeft => Some((1, self.settings.toggle_sprint)),
_ => None,
};
if let Some((slot, option)) = toggle {
let action = match (event.state, event.repeat) {
(ElementState::Released, _) => KeyAction::Release,
(_, false) => KeyAction::Press,
(_, true) => KeyAction::Repeat,
};
let screen_open = self.screen != Screen::Playing || self.title.is_some();
self.toggles.key(slot, action, screen_open, option);
self.sync_toggle(slot);
if event.state != ElementState::Pressed {
return Ok(());
}
} else if event.state != ElementState::Pressed {
self.keys.remove(&key);
return Ok(());
} else {
self.keys.insert(key);
}
if event.repeat {
return Ok(());
}
self.key_pressed(key)?;
self.mapped_key(key, event.state == ElementState::Pressed, event.repeat)?;
}
WindowEvent::RedrawRequested => {
self.observe_fullscreen();
@@ -8450,6 +8463,7 @@ impl ApplicationHandler for Game<'_> {
}
}
self.apply_mouse_look();
self.pad_look(elapsed.as_secs_f32());
self.advance_flight();
let ticked = Instant::now();
let rendered = self.render()?;
@@ -8554,6 +8568,7 @@ impl ApplicationHandler for Game<'_> {
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
self.poll_control(event_loop);
self.poll_pads();
if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout {
self.error = Some("frame-limited run timed out".into());
event_loop.exit();
@@ -8812,6 +8827,7 @@ pub fn run() -> Result<()> {
started: now,
previous: now,
last_input: now,
pad: Default::default(),
frames: 0,
fps: 0.0,
fps_frames: 0,
+1 -1
View File
@@ -87,7 +87,7 @@ impl Game<'_> {
self.right = false;
self.capture(false);
}
fn close_book(&mut self) {
pub(super) fn close_book(&mut self) {
self.book = None;
self.capture(true);
}
@@ -134,10 +134,12 @@ impl Game<'_> {
.chain(super::render_control::HELP)
.chain(super::sculk::HELP)
.chain(super::agent::HELP)
.chain(super::pad::HELP)
.collect::<Vec<_>>() }))),
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
"sculk" => Ok(Some(self.sculk_command(&words)?)),
"status" => Ok(Some(self.control_status())),
"pad" => Ok(Some(self.pad_command(&words)?)),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
self.require_world()?;
+464
View File
@@ -0,0 +1,464 @@
//! Controllers through gilrs (Horizon's own; docs/controllers.md): the
//! active pad's state each loop iteration, its button edges dispatched as
//! the vanilla key mappings they are bound to, the left stick as an analog
//! move vector and the right stick turning the view. `horizon-ctl pad`
//! injects a virtual pad on top of the real one.
use super::{Game, Screen};
use horizon_client::{
Result,
gamepad::{self, Button, Edges, GlyphStyle, PadState},
keybinds::{KeyBinds, key_code, mouse_button},
mouse::Rotation,
};
use serde_json::{Value, json};
use std::time::Instant;
use winit::keyboard::KeyCode;
pub(super) const HELP: &[&str] = &[
"pad BUTTON down|up|tap a virtual controller button (south east west north lb rb lt rt select start ls rs up down left right)",
"pad stick left|right X Y tilt a virtual stick (-1..1, up positive); 0 0 centres it",
"pad trigger left|right VALUE pull a virtual trigger (0..1)",
"pad release centre and release the virtual controller",
"pad status connected controllers, the active one and its state",
];
/// The controllers and the state the game last acted on.
#[derive(Default)]
pub(super) struct Pads {
gilrs: Option<gilrs::Gilrs>,
started: bool,
/// The pad last touched; only its input counts.
active: Option<gilrs::GamepadId>,
/// The virtual pad of `horizon-ctl pad`.
injected: PadState,
/// The virtual pad was in use at the last poll.
virtual_input: bool,
/// Buttons a `pad ... tap` releases at the next poll.
taps: Vec<Button>,
edges: Edges,
/// The game tick each button went down in, and releases held back until
/// a tick has passed: vanilla samples keys once per tick, so a click
/// shorter than that (a quick stick click for sprint) would be lost.
pressed_at: [Option<u64>; 16],
late_releases: Vec<Button>,
/// The merged state of the last poll.
state: PadState,
/// The pad drove the game last (the mouse and keyboard hand control back).
pub(super) in_use: bool,
pub(super) style: GlyphStyle,
}
fn gilrs_button(button: Button) -> gilrs::Button {
use gilrs::Button as G;
match button {
Button::South => G::South,
Button::East => G::East,
Button::West => G::West,
Button::North => G::North,
Button::LeftBumper => G::LeftTrigger,
Button::RightBumper => G::RightTrigger,
Button::LeftTrigger => G::LeftTrigger2,
Button::RightTrigger => G::RightTrigger2,
Button::Select => G::Select,
Button::Start => G::Start,
Button::LeftStick => G::LeftThumb,
Button::RightStick => G::RightThumb,
Button::DPadUp => G::DPadUp,
Button::DPadDown => G::DPadDown,
Button::DPadLeft => G::DPadLeft,
Button::DPadRight => G::DPadRight,
}
}
impl Pads {
/// 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) {
if self.started {
return;
}
self.started = true;
self.gilrs = match gilrs::Gilrs::new() {
Ok(g) => {
for (_, pad) in g.gamepads() {
log::info!("Controller connected: {}", pad.name());
}
Some(g)
}
Err(gilrs::Error::NotImplemented(_)) => None,
Err(e) => {
log::warn!("Horizon: controllers are unavailable: {e}");
None
}
};
}
/// Drain gilrs' events and read the active pad.
fn read(&mut self) -> PadState {
let Some(gilrs) = self.gilrs.as_mut() else {
return PadState::default();
};
while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() {
use gilrs::EventType as E;
match event {
E::Connected => {
log::info!("Controller connected: {}", gilrs.gamepad(id).name());
}
E::Disconnected => {
log::info!("Controller disconnected: {}", gilrs.gamepad(id).name());
if self.active == Some(id) {
self.active = None;
}
}
E::ButtonPressed(..) => self.active = Some(id),
E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _)
if value.abs() > 0.5 =>
{
self.active = Some(id)
}
_ => {}
}
}
let Some(pad) = self.active.and_then(|id| gilrs.connected_gamepad(id)) else {
return PadState::default();
};
self.style = GlyphStyle::of_vendor(pad.vendor_id());
let mut state = PadState::default();
for button in Button::ALL {
if !matches!(button, Button::LeftTrigger | Button::RightTrigger) {
state.set(button, pad.is_pressed(gilrs_button(button)));
}
}
let axis = |a| pad.value(a);
use gilrs::Axis as A;
state.left = [axis(A::LeftStickX), axis(A::LeftStickY)];
state.right = [axis(A::RightStickX), axis(A::RightStickY)];
// Triggers arrive as analog buttons on most mappings, as plain
// buttons on some.
let trigger = |b: gilrs::Button| {
let value = pad.button_data(b).map_or(0.0, |d| d.value());
if pad.is_pressed(b) {
value.max(1.0)
} else {
value
}
};
state.triggers = [
trigger(gilrs::Button::LeftTrigger2),
trigger(gilrs::Button::RightTrigger2),
];
state
}
}
impl Game<'_> {
/// Once per loop iteration: read the pads and act on button changes.
pub(super) fn poll_pads(&mut self) {
let settings = &self.settings.controller;
if !settings.enabled {
if self.pad.state != PadState::default() {
self.pad.state = PadState::default();
for (button, down) in self.pad.edges.release_all() {
self.pad_edge(button, down);
}
}
return;
}
self.pad.start();
let hardware = self.pad.read();
let state = hardware.merge(&self.pad.injected);
self.pad.virtual_input = self.pad.injected != PadState::default();
for button in std::mem::take(&mut self.pad.taps) {
self.pad.injected.set(button, false);
}
let threshold = self.settings.controller.trigger_threshold;
let edges = self.pad.edges.update(&state, threshold);
if state.active(&self.settings.controller) {
self.last_input = Instant::now();
self.pad.in_use = true;
}
self.pad.state = state;
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) {
self.pad_button_logged(button, false);
} else {
self.pad.late_releases.push(button);
}
}
for (button, down) in edges {
self.pad_edge(button, down);
}
}
fn pad_edge(&mut self, button: Button, down: bool) {
let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause;
if down {
// Pressed again before its held-back release went out.
if let Some(i) = self.pad.late_releases.iter().position(|b| *b == button) {
self.pad.late_releases.remove(i);
self.pad_button_logged(button, false);
}
self.pad.pressed_at[button as usize] = Some(self.ticks);
} else if ticking && self.pad.pressed_at[button as usize] == Some(self.ticks) {
self.pad.late_releases.push(button);
return;
}
self.pad_button_logged(button, down);
}
fn pad_button_logged(&mut self, button: Button, down: bool) {
if let Err(e) = self.pad_button(button, down) {
log::warn!("Horizon: controller {}: {e}", button.name());
}
}
/// Input from the pad counts while the window has focus, or always for
/// the virtual pad (a script can't focus the window).
fn pad_focused(&self) -> bool {
self.focused || self.pad.virtual_input
}
fn pad_button(&mut self, button: Button, down: bool) -> Result<()> {
if down && !self.pad_focused() {
return Ok(());
}
let playing = self.title.is_none() && self.screen == Screen::Playing;
if down && playing && !self.captured && self.focused {
// Like a click into the window: take the pointer.
self.capture(true);
}
if button == Button::Start {
return if down { self.pad_back() } else { Ok(()) };
}
if !playing && down {
// Until menus take the pad, it can at least leave them.
return match button {
Button::East => self.pad_back(),
Button::South if self.screen == Screen::Dead && self.title.is_none() => {
// The respawn button, as if clicked.
let size = self
.renderer
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = horizon_client::hud::HudBatch::new(size);
let (x, y, _, _) = super::screens::death_buttons(b.width, b.height)[0];
let cursor = std::mem::replace(&mut self.cursor, (x + 100.0, y + 10.0));
let result = self.death_click();
self.cursor = cursor;
result
}
Button::North if matches!(self.screen, Screen::Inventory | Screen::Creative) => {
self.mapped_key(KeyCode::KeyE, true, false)
}
_ => Ok(()),
};
}
// Releases always reach the mappings, so nothing stays held when a
// screen opened in between.
for action in self.settings.controller.actions_of(button) {
self.pad_action(action, down)?;
}
Ok(())
}
/// A bound action: a vanilla mapping acts as its default key or mouse
/// button, like a rebound keyboard key.
fn pad_action(&mut self, action: &str, down: bool) -> Result<()> {
match action {
gamepad::HOTBAR_PREVIOUS | gamepad::HOTBAR_NEXT => {
if down && self.screen == Screen::Playing {
self.selected =
gamepad::hotbar_step(self.selected, action == gamepad::HOTBAR_NEXT);
}
Ok(())
}
"key.sneak"
if self.settings.controller.toggle_sneak && !self.settings.toggle_crouch =>
{
// A stick click flips sneaking instead of holding it.
if down {
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
self.mapped_key(KeyCode::ShiftLeft, !sneaking, false)?;
}
Ok(())
}
_ => {
let default = KeyBinds::default_of(action);
if let Some(button) = mouse_button(default) {
if self.title.is_none() && self.screen == Screen::Playing {
self.play_mouse(button, down)?;
}
Ok(())
} else if let Some(key) = key_code(default) {
self.mapped_key(key, down, false)
} else {
Ok(())
}
}
}
}
/// B and Start: what Escape does where the pad is.
fn pad_back(&mut self) -> Result<()> {
if let Some(title) = self.title.as_mut() {
title.escape();
return Ok(());
}
if self.sign_edit.is_some() {
self.close_sign_editor();
return Ok(());
}
if self.book.is_some() {
self.close_book();
return Ok(());
}
if let Some(remote) = self.remote.as_mut()
&& remote.chat_input.is_some()
{
remote.chat_input = None;
self.capture(true);
return Ok(());
}
self.key_pressed(KeyCode::Escape)
}
/// The left stick as the move vector, while playing.
pub(super) fn pad_move(&self) -> Option<[f32; 2]> {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| !self.pad_focused()
{
return None;
}
gamepad::move_vector(self.pad.state.left, settings.move_deadzone)
}
/// The right stick turns the view, once per frame (`Entity.turn`).
pub(super) fn pad_look(&mut self, seconds: f32) {
let settings = &self.settings.controller;
if !settings.enabled
|| self.title.is_some()
|| self.screen != Screen::Playing
|| self.player.is_none()
|| !self.pad_focused()
{
return;
}
// A long frame (a hitch) must not spin the view.
let (yaw, pitch) = gamepad::look_delta(
self.pad.state.right,
settings,
seconds.min(0.1),
self.scoping(),
);
if yaw == 0.0 && pitch == 0.0 {
return;
}
let mut rotation = Rotation {
x_rot: self.pitch,
y_rot: self.yaw,
x_rot_o: self.pitch,
y_rot_o: self.yaw,
};
rotation.turn(f64::from(yaw / 0.15), f64::from(pitch / 0.15));
self.yaw = rotation.y_rot;
self.pitch = rotation.x_rot;
}
/// `horizon-ctl pad ...`.
pub(super) fn pad_command(&mut self, words: &[&str]) -> Result<Value> {
let arg = |i: usize| -> Result<&str> {
words
.get(i)
.copied()
.ok_or_else(|| format!("usage: {}", HELP[0]).into())
};
let number = |i: usize| -> Result<f32> {
let v: f32 = arg(i)?.parse()?;
if v.is_finite() {
Ok(v)
} else {
Err("not a number".into())
}
};
match arg(1)? {
"status" => {
let pads: Vec<Value> = self.pad.gilrs.as_ref().map_or(Vec::new(), |g| {
g.gamepads()
.map(|(id, p)| {
json!({
"name": p.name(),
"vendor": p.vendor_id(),
"product": p.product_id(),
"active": self.pad.active == Some(id),
})
})
.collect()
});
let s = &self.pad.state;
let held: Vec<&str> = Button::ALL
.into_iter()
.filter(|b| self.pad.edges.is_held(*b))
.map(Button::name)
.collect();
Ok(json!({
"enabled": self.settings.controller.enabled,
"backend": self.pad.gilrs.is_some(),
"controllers": pads,
"glyphs": self.pad.style.name(),
"in_use": self.pad.in_use,
"held": held,
"left": s.left,
"right": s.right,
"triggers": s.triggers,
}))
}
"release" => {
self.pad.injected = PadState::default();
self.pad.taps.clear();
Ok(json!({ "ok": true }))
}
"stick" => {
let v = [number(3)?.clamp(-1.0, 1.0), number(4)?.clamp(-1.0, 1.0)];
match arg(2)? {
"left" => self.pad.injected.left = v,
"right" => self.pad.injected.right = v,
other => return Err(format!("stick must be left or right, not {other}").into()),
}
Ok(json!({ "ok": true }))
}
"trigger" => {
let v = number(3)?.clamp(0.0, 1.0);
match arg(2)? {
"left" => self.pad.injected.triggers[0] = v,
"right" => self.pad.injected.triggers[1] = v,
other => {
return Err(format!("trigger must be left or right, not {other}").into());
}
}
Ok(json!({ "ok": true }))
}
name => {
let button = Button::parse(name)
.ok_or_else(|| format!("unknown pad button {name}; {}", HELP[0]))?;
match arg(2)? {
"down" => self.pad.injected.set(button, true),
"up" => self.pad.injected.set(button, false),
"tap" => {
self.pad.injected.set(button, true);
self.pad.taps.push(button);
}
other => {
return Err(
format!("pad action must be down, up or tap, not {other}").into()
);
}
}
Ok(json!({ "ok": true }))
}
}
}
}
+4 -1
View File
@@ -1635,6 +1635,7 @@ impl Game<'_> {
r.loaded_sent = true;
}
}
let stick = self.pad_move();
let Some(player) = self.player.as_mut() else {
return Ok(());
};
@@ -1649,7 +1650,9 @@ impl Game<'_> {
jump: held(KeyCode::Space),
shift: held(KeyCode::ShiftLeft),
sprint: held(KeyCode::ControlLeft),
};
analog: None,
}
.with_stick(stick.filter(|_| playing));
let input = u8::from(keys.forward)
| u8::from(keys.backward) << 1
| u8::from(keys.left) << 2
+1 -1
View File
@@ -40,7 +40,7 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
(x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"),
]
}
fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] {
pub(super) fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] {
[
(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0),
(
+1 -1
View File
@@ -33,7 +33,7 @@ impl Game<'_> {
self.right = false;
self.capture(false);
}
fn close_sign_editor(&mut self) {
pub(super) fn close_sign_editor(&mut self) {
if let Some(edit) = self.sign_edit.take() {
self.world
.modified
+596
View File
@@ -0,0 +1,596 @@
//! Controllers: Horizon's own feature (vanilla 26.3 has no gamepad input).
//! The default layout is Bedrock Edition's; see docs/controllers.md.
//!
//! This module is the backend-free part: positional buttons, the action
//! bindings, deadzones and the look curve, button edges from successive pad
//! states, and `horizon-controller.txt`, kept next to `options.txt` so that
//! file stays exactly vanilla's. The game reads the pads with gilrs.
use std::{collections::BTreeMap, fs, path::Path};
pub const FILE: &str = "horizon-controller.txt";
/// A button by its position on the pad (gilrs' and SDL's layout): `South`
/// is Xbox A, PlayStation ✕, Nintendo B.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Button {
South,
East,
West,
North,
LeftBumper,
RightBumper,
LeftTrigger,
RightTrigger,
Select,
Start,
LeftStick,
RightStick,
DPadUp,
DPadDown,
DPadLeft,
DPadRight,
}
impl Button {
pub const ALL: [Button; 16] = [
Button::South,
Button::East,
Button::West,
Button::North,
Button::LeftBumper,
Button::RightBumper,
Button::LeftTrigger,
Button::RightTrigger,
Button::Select,
Button::Start,
Button::LeftStick,
Button::RightStick,
Button::DPadUp,
Button::DPadDown,
Button::DPadLeft,
Button::DPadRight,
];
/// The name in `horizon-controller.txt` and `horizon-ctl pad`.
pub fn name(self) -> &'static str {
match self {
Button::South => "south",
Button::East => "east",
Button::West => "west",
Button::North => "north",
Button::LeftBumper => "lb",
Button::RightBumper => "rb",
Button::LeftTrigger => "lt",
Button::RightTrigger => "rt",
Button::Select => "select",
Button::Start => "start",
Button::LeftStick => "ls",
Button::RightStick => "rs",
Button::DPadUp => "up",
Button::DPadDown => "down",
Button::DPadLeft => "left",
Button::DPadRight => "right",
}
}
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|b| b.name() == name)
}
fn bit(self) -> u32 {
1 << self as u32
}
}
/// A pad's inputs at one moment. Sticks are `[x, y]` with right and up
/// positive; triggers run 0..1.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PadState {
/// Digital buttons as a bit set (triggers are in `triggers`).
pub buttons: u32,
pub left: [f32; 2],
pub right: [f32; 2],
pub triggers: [f32; 2],
}
impl PadState {
pub fn set(&mut self, button: Button, down: bool) {
if down {
self.buttons |= button.bit();
} else {
self.buttons &= !button.bit();
}
}
pub fn held(&self, button: Button) -> bool {
self.buttons & button.bit() != 0
}
/// Two sources at once (a real pad and `horizon-ctl pad`): buttons held on
/// either, sticks and triggers added.
pub fn merge(&self, other: &PadState) -> PadState {
let add = |a: [f32; 2], b: [f32; 2]| {
[
(a[0] + b[0]).clamp(-1.0, 1.0),
(a[1] + b[1]).clamp(-1.0, 1.0),
]
};
PadState {
buttons: self.buttons | other.buttons,
left: add(self.left, other.left),
right: add(self.right, other.right),
triggers: [
(self.triggers[0] + other.triggers[0]).clamp(0.0, 1.0),
(self.triggers[1] + other.triggers[1]).clamp(0.0, 1.0),
],
}
}
/// Anything pushed past the deadzones (the pad is in use).
pub fn active(&self, settings: &PadSettings) -> bool {
self.buttons != 0
|| length(self.left) > settings.move_deadzone
|| length(self.right) > settings.look_deadzone
|| self
.triggers
.iter()
.any(|t| *t >= settings.trigger_threshold)
}
}
/// Button presses and releases between successive states. Triggers count as
/// buttons past `threshold`, with a little hysteresis so a trigger resting
/// near the threshold doesn't chatter.
#[derive(Clone, Debug, Default)]
pub struct Edges {
held: u32,
}
impl Edges {
pub fn update(&mut self, state: &PadState, threshold: f32) -> Vec<(Button, bool)> {
let mut now = state.buttons;
for (trigger, button) in [(0, Button::LeftTrigger), (1, Button::RightTrigger)] {
let was = self.held & button.bit() != 0;
let value = state.triggers[trigger];
let on = if was {
value >= (threshold - 0.1).max(0.05)
} else {
value >= threshold
};
if on {
now |= button.bit();
} else {
now &= !button.bit();
}
}
let changed = now ^ self.held;
self.held = now;
Button::ALL
.into_iter()
.filter(|b| changed & b.bit() != 0)
.map(|b| (b, now & b.bit() != 0))
.collect()
}
/// Release everything (the pad was unplugged or turned off).
pub fn release_all(&mut self) -> Vec<(Button, bool)> {
let held = std::mem::take(&mut self.held);
Button::ALL
.into_iter()
.filter(|b| held & b.bit() != 0)
.map(|b| (b, false))
.collect()
}
pub fn is_held(&self, button: Button) -> bool {
self.held & button.bit() != 0
}
}
/// Horizon's pad-only actions (no vanilla key mapping).
pub const HOTBAR_PREVIOUS: &str = "pad.hotbarPrevious";
pub const HOTBAR_NEXT: &str = "pad.hotbarNext";
/// Bindable actions and their default buttons: vanilla key mappings (the
/// game acts as their default key) and Horizon's pad-only actions. Start is
/// always pause / back and isn't listed.
pub const ACTIONS: &[(&str, Option<Button>)] = &[
("key.jump", Some(Button::South)),
("key.drop", Some(Button::East)),
("key.swapOffhand", Some(Button::West)),
("key.inventory", Some(Button::North)),
(HOTBAR_PREVIOUS, Some(Button::LeftBumper)),
(HOTBAR_NEXT, Some(Button::RightBumper)),
("key.use", Some(Button::LeftTrigger)),
("key.attack", Some(Button::RightTrigger)),
("key.sprint", Some(Button::LeftStick)),
("key.sneak", Some(Button::RightStick)),
("key.togglePerspective", Some(Button::DPadUp)),
("key.pickItem", Some(Button::DPadLeft)),
("key.chat", Some(Button::DPadRight)),
("key.advancements", Some(Button::DPadDown)),
("key.playerlist", Some(Button::Select)),
("key.command", None),
("key.screenshot", None),
("key.toggleGui", None),
("key.smoothCamera", None),
];
/// Which button pictures prompts use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum GlyphStyle {
/// From the pad's maker.
#[default]
Auto,
Xbox,
PlayStation,
Nintendo,
}
impl GlyphStyle {
pub fn name(self) -> &'static str {
match self {
GlyphStyle::Auto => "auto",
GlyphStyle::Xbox => "xbox",
GlyphStyle::PlayStation => "playstation",
GlyphStyle::Nintendo => "nintendo",
}
}
pub fn parse(name: &str) -> Self {
match name {
"xbox" => GlyphStyle::Xbox,
"playstation" => GlyphStyle::PlayStation,
"nintendo" => GlyphStyle::Nintendo,
_ => GlyphStyle::Auto,
}
}
/// The style for a pad by its USB vendor (Sony, Nintendo; Microsoft,
/// Valve's Steam Deck and Steam Input's virtual pad, and everything else
/// look like Xbox).
pub fn of_vendor(vendor: Option<u16>) -> Self {
match vendor {
Some(0x054c) => GlyphStyle::PlayStation,
Some(0x057e) => GlyphStyle::Nintendo,
_ => GlyphStyle::Xbox,
}
}
}
/// The controller settings (`horizon-controller.txt`).
#[derive(Clone, Debug, PartialEq)]
pub struct PadSettings {
pub enabled: bool,
pub vibration: bool,
/// 0..1; 0.5 is the default speed, 1 twice that.
pub look_sensitivity: f32,
pub invert_x: bool,
pub invert_y: bool,
pub move_deadzone: f32,
pub look_deadzone: f32,
pub trigger_threshold: f32,
/// The sneak button flips sneaking (Bedrock's default) instead of
/// holding it, unless vanilla's toggle crouch is on already.
pub toggle_sneak: bool,
pub glyphs: GlyphStyle,
/// Action name -> button, `None` for unbound; missing means the default.
bindings: BTreeMap<&'static str, Option<Button>>,
}
impl Default for PadSettings {
fn default() -> Self {
Self {
enabled: true,
vibration: true,
look_sensitivity: 0.5,
invert_x: false,
invert_y: false,
move_deadzone: 0.15,
look_deadzone: 0.12,
trigger_threshold: 0.4,
toggle_sneak: true,
glyphs: GlyphStyle::Auto,
bindings: BTreeMap::new(),
}
}
}
fn bool_text(v: bool) -> &'static str {
if v { "true" } else { "false" }
}
impl PadSettings {
pub fn load(dir: &Path) -> Self {
fs::read_to_string(dir.join(FILE))
.map(|t| Self::parse(&t))
.unwrap_or_default()
}
/// Written once something differs from the defaults, so players who
/// never touch a controller get no new file.
pub fn save(&self, dir: &Path) {
let path = dir.join(FILE);
if *self != Self::default() || path.exists() {
let _ = fs::write(path, self.serialize());
}
}
pub fn parse(text: &str) -> Self {
let mut s = Self::default();
for line in text.lines() {
let Some((key, value)) = line.split_once(':') else {
continue;
};
let value = value.trim();
let flag = |d: bool| match value {
"true" => true,
"false" => false,
_ => d,
};
let unit = |d: f32| {
value
.parse::<f32>()
.ok()
.filter(|v| v.is_finite())
.map_or(d, |v| v.clamp(0.0, 1.0))
};
match key.trim() {
"enabled" => s.enabled = flag(s.enabled),
"vibration" => s.vibration = flag(s.vibration),
"lookSensitivity" => s.look_sensitivity = unit(s.look_sensitivity),
"invertX" => s.invert_x = flag(s.invert_x),
"invertY" => s.invert_y = flag(s.invert_y),
"moveDeadzone" => s.move_deadzone = unit(s.move_deadzone).min(0.9),
"lookDeadzone" => s.look_deadzone = unit(s.look_deadzone).min(0.9),
"triggerThreshold" => {
s.trigger_threshold = unit(s.trigger_threshold).clamp(0.1, 0.9)
}
"toggleSneak" => s.toggle_sneak = flag(s.toggle_sneak),
"glyphs" => s.glyphs = GlyphStyle::parse(value),
other => {
if let Some(action) = other.strip_prefix("bind_") {
let button = if value == "none" {
Some(None)
} else {
Button::parse(value).map(Some)
};
if let Some(button) = button {
s.bind(action, button);
}
}
}
}
}
s
}
pub fn serialize(&self) -> String {
let mut text = format!(
"enabled:{}\nvibration:{}\nlookSensitivity:{}\ninvertX:{}\ninvertY:{}\nmoveDeadzone:{}\nlookDeadzone:{}\ntriggerThreshold:{}\ntoggleSneak:{}\nglyphs:{}\n",
bool_text(self.enabled),
bool_text(self.vibration),
self.look_sensitivity,
bool_text(self.invert_x),
bool_text(self.invert_y),
self.move_deadzone,
self.look_deadzone,
self.trigger_threshold,
bool_text(self.toggle_sneak),
self.glyphs.name(),
);
for (action, button) in &self.bindings {
text.push_str(&format!(
"bind_{action}:{}\n",
button.map_or("none", Button::name)
));
}
text
}
pub fn default_of(action: &str) -> Option<Button> {
ACTIONS.iter().find(|a| a.0 == action).and_then(|a| a.1)
}
/// The button an action is bound to.
pub fn binding(&self, action: &str) -> Option<Button> {
match self.bindings.get(action) {
Some(button) => *button,
None => Self::default_of(action),
}
}
/// Bind an action (`None` unbinds); unknown actions are ignored.
pub fn bind(&mut self, action: &str, button: Option<Button>) {
let Some((name, default)) = ACTIONS.iter().find(|a| a.0 == action) else {
return;
};
if button == *default {
self.bindings.remove(name);
} else {
self.bindings.insert(name, button);
}
}
pub fn reset_bindings(&mut self) {
self.bindings.clear();
}
/// The actions a button triggers, in `ACTIONS` order.
pub fn actions_of(&self, button: Button) -> Vec<&'static str> {
ACTIONS
.iter()
.map(|a| a.0)
.filter(|a| self.binding(a) == Some(button))
.collect()
}
}
fn length(v: [f32; 2]) -> f32 {
(v[0] * v[0] + v[1] * v[1]).sqrt()
}
/// A radial deadzone: inside it the stick is centred; beyond it the rest of
/// the travel is rescaled to 0..1 in the same direction, so diagonals aren't
/// clipped and the first movement past the deadzone is small.
pub fn radial(v: [f32; 2], deadzone: f32) -> [f32; 2] {
let len = length(v);
if !len.is_finite() || len <= deadzone || len == 0.0 {
return [0.0, 0.0];
}
let scaled = ((len - deadzone) / (1.0 - deadzone)).min(1.0);
[v[0] / len * scaled, v[1] / len * scaled]
}
/// The left stick as the player's move vector, in `KeyboardInput`'s layout
/// (`[left, forward]`, length at most 1); `None` inside the deadzone.
pub fn move_vector(stick: [f32; 2], deadzone: f32) -> Option<[f32; 2]> {
let v = radial(stick, deadzone);
(v != [0.0, 0.0]).then_some([-v[0], v[1]])
}
/// Degrees per second at full tilt and the default sensitivity.
pub const YAW_SPEED: f32 = 200.0;
pub const PITCH_SPEED: f32 = 140.0;
/// The view turn from the right stick over `seconds`: `(yaw, pitch)` in
/// degrees, pitch positive looking down as in `Entity.turn`. A squared
/// curve keeps small tilts precise; a spyglass slows it down.
pub fn look_delta(
stick: [f32; 2],
settings: &PadSettings,
seconds: f32,
scoping: bool,
) -> (f32, f32) {
let v = radial(stick, settings.look_deadzone);
let len = length(v);
if len == 0.0 {
return (0.0, 0.0);
}
// The vector already has length `len`: scaling by it squares the tilt.
let curve = len;
let speed = settings.look_sensitivity * 2.0 * if scoping { 0.25 } else { 1.0 };
let x = v[0] * curve * if settings.invert_x { -1.0 } else { 1.0 };
let y = v[1] * curve * if settings.invert_y { -1.0 } else { 1.0 };
(
x * YAW_SPEED * speed * seconds,
-y * PITCH_SPEED * speed * seconds,
)
}
/// The hotbar slot after a bumper: one step with wrap-around.
pub fn hotbar_step(selected: usize, forward: bool) -> usize {
if forward {
(selected + 1) % 9
} else {
(selected + 8) % 9
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_follow_bedrock() {
let s = PadSettings::default();
assert_eq!(s.actions_of(Button::South), ["key.jump"]);
assert_eq!(s.actions_of(Button::RightTrigger), ["key.attack"]);
assert_eq!(s.actions_of(Button::LeftTrigger), ["key.use"]);
assert_eq!(s.actions_of(Button::North), ["key.inventory"]);
assert_eq!(s.actions_of(Button::RightBumper), [HOTBAR_NEXT]);
assert!(s.actions_of(Button::Start).is_empty());
// Every default action names a vanilla mapping or a pad action.
for (action, _) in ACTIONS {
assert!(
action.starts_with("pad.")
|| crate::keybinds::MAPPINGS.iter().any(|m| m.0 == *action),
"{action}"
);
}
}
#[test]
fn settings_round_trip_and_store_only_changes() {
let mut s = PadSettings::default();
assert!(!s.serialize().contains("bind_"));
s.bind("key.jump", Some(Button::East));
s.bind("key.drop", None);
s.bind("key.sneak", Some(Button::RightStick));
s.invert_y = true;
s.look_sensitivity = 0.75;
s.glyphs = GlyphStyle::PlayStation;
let text = s.serialize();
assert!(text.contains("bind_key.jump:east\n"));
assert!(text.contains("bind_key.drop:none\n"));
assert!(!text.contains("key.sneak"));
let back = PadSettings::parse(&text);
assert_eq!(back, s);
assert_eq!(back.binding("key.drop"), None);
assert_eq!(back.actions_of(Button::East), ["key.jump"]);
// Garbage keeps the defaults.
let odd =
PadSettings::parse("lookSensitivity:NaN\nbind_key.nope:south\nbind_key.jump:x9\n");
assert_eq!(odd, PadSettings::default());
}
#[test]
fn radial_deadzone_rescales() {
assert_eq!(radial([0.1, 0.05], 0.15), [0.0, 0.0]);
let full = radial([1.0, 0.0], 0.15);
assert!((full[0] - 1.0).abs() < 1e-6);
let half = radial([0.0, 0.575], 0.15);
assert!((half[1] - 0.5).abs() < 1e-6);
// A worn stick reporting more than 1 still caps at 1.
let over = radial([1.0, 1.0], 0.15);
assert!((length(over) - 1.0).abs() < 1e-6);
assert_eq!(move_vector([0.0, 0.0], 0.15), None);
let m = move_vector([1.0, 0.0], 0.15).unwrap();
assert!(m[0] < -0.99 && m[1] == 0.0, "right is negative left");
}
#[test]
fn look_turns_right_and_up() {
let s = PadSettings::default();
let (yaw, pitch) = look_delta([1.0, 0.0], &s, 1.0, false);
assert!((yaw - YAW_SPEED).abs() < 1e-3 && pitch == 0.0);
let (_, pitch) = look_delta([0.0, 1.0], &s, 0.5, false);
assert!((pitch + PITCH_SPEED * 0.5).abs() < 1e-3, "up looks up");
let inverted = PadSettings {
invert_y: true,
..PadSettings::default()
};
assert!(look_delta([0.0, 1.0], &inverted, 1.0, false).1 > 0.0);
let (small, _) = look_delta([0.5, 0.0], &s, 1.0, false);
assert!(
small < YAW_SPEED * 0.5,
"the curve is gentler near the centre"
);
assert_eq!(look_delta([0.05, 0.05], &s, 1.0, false), (0.0, 0.0));
assert!(look_delta([1.0, 0.0], &s, 1.0, true).0 < YAW_SPEED * 0.5);
}
#[test]
fn edges_with_trigger_hysteresis() {
let mut edges = Edges::default();
let mut state = PadState::default();
state.set(Button::South, true);
assert_eq!(edges.update(&state, 0.4), [(Button::South, true)]);
assert!(edges.update(&state, 0.4).is_empty());
state.triggers[1] = 0.45;
assert_eq!(edges.update(&state, 0.4), [(Button::RightTrigger, true)]);
state.triggers[1] = 0.35;
assert!(
edges.update(&state, 0.4).is_empty(),
"inside the hysteresis"
);
state.triggers[1] = 0.2;
state.set(Button::South, false);
assert_eq!(
edges.update(&state, 0.4),
[(Button::South, false), (Button::RightTrigger, false)]
);
state.set(Button::DPadUp, true);
edges.update(&state, 0.4);
assert_eq!(edges.release_all(), [(Button::DPadUp, false)]);
}
#[test]
fn merge_and_activity() {
let s = PadSettings::default();
let mut a = PadState::default();
assert!(!a.active(&s));
a.left = [0.1, 0.0];
assert!(!a.active(&s), "drift inside the deadzone");
let mut b = PadState::default();
b.set(Button::North, true);
b.left = [0.95, 0.0];
let m = a.merge(&b);
assert!(m.held(Button::North) && m.left[0] == 1.0 && m.active(&s));
}
#[test]
fn hotbar_wraps_and_glyphs_follow_the_vendor() {
assert_eq!(hotbar_step(8, true), 0);
assert_eq!(hotbar_step(0, false), 8);
assert_eq!(hotbar_step(3, true), 4);
assert_eq!(GlyphStyle::of_vendor(Some(0x054c)), GlyphStyle::PlayStation);
assert_eq!(GlyphStyle::of_vendor(Some(0x28de)), GlyphStyle::Xbox);
assert_eq!(GlyphStyle::of_vendor(None), GlyphStyle::Xbox);
}
}
+1
View File
@@ -53,6 +53,7 @@ pub mod flatgen;
pub mod fog;
pub mod font;
pub mod front;
pub mod gamepad;
pub mod gamerules;
pub mod gfx;
pub mod gizmos;
+11
View File
@@ -177,6 +177,8 @@ pub struct Settings {
pub sprint_window: i32,
/// Horizon's own graphics settings (`horizon-graphics.txt`, not options.txt).
pub horizon: crate::graphics::Graphics,
/// Controller settings (`horizon-controller.txt`, Horizon's own).
pub controller: crate::gamepad::PadSettings,
}
impl Default for Settings {
fn default() -> Self {
@@ -246,6 +248,7 @@ impl Default for Settings {
toggle_use: false,
sprint_window: 7,
horizon: Default::default(),
controller: Default::default(),
}
}
}
@@ -280,13 +283,19 @@ impl Settings {
.parent()
.map(crate::graphics::Graphics::load)
.unwrap_or_default();
let controller = path
.parent()
.map(crate::gamepad::PadSettings::load)
.unwrap_or_default();
let settings = match fs::read(path) {
Ok(bytes) => Self {
horizon,
controller,
..Self::parse(&String::from_utf8_lossy(&bytes))
},
Err(_) => Self {
horizon,
controller,
..Self::default()
},
};
@@ -385,6 +394,7 @@ impl Settings {
toggle_use: f.bool("toggleUse"),
sprint_window: f.int("sprintWindow"),
horizon: Default::default(),
controller: Default::default(),
auto_jump: f.bool("autoJump"),
language: f.string("lang"),
force_unicode: f.bool("forceUnicodeFont"),
@@ -517,6 +527,7 @@ impl Settings {
let _ = fs::write(path, self.serialize());
if let Some(dir) = path.parent() {
self.horizon.save(dir);
self.controller.save(dir);
}
}
/// Volume of a sound source (master excluded).
+20 -1
View File
@@ -11,10 +11,29 @@ pub struct Keys {
pub jump: bool,
pub shift: bool,
pub sprint: bool,
/// A controller stick's move vector (`[left, forward]`, Horizon's own),
/// used instead of the keys' direction while it is pushed.
pub analog: Option<[f32; 2]>,
}
impl Keys {
pub fn direction(self) -> [f32; 2] {
input::keyboard_direction(self.forward, self.backward, self.left, self.right)
match self.analog {
Some(v) => v,
None => input::keyboard_direction(self.forward, self.backward, self.left, self.right),
}
}
/// Add a stick's move vector: the direction flags code reading keys
/// (sprint, vehicles, the server's input packet) see are set past a
/// third of the travel.
pub fn with_stick(mut self, stick: Option<[f32; 2]>) -> Self {
if let Some([left, forward]) = stick {
self.forward |= forward > 0.3;
self.backward |= forward < -0.3;
self.left |= left > 0.3;
self.right |= left < -0.3;
self.analog = Some([left, forward]);
}
self
}
}
#[derive(Clone, Copy, Debug, Default)]
+174
View File
@@ -0,0 +1,174 @@
# Controllers
Horizon plays with PlayStation (DualShock 4, DualSense), Xbox (360, One,
Series) and Nintendo Switch Pro controllers, and on the Steam Deck with its
built-in controls. Keyboard and mouse keep working exactly as before: with no
controller connected, or with controllers turned off, nothing changes.
## What vanilla has
Nothing. Minecraft Java 26.3 never calls GLFW's gamepad or joystick API, has
no controller options and ships no button glyphs. Its only non-mouse UI input
is keyboard focus navigation (`InputType.KEYBOARD_ARROW` / `KEYBOARD_TAB`:
arrows and Tab move a focus ring between widgets). So controller support is
Horizon's own feature. It follows what players already know from Minecraft on
consoles (Bedrock Edition's default controller layout) and Horizon's menu
design for any new screen.
## Input layer
[gilrs](https://crates.io/crates/gilrs) reads the pads: evdev on Linux (with
libudev for hot-plugging), IOKit on macOS, Windows.Gaming.Input on Windows.
Its SDL mapping database normalizes every pad to one positional layout
(South/East/West/North face buttons, bumpers, triggers, sticks, D-pad,
Select/Start). No second windowing or event stack: gilrs is polled once per
loop iteration next to winit's events.
- The pure logic (mapping table, deadzones and curves, button edges, the
settings file, glyph choice) lives in `crates/horizon-client/src/gamepad.rs`
and is unit-tested. The game owns a thin gilrs backend and applies actions.
- Controller actions go through the same path a keyboard key takes after
rebinding: an action names a vanilla key mapping (`key.jump`, `key.attack`,
...), and the game handles it as that mapping's default key or mouse button.
Toggle sneak/sprint/attack/use, screens releasing held keys, and the
multiplayer client all behave as they do on the keyboard.
- Movement is analog: the left stick's direction and tilt feed the player's
move vector directly (a half-tilted stick walks slowly, like Bedrock),
instead of being rounded to WASD. The forward/back/left/right flags other
code reads (sprint start, boats, minecarts, the server's input packet) are
set when the stick passes a threshold.
- The pad last touched is the active one. Several pads are not merged.
- `horizon-ctl pad ...` injects a virtual pad (buttons, sticks, triggers) into
a running game, for tests without hardware.
## Default mapping
| Action | Xbox | PlayStation | Mapping |
|---|---|---|---|
| Move | Left stick | Left stick | analog `key.forward/back/left/right` |
| Look | Right stick | Right stick | camera |
| Jump / fly up | A | ✕ | `key.jump` |
| Drop item | B | ○ | `key.drop` |
| Swap offhand | X | □ | `key.swapOffhand` |
| Inventory | Y | △ | `key.inventory` |
| Hotbar left / right | LB / RB | L1 / R1 | Horizon `pad.hotbarPrevious/Next` |
| Use / place | LT | L2 | `key.use` |
| Attack / break | RT | R2 | `key.attack` |
| Sprint | Left stick click | L3 | `key.sprint` |
| Sneak (toggles) | Right stick click | R3 | `key.sneak` |
| Change camera | D-pad up | D-pad up | `key.togglePerspective` |
| Pick block | D-pad left | D-pad left | `key.pickItem` |
| Chat | D-pad right | D-pad right | `key.chat` |
| Advancements | D-pad down | D-pad down | `key.advancements` |
| Player list (hold) | View | Create / Share | `key.playerlist` |
| Pause / back | Menu | Options | Escape (fixed) |
The Guide / PS / Steam button is left to the system. Sneak on a stick click
toggles by default (holding a stick in while steering the camera is
awkward, which is why Bedrock does the same); the controls options can make it
hold-to-sneak.
## Menus and inventories
Vanilla's screens are all mouse-driven, and Horizon draws them 1:1, so a pad
drives them through a **virtual cursor** (as Bedrock's classic inventory UI
and Java's controller mods do), not focus navigation:
- Left stick moves the cursor with acceleration; in container screens the
cursor is gently pulled toward the nearest slot centre.
- D-pad steps one slot (18 GUI pixels in containers) or one widget row in
menus and snaps to it.
- A = left click (take / place stack, press a button), X = right click
(half stack / place one), Y = quick move (shift-click), B = back / close.
- LB / RB switch creative tabs and recipe book pages; right stick scrolls
(creative grid, lists, chat).
- Sliders: A grabs, the stick or D-pad left/right moves, A releases.
- Text fields: the Steam Deck's keyboard (Steam + X) types into them like a
real keyboard. Other platforms have no on-screen keyboard yet; text input
needs a keyboard.
The cursor is drawn only while the pad is the last-used input; moving the
mouse hands control back immediately.
## Glyphs
Horizon draws its own button glyphs in the HUD and screens (no Mojang
assets, nothing new from the player's jar): a small round or pill shape with
the label in the game font, sized to the GUI scale, with two styles:
- **Xbox / Steam Deck / generic**: A B X Y in their usual colours, LB RB LT
RT, View, Menu, stick icons.
- **PlayStation**: ✕ ○ □ △ drawn as shapes in their colours, L1 R1 L2 R2,
Create/Share, Options.
- **Nintendo**: B A Y X by position.
The style comes from the pad's USB vendor (Sony 054c, Microsoft 045e,
Nintendo 057e, Valve 28de) unless the controls options force one. Glyphs
replace key names where a prompt names a key (the controls list, tutorial
hints, "Press X to dismount") only while the pad is the last-used input.
## Options and remapping
Controller settings are Horizon's own and live in `horizon-controller.txt`
next to `options.txt`, like `horizon-graphics.txt`: `options.txt` stays
exactly vanilla's, so a vanilla client can share the game folder.
```
enabled:true
vibration:true
lookSensitivity:0.5
invertX:false
invertY:false
moveDeadzone:0.15
lookDeadzone:0.12
triggerThreshold:0.4
toggleSneak:true
glyphs:auto
bind_key.jump:south
bind_pad.hotbarNext:rb
```
Only bindings that differ from the defaults are written. The controls
options get a Controller page: on/off, vibration, look sensitivity, invert
X/Y, deadzones, glyph style, sneak toggle, and a binding list like the key
binds screen (pick an action, press a button; conflicts marked as vanilla
does; reset).
Deadzones are radial (the stick's length, so diagonals aren't clipped) and the
remaining range is rescaled to 0..1. Look uses a squared curve for precise
aim near the centre, up to 200°/s yaw and 140°/s pitch at the default
sensitivity, slower while scoping with a spyglass.
## Rumble
Vibration (on by default, off in the options) through gilrs force feedback:
taking damage (stronger with the damage), a block broken, an explosion nearby
(scaled by distance), a totem of undying, an elytra boost, a fish biting.
Short, low-intensity pulses, as on Bedrock. Linux (evdev force feedback,
including Steam Input's virtual pad) and Windows support it; macOS gilrs has
no force feedback, so it is silently skipped there.
## Steam Deck
- In Game Mode, or any game launched through Steam, Steam Input presents the
Deck's controls as a virtual Xbox pad: Horizon sees it like any Xbox pad
and uses Xbox-letter glyphs (the Deck's face buttons are A B X Y). Steam's
default "Gamepad" layout works with no setup; the trackpads stay mouse.
- Started outside Steam on the Deck, the kernel's `hid-steam` driver exposes
the controls as a gamepad too (while Steam isn't holding them), so it also
works out of the box.
- Text entry uses Steam's keyboard (Steam + X).
## PR plan
1. **Input layer and gameplay** (this note, gilrs, defaults, movement,
camera, actions, hotbar, B/Start to leave screens, `horizon-ctl pad`,
`horizon-controller.txt` with the look/deadzone settings).
2. **Menus and inventories**: virtual cursor, slot snapping, clicks, quick
move, tabs, scrolling, sliders.
3. **Glyphs and the Controller options page**: glyph drawing per pad type,
the options page, remapping UI.
4. **Rumble**.
Each is shippable alone. Testing is with unit tests, the injected pad and
vscreen screenshots; each PR says what still needs a real controller.
+1 -1
View File
@@ -28,7 +28,7 @@ WINDOWS_SYSTEM = {
LINUX_LOADER = "/lib64/ld-linux-x86-64.so.2"
LINUX_SYSTEM = {
"libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1",
"ld-linux-x86-64.so.2", "libasound.so.2",
"ld-linux-x86-64.so.2", "libasound.so.2", "libudev.so.1",
}