From 9f0df29d6c2efdb295c518e84f35c118ceef81e0 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:15:54 -0400 Subject: [PATCH 01/30] Keep the inventory tab in the creative screen --- crates/horizon-client/src/creative.rs | 52 ++++ crates/horizon-client/src/game.rs | 259 ++++++++++++++------ tests/test_creative_inventory_transition.py | 58 +++++ tests/test_hand_frame_policy.py | 62 +++++ 4 files changed, 351 insertions(+), 80 deletions(-) create mode 100644 tests/test_creative_inventory_transition.py create mode 100644 tests/test_hand_frame_policy.py diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index b696348f2..6ea7e6b14 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -67,6 +67,32 @@ impl Names { impl Creative { pub const WIDTH: f32 = 195.0; pub const HEIGHT: f32 = 136.0; + pub const TRASH_POSITION: (f32, f32) = (173.0, 112.0); + + /// Visible player slots in the creative inventory tab (game slot ids). + pub fn inventory_slots() -> impl Iterator { + (0..36).chain(500..505) + } + + /// CreativeModeInventoryScreen.selectTab positions its InventoryMenu wrappers. + pub fn inventory_slot_position(slot: usize) -> Option<(f32, f32)> { + match slot { + 0..9 => Some((9.0 + slot as f32 * 18.0, 112.0)), + 9..36 => Some(( + 9.0 + ((slot - 9) % 9) as f32 * 18.0, + 54.0 + ((slot - 9) / 9) as f32 * 18.0, + )), + 500..504 => { + let position = slot - 500; + Some(( + 54.0 + (position / 2) as f32 * 54.0, + 6.0 + (position % 2) as f32 * 27.0, + )) + } + 504 => Some((35.0, 20.0)), + _ => None, + } + } /// The scrollbar track (insideScrollbar), relative to the screen origin. pub const SCROLL_X: f32 = 175.0; pub const SCROLL_Y: f32 = 18.0; @@ -391,6 +417,32 @@ mod tests { Creative::from_json(&raw).unwrap() } + #[test] + fn inventory_tab_slot_layout_matches_vanilla() { + assert_eq!(Creative::inventory_slots().count(), 41); + for (slot, expected) in [ + (0, (9.0, 112.0)), + (8, (153.0, 112.0)), + (9, (9.0, 54.0)), + (35, (153.0, 90.0)), + (500, (54.0, 6.0)), + (501, (54.0, 33.0)), + (502, (108.0, 6.0)), + (503, (108.0, 33.0)), + (504, (35.0, 20.0)), + ] { + assert_eq!(Creative::inventory_slot_position(slot), Some(expected)); + } + assert_eq!(Creative::inventory_slot_position(100), None); + assert_eq!(Creative::TRASH_POSITION, (173.0, 112.0)); + let mut c = creative(90); + c.select(2); + assert!(c.tab().inventory); + assert!(!c.can_scroll(&Names { + map: HashMap::new() + })); + } + #[test] fn hidden_tabs_are_skipped() { let c = creative(0); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a0d350a6b..594eb9325 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3392,7 +3392,13 @@ impl Game<'_> { self.draw_book(&mut batch); batch } + fn creative_inventory_open(&self) -> bool { + self.screen == Screen::Creative && self.creative_screen.tab().inventory + } fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) { + if self.creative_inventory_open() { + return Self::creative_origin(batch); + } let (x, y) = batch.centered_origin(176.0, self.screen_height()); (x + self.recipe_book_shift(batch.width), y) } @@ -3403,6 +3409,9 @@ impl Game<'_> { } /// 300.. are the open container's slots. fn slots(&self) -> Vec { + if self.creative_inventory_open() { + return Creative::inventory_slots().collect(); + } if let Some(v) = self.station_slots().or_else(|| self.mount_slots()) { return v; } @@ -3433,6 +3442,11 @@ impl Game<'_> { } /// InventoryMenu / CraftingMenu slot layouts. fn slot_position(&self, i: usize) -> (f32, f32) { + if self.creative_inventory_open() + && let Some(position) = Creative::inventory_slot_position(i) + { + return position; + } if let Some(p) = self .station_slot_position(i) .or_else(|| self.machine_slot_position(i)) @@ -3542,6 +3556,32 @@ impl Game<'_> { .find_with(&grid, n, &scale) .map(|(name, result)| (name.to_owned(), result)) } + fn draw_inventory_slots(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { + for i in self.slots() { + let (sx, sy) = self.slot_position(i); + if i == 504 && self.offhand.is_none() { + batch.sprite( + &self.res.atlas, + "gui/sprites/container/slot/shield", + ox + sx, + oy + sy, + ); + } + if (500..504).contains(&i) && self.armor[i - 500].is_none() { + let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; + batch.sprite( + &self.res.atlas, + &format!("gui/sprites/container/slot/{icon}"), + ox + sx, + oy + sy, + ); + } + let stack = self.slot_view(i); + if let Some(stack) = stack { + self.draw_item(batch, &stack, ox + sx, oy + sy); + } + } + } fn draw_inventory(&mut self, batch: &mut HudBatch) { if self.draw_station(batch) { return; @@ -3668,30 +3708,7 @@ impl Game<'_> { if self.container.is_none() && self.craft_size != 3 && !self.mount_active() { self.draw_inventory_player(batch, ox, oy); } - for i in self.slots() { - let (sx, sy) = self.slot_position(i); - if i == 504 && self.offhand.is_none() { - batch.sprite( - &self.res.atlas, - "gui/sprites/container/slot/shield", - ox + sx, - oy + sy, - ); - } - if (500..504).contains(&i) && self.armor[i - 500].is_none() { - let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; - batch.sprite( - &self.res.atlas, - &format!("gui/sprites/container/slot/{icon}"), - ox + sx, - oy + sy, - ); - } - let stack = self.slot_view(i); - if let Some(stack) = stack { - self.draw_item(batch, &stack, ox + sx, oy + sy); - } - } + self.draw_inventory_slots(batch, ox, oy); self.draw_recipe_book(batch); if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); @@ -7260,63 +7277,100 @@ impl Game<'_> { ); } let atlas = &self.res.atlas; - batch.text( - atlas, - &tab.title, - ox + 8.0, - oy + 6.0, - rgba(64, 64, 64, 255), - false, - ); + if !tab.inventory { + batch.text( + atlas, + &tab.title, + ox + 8.0, + oy + 6.0, + rgba(64, 64, 64, 255), + false, + ); + } if tab.search { let shown = format!("{}_", self.creative_screen.search); batch.text(atlas, &shown, ox + 82.0, oy + 6.0, u32::MAX, true); } - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); let mut hovered: Option = None; - for r in 0..5 { - for c in 0..9 { - let Some(stack) = items.get((first + r) * 9 + c) else { - continue; - }; - let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); - self.draw_item(batch, stack, x, y); - if self.cursor.0 >= x - && self.cursor.0 < x + 16.0 - && self.cursor.1 >= y - && self.cursor.1 < y + 16.0 - { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); - hovered = Some(stack.item.to_string()); - } + if tab.inventory { + self.draw_player_preview( + batch, + ox + 73.0, + oy + 6.0, + ox + 105.0, + oy + 49.0, + 20.0, + 0.0625, + ); + self.draw_inventory_slots(batch, ox, oy); + if Self::creative_trash_hovered(batch, self.cursor) { + let (x, y) = Creative::TRASH_POSITION; + batch.fill( + &self.res.atlas, + ox + x, + oy + y, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); } - } - for c in 0..9 { - let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0); - if let Some(stack) = self.inventory[c].clone() { - self.draw_item(batch, &stack, x, y); - if self.cursor.0 >= x - && self.cursor.0 < x + 16.0 - && self.cursor.1 >= y - && self.cursor.1 < y + 16.0 - { - hovered = Some(stack.item.to_string()); - } + if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { + let (x, y) = self.slot_position(slot); + batch.fill( + &self.res.atlas, + ox + x, + oy + y, + 16.0, + 16.0, + rgba(255, 255, 255, 128), + ); } - } - let scrollable = self.creative_screen.rows(&self.res.names) > 5; - let scroller = if scrollable { - "gui/sprites/container/creative_inventory/scroller" } else { - "gui/sprites/container/creative_inventory/scroller_disabled" - }; - batch.sprite( - &self.res.atlas, - scroller, - ox + Creative::SCROLL_X, - oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), - ); + let items = self.creative_screen.items(&self.res.names); + let first = self.creative_screen.first_row(&self.res.names); + for r in 0..5 { + for c in 0..9 { + let Some(stack) = items.get((first + r) * 9 + c) else { + continue; + }; + let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 18.0 + r as f32 * 18.0); + self.draw_item(batch, stack, x, y); + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { + batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + hovered = Some(stack.item.to_string()); + } + } + } + for c in 0..9 { + let (x, y) = (ox + 9.0 + c as f32 * 18.0, oy + 112.0); + if let Some(stack) = self.inventory[c].clone() { + self.draw_item(batch, &stack, x, y); + if self.cursor.0 >= x + && self.cursor.0 < x + 16.0 + && self.cursor.1 >= y + && self.cursor.1 < y + 16.0 + { + hovered = Some(stack.item.to_string()); + } + } + } + let scrollable = self.creative_screen.rows(&self.res.names) > 5; + let scroller = if scrollable { + "gui/sprites/container/creative_inventory/scroller" + } else { + "gui/sprites/container/creative_inventory/scroller_disabled" + }; + batch.sprite( + &self.res.atlas, + scroller, + ox + Creative::SCROLL_X, + oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), + ); + } for t in &tabs { let (tx, ty) = Creative::tab_position(t); if self.cursor.0 >= ox + tx @@ -7329,11 +7383,28 @@ impl Game<'_> { } if let Some(stack) = self.carried.clone() { self.draw_item(batch, &stack, self.cursor.0 - 8.0, self.cursor.1 - 8.0); - } else if let Some(item) = hovered { + } + if tab.inventory { + if Self::creative_trash_hovered(batch, self.cursor) { + self.tooltip(batch, "Destroy Item", self.cursor.0, self.cursor.1); + } else { + self.draw_slot_tooltip(batch); + } + } else if self.carried.is_none() + && let Some(item) = hovered + { let name = self.res.names.item(&item); self.tooltip(batch, &name, self.cursor.0, self.cursor.1); } } + fn creative_trash_hovered(batch: &HudBatch, cursor: (f32, f32)) -> bool { + let (ox, oy) = Self::creative_origin(batch); + let (x, y) = Creative::TRASH_POSITION; + cursor.0 >= ox + x + && cursor.0 < ox + x + 16.0 + && cursor.1 >= oy + y + && cursor.1 < oy + y + 16.0 + } fn click_creative(&mut self, right: bool) { let Some(size) = self .renderer @@ -7349,14 +7420,36 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { let (tx, ty) = Creative::tab_position(t); if cx >= ox + tx && cx < ox + tx + 26.0 && cy >= oy + ty && cy < oy + ty + 32.0 { - if t.inventory { - self.screen = Screen::Inventory; - return; - } self.creative_screen.select(i); + self.inv_drag = None; + self.last_inv_click = None; return; } } + if self.creative_inventory_open() { + if Self::creative_trash_hovered(&batch, self.cursor) { + if self.keys.contains(&KeyCode::ShiftLeft) + || self.keys.contains(&KeyCode::ShiftRight) + { + self.inventory.fill(None); + self.armor.fill(None); + self.offhand = None; + self.craft_grid[..4].fill(None); + self.apply_equipment(); + } else { + self.carried = None; + } + self.inv_drag = None; + } else if self.slot_at(&batch, cx, cy).is_some() + || !(cx >= ox + && cx < ox + Creative::WIDTH + && cy >= oy + && cy < oy + Creative::HEIGHT) + { + self.inventory_press(right); + } + return; + } // Holding the scrollbar scrolls as the mouse moves (mouseDragged). if !right && self @@ -7670,7 +7763,7 @@ impl Game<'_> { } else { Vec::new() }; - let hand = if title || self.screen == Screen::Inventory || self.scoping() { + let hand = if title || self.scoping() { Vec::new() } else { self.hand_geometry(alpha) @@ -7861,7 +7954,8 @@ impl Game<'_> { | KeyCode::Digit9 | KeyCode::KeyF | KeyCode::KeyQ - if self.screen == Screen::Inventory && self.inventory_hotkey(key) => {} + if (self.screen == Screen::Inventory || self.creative_inventory_open()) + && self.inventory_hotkey(key) => {} KeyCode::KeyT if self.screen == Screen::Inventory => self.recipe_focus_search(), KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), // key.advancements. @@ -8199,6 +8293,8 @@ impl ApplicationHandler for Game<'_> { } if self.screen == Screen::Inventory { self.loom_drag(); + } + if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } if self.dragging && self.screen == Screen::Options { @@ -8354,6 +8450,9 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); } + Screen::Creative if self.creative_screen.tab().inventory => { + self.inventory_release(); + } Screen::Creative if button == MouseButton::Left => { self.creative_screen.release(); } diff --git a/tests/test_creative_inventory_transition.py b/tests/test_creative_inventory_transition.py new file mode 100644 index 000000000..2c3a5d7b1 --- /dev/null +++ b/tests/test_creative_inventory_transition.py @@ -0,0 +1,58 @@ +"""Exercise the real creative-tab selection branch without a desktop window.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class CreativeInventoryTransitionTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the tab-selection probe") + def test_inventory_tab_stays_in_the_creative_screen(self): + source = (ROOT / "crates/horizon-client/src/game.rs").read_text() + click = source.split("fn click_creative(&mut self, right: bool)", 1)[1] + branch = click.split("if cx >= ox + tx", 1)[1] + branch = branch.split("{", 1)[1].split("\n }\n", 1)[0] + program = """ +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Screen { Creative, Inventory } +struct Tab { inventory: bool } +struct Creative { selected: usize, tabs: [Tab; 2] } +impl Creative { fn select(&mut self, i: usize) { self.selected = i; } } +struct Game { screen: Screen, creative_screen: Creative, inv_drag: Option, last_inv_click: Option } +impl Game { + fn click_tab(&mut self, i: usize) { + let t = &self.creative_screen.tabs[i]; + SELECTION + } +} +#[test] +fn inventory_and_back_preserve_the_creative_screen() { + let mut game = Game { screen: Screen::Creative, + creative_screen: Creative { selected: 0, tabs: [Tab { inventory: false }, Tab { inventory: true }] }, + inv_drag: Some(1), last_inv_click: Some(2) }; + game.click_tab(1); + assert_eq!(game.screen, Screen::Creative); + assert_eq!(game.creative_screen.selected, 1); + assert!(game.inv_drag.is_none() && game.last_inv_click.is_none()); + game.click_tab(0); + assert_eq!(game.screen, Screen::Creative); + assert_eq!(game.creative_screen.selected, 0); +} +""".replace("SELECTION", branch) + with tempfile.TemporaryDirectory(prefix="horizon-creative-tab-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + compiled = subprocess.run( + ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")], + capture_output=True, text=True, check=False, + ) + self.assertEqual(compiled.returncode, 0, compiled.stderr) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hand_frame_policy.py b/tests/test_hand_frame_policy.py new file mode 100644 index 000000000..e9a83245a --- /dev/null +++ b/tests/test_hand_frame_policy.py @@ -0,0 +1,62 @@ +"""Compile the real frame hand-selection expression without opening a window.""" +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class HandFramePolicyTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the frame-policy probe") + def test_inventory_screen_does_not_suppress_first_person_geometry(self): + source = (ROOT / "crates/horizon-client/src/game.rs").read_text() + match = re.search(r"let hand = (if .*?);\s*let screen =", source, re.S) + self.assertIsNotNone(match, "frame hand-selection seam changed") + selection = match.group(1) + # Only geometry generation is stubbed; execute the actual frame guard. + program = """ +#[derive(Clone, Copy, PartialEq, Eq)] +enum Screen { Playing, Creative, Inventory } +struct Game { screen: Screen, scoping: bool } +impl Game { + fn scoping(&self) -> bool { self.scoping } + fn hand_geometry(&mut self, _: f64) -> Vec { vec![1] } + fn hand_len(&mut self, title: bool) -> usize { + let alpha = 0.0; + let hand = SELECTION; + hand.len() + } +} +#[test] +fn creative_inventory_and_return_keep_the_hand() { + let mut game = Game { screen: Screen::Playing, scoping: false }; + for screen in [Screen::Playing, Screen::Creative, Screen::Inventory, Screen::Playing] { + game.screen = screen; + assert_eq!(game.hand_len(false), 1); + } +} +#[test] +fn title_and_spyglass_still_hide_the_hand() { + let mut game = Game { screen: Screen::Inventory, scoping: false }; + assert_eq!(game.hand_len(true), 0); + game.scoping = true; + assert_eq!(game.hand_len(false), 0); +} +""".replace("SELECTION", selection) + with tempfile.TemporaryDirectory(prefix="horizon-hand-policy-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + compiled = subprocess.run( + ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")], + capture_output=True, text=True, check=False, + ) + self.assertEqual(compiled.returncode, 0, compiled.stderr) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() From 767ed4cb47b714631209cc9e906dc4b40ac9b37d Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:21:01 -0400 Subject: [PATCH 02/30] Use physical Ctrl state for stack dropping, not toggle sprint --- crates/horizon-client/src/game.rs | 6 ++- crates/horizon-client/src/game/agent.rs | 9 +--- tests/test_drop_modifier_policy.py | 55 +++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 10 deletions(-) create mode 100644 tests/test_drop_modifier_policy.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 594eb9325..5156e685c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4170,7 +4170,8 @@ impl Game<'_> { (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap), (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap), (None, KeyCode::KeyQ) => { - let all = self.keys.contains(&KeyCode::ControlLeft); + let all = self.physical_keys.contains(&KeyCode::ControlLeft) + || self.physical_keys.contains(&KeyCode::ControlRight); self.menu_click(Some(slot), i32::from(all), Input::Throw) } _ => false, @@ -8001,7 +8002,8 @@ impl Game<'_> { self.using = None; } KeyCode::KeyQ if self.screen == Screen::Playing => { - let all = self.keys.contains(&KeyCode::ControlLeft); + let all = self.physical_keys.contains(&KeyCode::ControlLeft) + || self.physical_keys.contains(&KeyCode::ControlRight); self.drop_held(all); } KeyCode::Digit1 diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 2de1f4c74..8b1b8071e 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1232,14 +1232,7 @@ impl Game<'_> { self.playing()?; let all = a.pos.first() == Some(&"all"); let before = self.held().map(|s| self.stack_value(s)); - if all { - self.keys.insert(KeyCode::ControlLeft); - } - let result = self.key_pressed(KeyCode::KeyQ); - if all { - self.keys.remove(&KeyCode::ControlLeft); - } - result?; + self.drop_held(all); ok( json!({ "ok": true, "dropped_from": before, "held": self.held().map(|s| self.stack_value(s)) }), ) diff --git a/tests/test_drop_modifier_policy.py b/tests/test_drop_modifier_policy.py new file mode 100644 index 000000000..76415f876 --- /dev/null +++ b/tests/test_drop_modifier_policy.py @@ -0,0 +1,55 @@ +"""Drop modifiers must come from physical Ctrl, not the sprint key mapping.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class DropModifierPolicyTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the drop-policy probe") + def test_playing_and_inventory_drop_ignore_latched_sprint(self): + source = (ROOT / "crates/horizon-client/src/game.rs").read_text() + inventory = source.split("fn inventory_hotkey(", 1)[1] + playing = source.split("KeyCode::KeyQ if self.screen == Screen::Playing =>", 1)[1] + expressions = [section.split("let all = ", 1)[1].split(";", 1)[0] + for section in (inventory, playing)] + program = """ +use std::collections::HashSet; +#[derive(PartialEq, Eq, Hash)] enum KeyCode { ControlLeft, ControlRight } +struct Game { keys: HashSet, physical_keys: HashSet } +impl Game { + fn inventory_drop_all(&self) -> bool { INVENTORY } + fn playing_drop_all(&self) -> bool { PLAYING } +} +#[test] +fn sprint_and_control_are_independent() { + for sprint in [false, true] { + for held in 0..4 { + let ctrl = held != 0; + let mut game = Game { keys: HashSet::new(), physical_keys: HashSet::new() }; + if held & 1 != 0 { game.physical_keys.insert(KeyCode::ControlLeft); } + if held & 2 != 0 { game.physical_keys.insert(KeyCode::ControlRight); } + if sprint { game.keys.insert(KeyCode::ControlLeft); } + assert_eq!(game.inventory_drop_all(), ctrl, "inventory: sprint={sprint}, ctrl={ctrl}"); + assert_eq!(game.playing_drop_all(), ctrl, "playing: sprint={sprint}, ctrl={ctrl}"); + } + } +} +""".replace("INVENTORY", expressions[0]).replace("PLAYING", expressions[1]) + with tempfile.TemporaryDirectory(prefix="horizon-drop-policy-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + compiled = subprocess.run( + ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")], + capture_output=True, text=True, check=False, + ) + self.assertEqual(compiled.returncode, 0, compiled.stderr) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() From 0818190ee4b23f93857d65e9f4dd39f35ea8e7d0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:06:50 +0200 Subject: [PATCH 03/30] docs: controller support design note Vanilla 26.3 has no gamepad code; Horizon's own design follows Bedrock's default controller layout. Mapping, menus, glyphs, options file, rumble, Steam Deck and the PR plan. Co-Authored-By: Claude Opus 5.5 --- docs/controllers.md | 174 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 docs/controllers.md diff --git a/docs/controllers.md b/docs/controllers.md new file mode 100644 index 000000000..74aea46da --- /dev/null +++ b/docs/controllers.md @@ -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. From 74821bf1883b97f9717179ec23953c876d965130 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:02:42 +0200 Subject: [PATCH 04/30] Overlay texels from OverlayTexture, and the creeper's white flash The hurt red and the white row's alphas come from overlay.rs, which reproduces OverlayTexture's texels (checked against values printed by the 26.3 JVM) and is prepended to entity.wgsl; a test parses and validates the composed shader with naga. Swelling creepers flash white as CreeperRenderer.getWhiteOverlayProgress says (the white row's column, red winning while hurt; layers keep the red only), and CreeperRenderer.scale's wobble uses the unclamped swelling as vanilla does. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/Cargo.toml | 4 + crates/horizon-client/src/entity.wgsl | 12 +-- crates/horizon-client/src/gfx.rs | 17 +++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs/render.rs | 34 ++++++-- crates/horizon-client/src/overlay.rs | 102 +++++++++++++++++++++++ 7 files changed, 156 insertions(+), 15 deletions(-) create mode 100644 crates/horizon-client/src/overlay.rs diff --git a/Cargo.lock b/Cargo.lock index 2a9d0cd47..8937812b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -848,6 +848,7 @@ dependencies = [ "horizon-world", "log", "miniz_oxide 0.8.9", + "naga", "png", "pollster", "serde_json", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index f602eac7b..97e3fb217 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -35,3 +35,7 @@ rng-trace = ["horizon-core/rng-trace"] [lints] workspace = true + +[dev-dependencies] +# Parses and validates the composed entity shader (already built for wgpu). +naga = { version = "30.0.1", features = ["wgsl-in"] } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 18cb01230..44ae40766 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -48,12 +48,14 @@ fn entity_light(normal: vec3, nether: bool) -> f32 { let l1 = normalize(vec3(-0.2, select(1.0, -1.0, nether), 0.7)); return min(1.0, (max(0.0, dot(l0, normal)) + max(0.0, dot(l1, normal))) * 0.6 + 0.4); } -// The OverlayTexture texel entity.vsh fetches: rows 0-7 hold the hurt red -// 0xB2FF0000; row 10 is white with alpha (1 - u / 15 * 0.75) * 255, u = 15 -// for the primed TNT flash (OverlayTexture.u(1.0)), so 63. Alpha 1 changes nothing. +// The OverlayTexture texel entity.vsh fetches (constants from overlay.rs): +// the hurt red for overlays 1 and 8, the white row at column 15 for the +// primed TNT flash (5) and at column overlay - 16 for 16..=31 (a creeper's +// swelling). Alpha 1 changes nothing. fn overlay_texel(overlay: u32) -> vec4 { - if overlay == 1u || overlay == 8u { return vec4(1.0, 0.0, 0.0, 178.0 / 255.0); } - if overlay == 5u { return vec4(1.0, 1.0, 1.0, 63.0 / 255.0); } + if overlay == 1u || overlay == 8u { return HURT_OVERLAY; } + if overlay == 5u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[15]); } + if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 4c539156e..dd4965782 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -23,6 +23,11 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState { alpha: wgpu::BlendComponent::REPLACE, }; +/// entity.wgsl after the OverlayTexture constants it reads. +fn entity_shader() -> String { + crate::overlay::wgsl_constants() + include_str!("entity.wgsl") +} + // Separate special materials without changing entity order or their overlays. fn batch_entities( entities: &[Vertex], @@ -826,7 +831,7 @@ impl Renderer { hud.atlas_texture = Some(atlas.clone()); let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon entities"), - source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()), + source: wgpu::ShaderSource::Wgsl(entity_shader().into()), }); let entity_bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Entity bindings"), @@ -2573,6 +2578,16 @@ mod tests { ); } #[test] + fn entity_shader_validates_with_its_overlay_constants() { + let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } + #[test] fn cracks_multiply_instead_of_covering_the_block() { let blend = super::CRUMBLING_BLEND; assert_eq!(blend.color.src_factor, wgpu::BlendFactor::Dst); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 70c4ed119..02ea309db 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -95,6 +95,7 @@ pub mod options_file; pub mod options_fixes; pub mod options_horizon; pub mod options_ui; +pub mod overlay; pub mod pack_screen; pub mod packs; pub mod particles; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 266a1f4dd..638d1d5c1 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -778,6 +778,25 @@ fn species_rotations(m: &Mob, alpha: f32) -> glam::Mat4 { _ => glam::Mat4::IDENTITY, } } +/// Creeper.getSwelling: the fuse's progress, past 1 in its last two ticks. +fn creeper_swelling(m: &Mob, alpha: f32) -> f32 { + (m.previous_swell as f32 + alpha * (m.swell - m.previous_swell) as f32) / 28.0 +} +/// LivingEntityRenderer.getOverlayCoords for the body: the hurt red, or a +/// swelling creeper's white flash. Layers take the red only (progress 0). +fn body_overlay(m: &Mob, alpha: f32) -> u32 { + let white = if m.species() == Species::Creeper { + crate::overlay::creeper_progress(creeper_swelling(m, alpha)) + } else { + 0.0 + }; + crate::overlay::living(white, red_overlay(m)) +} +/// LivingEntityRenderState.hasRedOverlay: hurt or dying (not a creaking +/// tearing down). +fn red_overlay(m: &Mob) -> bool { + m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)) +} fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { match m.species() { Species::Wither => { @@ -785,10 +804,9 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 { } Species::Creeper => { // CreeperRenderer.scale: swelling with a wobble. - let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha) - / 28.0) - .clamp(0.0, 1.0); - let wobble = 1.0 + (s * 100.0).msin() * s * 0.01; + let g = creeper_swelling(m, alpha); + let wobble = 1.0 + (g * 100.0).msin() * g * 0.01; + let s = g.clamp(0.0, 1.0); let s4 = s * s * s * s; let xz = (1.0 + s4 * 0.4) * wobble; let y = (1.0 + s4 * 0.1) / wobble; @@ -923,8 +941,7 @@ fn render_visible( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = - u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); + let overlay = u32::from(red_overlay(m)); let s = anim::state(m, alpha); let (model_key, texture) = body(m); let model = m @@ -942,7 +959,7 @@ fn render_visible( uv, body_color(m, alpha), light, - overlay, + body_overlay(m, alpha), out, ); } @@ -1013,8 +1030,7 @@ pub fn render_single( out: &mut Vec, ) { let base = base_transform(m, alpha, camera); - let overlay = - u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m))); + let overlay = body_overlay(m, alpha); let s = anim::state(m, alpha); let model = m.kind.model.clone(); let mut poses = Poses::new(&model); diff --git a/crates/horizon-client/src/overlay.rs b/crates/horizon-client/src/overlay.rs new file mode 100644 index 000000000..2d27629a5 --- /dev/null +++ b/crates/horizon-client/src/overlay.rs @@ -0,0 +1,102 @@ +//! OverlayTexture: the hurt red and white flash entity.wgsl mixes over a lit +//! entity before the lightmap (entity.fsh), and the overlay codes models carry. +//! +//! Vanilla's 16 by 16 texture: rows 0 to 7 are the hurt red, row 10 is white +//! with an alpha falling with u; LivingEntityRenderer.getOverlayCoords picks +//! u from the white overlay progress and row 3 when the entity is hurt. + +/// The overlay code of white flashes: `WHITE + u`, u in 1..=15. +pub const WHITE: u32 = 16; +/// The hurt red (rows 0 to 7) as RGBA bytes: 0xB2FF0000. +pub const HURT_TEXEL: [u8; 4] = [255, 0, 0, 0xB2]; + +/// The white row's alpha at column u: `(int) ((1 - u / 15 * 0.75) * 255)` +/// in float precision. +pub fn white_alpha(u: u32) -> u8 { + ((1.0f32 - u as f32 / 15.0 * 0.75) * 255.0) as u8 +} + +/// OverlayTexture.u: the column of a white overlay progress. +pub fn white_column(progress: f32) -> u32 { + (progress * 15.0) as u32 +} + +/// LivingEntityRenderer.getOverlayCoords as entity.wgsl's overlay code: the +/// red row hides the white column; column 0 of the white row is opaque white +/// with full alpha, so no overlay. +pub fn living(white_progress: f32, red: bool) -> u32 { + if red { + return 1; + } + match white_column(white_progress) { + 0 => 0, + u => WHITE + u.min(15), + } +} + +/// CreeperRenderer.getWhiteOverlayProgress: flashing every other tenth of +/// the swelling, at least half white. +pub fn creeper_progress(swelling: f32) -> f32 { + if (swelling * 10.0) as i32 % 2 == 0 { + 0.0 + } else { + swelling.clamp(0.5, 1.0) + } +} + +/// The texels as WGSL constants, prepended to entity.wgsl. +pub fn wgsl_constants() -> String { + let [r, g, b, a] = HURT_TEXEL.map(|v| format!("{v}.0 / 255.0")); + let white: Vec = (0..16) + .map(|u| format!("{}.0 / 255.0", white_alpha(u))) + .collect(); + format!( + "// OverlayTexture (overlay.rs): the hurt texel and the white row's alpha by column.\n\ + const HURT_OVERLAY = vec4({r}, {g}, {b}, {a});\n\ + const WHITE_OVERLAY_ALPHA = array({});\n", + white.join(", ") + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn texels_are_vanilla_s() { + // OverlayTexture's constructor, printed by the 26.3 JVM. + let vanilla = [ + 255, 242, 229, 216, 203, 191, 178, 165, 152, 140, 127, 114, 101, 89, 76, 63, + ]; + assert_eq!((0..16).map(white_alpha).collect::>(), vanilla); + assert_eq!( + u32::from_be_bytes([HURT_TEXEL[3], HURT_TEXEL[0], HURT_TEXEL[1], HURT_TEXEL[2]]), + 0xB2FF_0000 + ); + } + + #[test] + fn creeper_flashes_like_vanilla() { + // (swelling, OverlayTexture.u(getWhiteOverlayProgress)) from the JVM. + let vanilla = [ + (0.05, 0), + (0.1, 7), + (0.19, 7), + (0.2, 0), + (0.3, 7), + (0.49, 0), + (0.5, 7), + (0.55, 8), + (0.7, 10), + (0.75, 11), + (0.95, 14), + (1.0, 0), + ]; + for (swelling, u) in vanilla { + assert_eq!(white_column(creeper_progress(swelling)), u, "{swelling}"); + } + assert_eq!(living(creeper_progress(0.55), false), WHITE + 8); + assert_eq!(living(creeper_progress(0.55), true), 1); + assert_eq!(living(0.0, false), 0); + } +} From 8355a6ff14add2bb34cf2d30037b3ea5ef721bc6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:10:13 +0200 Subject: [PATCH 05/30] horizon-prepare sounds: the sound copy in Rust, run by the launcher tools/fetch_sounds.py (and the lab.py functions it used) becomes `horizon-prepare sounds` (horizon_prepare::sounds): the pinned asset index, sounds.json and every .ogg from the player's own launcher install, each SHA-1 checked, into .local/horizon-client/. The launcher runs it as part of Prepare (in-process, the version's own binary when its sources differ and it knows the subcommand, in-process for older versions), and a launcher install without the assets only logs that the game will be silent. Player docs no longer mention Python for sound. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- crates/horizon-prepare/src/artifacts.rs | 11 +- crates/horizon-prepare/src/lib.rs | 3 + crates/horizon-prepare/src/main.rs | 18 +- crates/horizon-prepare/src/sounds.rs | 299 ++++++++++++++++++++++++ docs/native-client.md | 11 +- launcher/README.md | 4 +- launcher/src/backend.rs | 49 +++- launcher/src/cli.rs | 4 +- launcher/src/main.rs | 18 +- launcher/src/mcp.rs | 6 +- packaging/PLAY.txt | 8 +- tools/audio_harness.py | 2 +- tools/fetch_sounds.py | 36 --- tools/package_native_client.py | 2 +- 15 files changed, 408 insertions(+), 65 deletions(-) create mode 100644 crates/horizon-prepare/src/sounds.rs delete mode 100644 tools/fetch_sounds.py diff --git a/README.md b/README.md index cf56bd042..68631e117 100644 --- a/README.md +++ b/README.md @@ -141,7 +141,7 @@ Horizon contains no game files and never downloads them. It builds its resources git clone https://github.com/ludovic111/horizon.git cd horizon cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar # needs JDK 25 -python3 tools/fetch_sounds.py # optional: sounds from your launcher install +cargo run --release -p horizon-prepare -- sounds # optional: sounds from your launcher install cargo run --release -p horizon-client ``` diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index c3aa10280..a3e6c2cc0 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -22,6 +22,11 @@ fn hint(text: &str, version: &str) -> String { text.replace("{version}", version) } +/// What to do when the player's launcher install lacks the pinned version's files. +pub(crate) fn launcher_hint(version: &str) -> String { + hint(LAUNCHER_HINT, version) +} + /// research-lock.json and the folder the pinned version's files go to. pub struct Lock { pub json: Value, @@ -120,7 +125,7 @@ pub fn minecraft_dir(chosen: Option<&Path>) -> PathBuf { /// Copy one file from the player's install, checked like a download; an existing verified /// copy is kept. -fn import_copy( +pub(crate) fn import_copy( source: &Path, destination: &Path, checksum: &str, @@ -156,7 +161,7 @@ fn import_copy( /// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins /// over the cached one so the manifest matches the asset index installed alongside it. -fn import_manifest(lock: &Lock, minecraft: &Path) -> Result { +pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result { let version = &lock.version; let destination = lock.directory.join("manifest.json"); let source = minecraft @@ -355,7 +360,7 @@ fn client_library_artifacts(manifest: &Value) -> Result, String> { } /// A relative path with only normal components and forward slashes, from a manifest or bundle. -fn safe_relative(path: &str) -> Option { +pub(crate) fn safe_relative(path: &str) -> Option { if path.contains('\\') || path.starts_with('/') { return None; } diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index e09b529eb..246cb4d51 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -14,8 +14,11 @@ pub mod artifacts; mod inventory; pub mod java; pub mod pyjson; +mod sounds; mod survival; +pub use sounds::sounds; + use pyjson::Value; use sha2::Digest; use std::fs; diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index d56ee8175..1ef1387ad 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -9,6 +9,7 @@ const HELP: &str = "\ horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH] + horizon-prepare sounds [--minecraft-dir PATH] [--root PATH] --prepare Import the pinned game files from your own copy first --server-jar PATH The pinned server jar you downloaded yourself @@ -21,6 +22,10 @@ Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [- Needs Minecraft played once from the official launcher, and Java (a JDK) of the version research-lock.json pins: JAVA_HOME, else javac and java on the PATH. The resources go to /.local/horizon-client/; pass that to horizon-client --resources. + +horizon-prepare sounds copies the pinned version's sounds (about 380 MB) from the official +launcher's asset store into the same folder, checking every file. It is optional: without it the +game is silent. Nothing is downloaded; it needs the version played once from the official launcher. "; /// The folder with research-lock.json: beside the executable in a release folder, else the @@ -46,7 +51,8 @@ fn main() -> ExitCode { server_jar: None, }; let mut root = None; - let mut args = std::env::args_os().skip(1); + let mut args = std::env::args_os().skip(1).peekable(); + let sounds = args.next_if(|a| a == "sounds").is_some(); while let Some(arg) = args.next() { let text = arg.to_string_lossy().into_owned(); let (flag, inline) = match text.split_once('=') { @@ -65,6 +71,9 @@ fn main() -> ExitCode { } }; let parsed = match flag.as_str() { + "--prepare" | "--server-jar" if sounds => { + Err(format!("{flag} is for preparing, not for sounds")) + } "--prepare" if inline.is_none() => { options.import = true; Ok(()) @@ -99,7 +108,12 @@ fn main() -> ExitCode { let _ = writeln!(out, "{line}"); let _ = out.flush(); }; - match horizon_prepare::prepare(&options, &log) { + let result = if sounds { + horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log) + } else { + horizon_prepare::prepare(&options, &log) + }; + match result { Ok(_) => ExitCode::SUCCESS, Err(e) => { eprintln!("error: {e}"); diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs new file mode 100644 index 000000000..75ed221a4 --- /dev/null +++ b/crates/horizon-prepare/src/sounds.rs @@ -0,0 +1,299 @@ +//! The pinned version's sounds (sounds.json and the .ogg files) from the player's own official +//! launcher install, each object checked against the asset index's SHA-1, copied into +//! `.local/horizon-client//assets` where the game reads them (tools/fetch_sounds.py and +//! the tools/lab.py functions it called). Nothing is downloaded. + +use crate::artifacts::{self, Lock}; +use crate::pyjson::Value; +use crate::{digest, read_json, Log}; +use std::fs; +use std::path::{Path, PathBuf}; + +/// The launcher's asset directory and the pinned version's verified asset index +/// (tools/lab.py `launcher_assets`). +fn launcher_assets(manifest: &Value, minecraft: &Path) -> Result<(PathBuf, PathBuf), String> { + let assets = minecraft.join("assets"); + let info = manifest + .get("assetIndex") + .ok_or("The version JSON has no assetIndex")?; + let field = |key: &str| { + info.get(key) + .and_then(Value::as_str) + .ok_or_else(|| format!("The version JSON's assetIndex has no {key}")) + }; + let (id, sha1) = (field("id")?, field("sha1")?); + if artifacts::safe_relative(id).is_none_or(|p| p.components().count() != 1) { + return Err(format!("Unsafe asset index id {id:?}")); + } + let index = assets.join("indexes").join(format!("{id}.json")); + if !index.is_file() { + let version = manifest.get("id").and_then(Value::as_str).unwrap_or(""); + return Err(format!( + "Missing {}. {}", + index.display(), + artifacts::launcher_hint(version) + )); + } + if digest(&index, "sha1")? != sha1 { + return Err(format!("{} is not the pinned asset index", index.display())); + } + Ok((assets, index)) +} + +/// Where the launcher's asset store keeps the object with this SHA-1. +fn object_path(assets: &Path, checksum: &str) -> Result { + if checksum.len() != 40 || !checksum.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(format!("Bad asset hash {checksum:?} in the asset index")); + } + Ok(assets.join("objects").join(&checksum[..2]).join(checksum)) +} + +/// One verified object from the launcher's asset store (tools/lab.py `launcher_object`). +fn launcher_object(assets: &Path, checksum: &str) -> Result { + let path = object_path(assets, checksum)?; + if !path.is_file() { + return Err(format!( + "Missing asset object {}. Play the pinned version once in the official launcher.", + path.display() + )); + } + if digest(&path, "sha1")? != checksum { + return Err(format!( + "Corrupt asset object {}; let the launcher repair it", + path.display() + )); + } + Ok(path) +} + +/// Whether the game plays this asset: sounds.json and everything under sounds/. +fn is_sound(name: &str) -> bool { + name == "minecraft/sounds.json" || name.starts_with("minecraft/sounds/") +} + +/// Copies the pinned version's asset index and sounds from the official launcher's game +/// directory (`minecraft`, else HORIZON_MINECRAFT_DIR, else the launcher's own) into `root`'s +/// `.local/horizon-client/`; returns that folder. Files already there with the right +/// SHA-1 are kept. +pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + let lock = Lock::read(root)?; + let minecraft = artifacts::minecraft_dir(minecraft); + let manifest = artifacts::import_manifest(&lock, &minecraft)?; + let (store, index) = launcher_assets(&manifest, &minecraft)?; + let id = manifest + .get("id") + .and_then(Value::as_str) + .ok_or("The version JSON has no id")?; + let target = root.join(".local/horizon-client").join(id); + fs::create_dir_all(&target).map_err(|e| format!("{}: {e}", target.display()))?; + fs::copy(&index, target.join("asset-index.json")) + .map_err(|e| format!("{}: {e}", target.join("asset-index.json").display()))?; + let objects = read_json(&index)?; + let objects = objects + .get("objects") + .and_then(Value::as_object) + .ok_or_else(|| format!("{} has no objects", index.display()))?; + // A repeated name keeps its first place and its last value, as a Python dict does. + let mut wanted: Vec<(&str, &Value)> = Vec::new(); + for (name, info) in objects.iter().filter(|(name, _)| is_sound(name)) { + match wanted.iter_mut().find(|(n, _)| n == name) { + Some(entry) => entry.1 = info, + None => wanted.push((name, info)), + } + } + let mut total: u64 = 0; + for (name, info) in &wanted { + let hash = info + .get("hash") + .and_then(Value::as_str) + .ok_or_else(|| format!("{name} has no hash in the asset index"))?; + let size = info + .get("size") + .and_then(Value::as_i64) + .and_then(|s| u64::try_from(s).ok()) + .ok_or_else(|| format!("{name} has no size in the asset index"))?; + let relative = artifacts::safe_relative(name) + .ok_or_else(|| format!("Unsafe asset name {name:?} in the asset index"))?; + let source = launcher_object(&store, hash)?; + artifacts::import_copy( + &source, + &target.join("assets").join(relative), + hash, + "sha1", + "", + )?; + total += size; + } + log(&format!( + "Sound assets ready: {} files, {:.1} MB", + wanted.len(), + total as f64 / 1e6 + )); + Ok(target) +} + +#[cfg(test)] +mod tests { + use super::*; + use sha1::Digest; + + fn sha1_hex(data: &[u8]) -> String { + crate::hex(&sha1::Sha1::digest(data)) + } + + /// A Horizon folder and an official launcher directory holding version `9.9` with + /// sounds.json, two sounds and a language file in its asset store. + struct Fixture { + dir: PathBuf, + root: PathBuf, + minecraft: PathBuf, + objects: Vec<(&'static str, Vec)>, + } + + impl Fixture { + fn new(name: &str) -> Fixture { + let dir = std::env::temp_dir().join(format!( + "horizon-prepare-sounds-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&dir); + let root = dir.join("horizon"); + let minecraft = dir.join("minecraft"); + let objects: Vec<(&'static str, Vec)> = vec![ + ("minecraft/sounds.json", b"{\"a\": {}}".to_vec()), + ("minecraft/sounds/ambient/cave1.ogg", b"OggS cave".to_vec()), + ("minecraft/sounds/dig/stone1.ogg", b"OggS stone".to_vec()), + ("minecraft/lang/fr_fr.json", b"{}".to_vec()), + ]; + let mut index = String::from("{\"objects\": {"); + for (i, (name, data)) in objects.iter().enumerate() { + let hash = sha1_hex(data); + let path = minecraft + .join("assets/objects") + .join(&hash[..2]) + .join(&hash); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, data).unwrap(); + let comma = if i > 0 { ", " } else { "" }; + index += &format!( + "{comma}\"{name}\": {{\"hash\": \"{hash}\", \"size\": {}}}", + data.len() + ); + } + index += "}}"; + let indexes = minecraft.join("assets/indexes"); + fs::create_dir_all(&indexes).unwrap(); + fs::write(indexes.join("7.json"), &index).unwrap(); + let manifest = format!( + "{{\"id\": \"9.9\", \"assetIndex\": {{\"id\": \"7\", \"sha1\": \"{}\"}}, \ + \"downloads\": {{\"client\": {{\"sha1\": \"c\"}}, \"server\": {{\"sha1\": \"s\"}}}}, \ + \"javaVersion\": {{\"majorVersion\": 25}}}}", + sha1_hex(index.as_bytes()) + ); + let versions = minecraft.join("versions/9.9"); + fs::create_dir_all(&versions).unwrap(); + fs::write(versions.join("9.9.json"), &manifest).unwrap(); + fs::create_dir_all(&root).unwrap(); + fs::write( + root.join("research-lock.json"), + format!( + "{{\"minecraft\": {{\"version\": \"9.9\", \"java_major\": 25, \ + \"client_sha1\": \"c\", \"server_sha1\": \"s\", \"manifest_sha1\": \"{}\"}}}}", + sha1_hex(manifest.as_bytes()) + ), + ) + .unwrap(); + Fixture { + dir, + root, + minecraft, + objects, + } + } + + fn run(&self) -> Result { + sounds(&self.root, Some(&self.minecraft), &|_| {}) + } + + fn object(&self, i: usize) -> PathBuf { + let hash = sha1_hex(&self.objects[i].1); + self.minecraft + .join("assets/objects") + .join(&hash[..2]) + .join(hash) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.dir); + } + } + + #[test] + fn sounds_land_where_the_game_reads_them() { + let f = Fixture::new("layout"); + let lines = std::cell::RefCell::new(Vec::new()); + let target = sounds(&f.root, Some(&f.minecraft), &|l| { + lines.borrow_mut().push(l.to_string()) + }) + .unwrap(); + assert_eq!(target, f.root.join(".local/horizon-client/9.9")); + for (name, data) in &f.objects[..3] { + assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); + } + assert!(!target.join("assets/minecraft/lang").exists()); + assert_eq!( + fs::read(target.join("asset-index.json")).unwrap(), + fs::read(f.minecraft.join("assets/indexes/7.json")).unwrap() + ); + assert!(f.root.join(".local/minecraft/9.9/manifest.json").is_file()); + assert_eq!(*lines.borrow(), ["Sound assets ready: 3 files, 0.0 MB"]); + // Again: the verified copies are kept. + f.run().unwrap(); + } + + #[test] + fn every_object_is_checked() { + let f = Fixture::new("corrupt"); + fs::write(f.object(1), b"not the sound").unwrap(); + let error = f.run().unwrap_err(); + assert!(error.starts_with("Corrupt asset object"), "{error}"); + assert!(!f + .root + .join(".local/horizon-client/9.9/assets/minecraft/sounds/ambient/cave1.ogg") + .exists()); + fs::remove_file(f.object(1)).unwrap(); + assert!(f.run().unwrap_err().starts_with("Missing asset object")); + } + + #[test] + fn the_index_must_be_the_pinned_one() { + let f = Fixture::new("index"); + let index = f.minecraft.join("assets/indexes/7.json"); + fs::write(&index, "{\"objects\": {}}").unwrap(); + assert!(f + .run() + .unwrap_err() + .ends_with("is not the pinned asset index")); + fs::remove_file(&index).unwrap(); + let error = f.run().unwrap_err(); + assert!( + error.starts_with("Missing ") && error.contains("play 9.9 once"), + "{error}" + ); + } + + #[test] + fn object_paths_come_from_real_hashes() { + let store = Path::new("assets"); + let hash = "abfaa525f923f807df8b4e4d29c1b5e3a104adbe"; + assert_eq!( + object_path(store, hash).unwrap(), + store.join("objects/ab").join(hash) + ); + assert!(object_path(store, "../../etc/passwd").is_err()); + assert!(is_sound("minecraft/sounds/x.ogg") && is_sound("minecraft/sounds.json")); + assert!(!is_sound("minecraft/soundsx.json") && !is_sound("realms/sounds/x.ogg")); + } +} diff --git a/docs/native-client.md b/docs/native-client.md index 4522966ec..3081bac7c 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -14,23 +14,24 @@ missing; [Rust rewrite status](rust-parity.md) has the details. ## Run from a checkout -Use current stable Rust (1.90+) and JDK 25 (Python 3.10+ for the sounds and the -development harnesses). Horizon never +Use current stable Rust (1.90+) and JDK 25 (Python 3.10+ only for the development +harnesses). Horizon never downloads the game: resource preparation imports **your own copy** (the 26.3 client from your official launcher install, and the 26.3 server jar you downloaded yourself; see [Build from source](../README.md#build-from-source)), verifies it against the pinned checksums, runs vanilla's data generator and small exporters against those jars, and extracts the jar's assets and data into ignored `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your -launcher's asset store. Prepared resources are private; never commit them. +launcher's asset store by `horizon-prepare sounds`, each file checked against the asset +index's SHA-1. Prepared resources are private; never commit them. Preparation is `horizon-prepare` (`crates/horizon-prepare`, Rust): it needs no Python, only the JDK, for the small exporters that call Mojang's own code. Release folders ship it beside -`horizon-client`, and the launcher prepares with it. +`horizon-client`, and the launcher prepares with it and copies the sounds as part of preparing. ```sh cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar -python3 tools/fetch_sounds.py +cargo run --release -p horizon-prepare -- sounds cargo run --release -p horizon-client -- --render-distance 12 ``` diff --git a/launcher/README.md b/launcher/README.md index 11c25d056..f77d345d2 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -15,7 +15,9 @@ The opening, then Play ([clip](docs/opening.webm)): - **Versions**: lists the published releases of ludovic111/horizon, installs the build for this platform into its own folder, and removes it again. - **Play**: prepares resources as `PLAY.txt` describes (your launcher's 26.3 install, the - 26.3 server jar from that version's own json, and Java 25), then starts the client, or a + 26.3 server jar from that version's own json, and Java 25) and copies its sounds from your + launcher's asset store (`horizon-prepare sounds`; a launcher install without them only + leaves the game silent), then starts the client, or a server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is horizon-prepare: linked into the launcher, used in-process when a version ships the same preparer sources, else that version's own `horizon-prepare`; versions released before it diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index bd12dbf94..354837d2c 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -441,7 +441,7 @@ fn resources_compatible(from: &Path, to: &Path, manifest: &serde_json::Value) -> sources.iter().all(|s| same(s)) } -/// Where a version folder keeps the preparer's sources (packaging/package.sh copies them). +/// Where a version folder keeps the preparer's sources (the release package copies them). const PREPARER_CRATE: &str = "crates/horizon-prepare"; /// The files under `dir/relative`, as paths relative to `dir`. @@ -679,6 +679,53 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result
 Command::new(binary)
+            .current_dir(&dir)
+            .arg("sounds")
+            .arg("--root")
+            .arg(&dir)
+            .arg("--minecraft-dir")
+            .arg(minecraft)
+            .output()
+            .map_err(|e| e.to_string())
+            .and_then(|o| {
+                let text = |b: &[u8]| String::from_utf8_lossy(b).trim().to_string();
+                for line in text(&o.stdout).lines() {
+                    log(line.to_string());
+                }
+                match o.status.success() {
+                    true => Ok(()),
+                    false => Err(text(&o.stderr).trim_start_matches("error: ").to_string()),
+                }
+            }),
+        None => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+            horizon_prepare::sounds(&dir, Some(minecraft), &|line| log(line.to_string()))
+        }))
+        .unwrap_or_else(|_| Err("The sound copy stopped unexpectedly".into()))
+        .map(|_| ()),
+    };
+    if let Err(e) = result {
+        log(format!("No sound (the game will be silent): {e}"));
+    }
+}
+
 /// Runs `Preparer::InProcess` on this thread, each progress line to `log`. A panic is an
 /// error like any other, so the window never waits on a preparation that died.
 pub fn prepare_in_process(
diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs
index 7aad2bc31..b624b2259 100644
--- a/launcher/src/cli.rs
+++ b/launcher/src/cli.rs
@@ -215,7 +215,9 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
         Cmd::Prepare { minecraft, version } => {
             let tag = backend::resolve_version(version.as_deref())?;
             let minecraft = backend::minecraft_dir(minecraft)?;
-            match backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))? {
+            let preparer = backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?;
+            backend::sounds(&tag, &minecraft, &|line| println!("{line}"));
+            match preparer {
                 backend::Preparer::Process(cmd) => attached(cmd)?,
                 backend::Preparer::InProcess(options) => {
                     backend::prepare_in_process(&options, &|line| println!("{line}"))?
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index 5716719d7..be556226f 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -515,14 +515,16 @@ impl Launcher {
             let log = |line| {
                 let _ = tx.send(Msg::Line(Job::Prepare, line));
             };
-            let result = backend::preparer(&tag, &minecraft, &log).and_then(|p| match p {
-                backend::Preparer::Process(cmd) => {
-                    backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
-                }
-                backend::Preparer::InProcess(options) => {
-                    backend::prepare_in_process(&options, &log).map(|_| true)
-                }
-            });
+            let result = backend::preparer(&tag, &minecraft, &log)
+                .inspect(|_| backend::sounds(&tag, &minecraft, &log))
+                .and_then(|p| match p {
+                    backend::Preparer::Process(cmd) => {
+                        backend::spawn(Job::Prepare, cmd, tx.clone()).map(|_running| false)
+                    }
+                    backend::Preparer::InProcess(options) => {
+                        backend::prepare_in_process(&options, &log).map(|_| true)
+                    }
+                });
             match result {
                 // A process sends its own Exit when it ends.
                 Ok(false) => {}
diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs
index 03c78ef2f..a8fd6de9a 100644
--- a/launcher/src/mcp.rs
+++ b/launcher/src/mcp.rs
@@ -97,7 +97,10 @@ impl Session {
                 let tag = backend::resolve_version(arg_str(args, "version"))?;
                 let minecraft =
                     backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
-                let (result, tail) = match backend::preparer(&tag, &minecraft, &|_| {})? {
+                let preparer = backend::preparer(&tag, &minecraft, &|_| {})?;
+                let sound = std::cell::RefCell::new(Vec::new());
+                backend::sounds(&tag, &minecraft, &|line| sound.borrow_mut().push(line));
+                let (result, tail) = match preparer {
                     backend::Preparer::Process(cmd) => {
                         let run = Logged::start(Job::Prepare, cmd)?;
                         let result = run.wait();
@@ -120,6 +123,7 @@ impl Session {
                         (result, tail)
                     }
                 };
+                let tail = format!("{}\n{tail}", sound.into_inner().join("\n"));
                 result
                     .map(|_| format!("{tag} is prepared.\n{tail}"))
                     .map_err(|e| format!("{e}\n{tail}"))
diff --git a/packaging/PLAY.txt b/packaging/PLAY.txt
index ea579d8af..5ad53d062 100644
--- a/packaging/PLAY.txt
+++ b/packaging/PLAY.txt
@@ -19,10 +19,10 @@ Downloaded this archive directly?
   To prepare this folder by hand you need Minecraft Java Edition 26.3, played
   once from the official launcher, and Java 25 (a JDK). Then, in this folder:
     ./horizon-prepare --prepare --server-jar PATH/TO/server.jar
-    python3 tools/fetch_sounds.py          (optional, for sound; needs Python 3.10+)
-  (Windows: horizon-prepare.exe, and py instead of python3.) The 26.3 server jar is the
-  downloads.server.url in your launcher's versions/26.3/26.3.json. Add
-  --minecraft-dir PATH if your launcher keeps the game elsewhere. Then run
+    ./horizon-prepare sounds               (optional, for sound)
+  (Windows: horizon-prepare.exe.) The 26.3 server jar is the downloads.server.url
+  in your launcher's versions/26.3/26.3.json. Add --minecraft-dir PATH to both if
+  your launcher keeps the game elsewhere. Then run
   ./horizon-client (horizon-client.exe on Windows; on macOS the first time:
   right-click > Open). horizon-client --help lists the options.
 
diff --git a/tools/audio_harness.py b/tools/audio_harness.py
index 41e0fa9dd..52054c2f2 100644
--- a/tools/audio_harness.py
+++ b/tools/audio_harness.py
@@ -33,7 +33,7 @@ COMMON_SOURCES = [
 
 def require_sounds():
     if not (RESOURCES / 'assets/minecraft/sounds.json').is_file():
-        raise SystemExit('Sound assets missing: run tools/fetch_sounds.py first')
+        raise SystemExit('Sound assets missing: run cargo run -p horizon-prepare -- sounds first')
 
 
 def run_harness(name, oracle, example, inputs_text, extra_sources=(), java_args=(), rust_args=(), scope='', timeout=1800):
diff --git a/tools/fetch_sounds.py b/tools/fetch_sounds.py
deleted file mode 100644
index 7349b3eb9..000000000
--- a/tools/fetch_sounds.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/env python3
-"""Copy the pinned version's sound assets (sounds.json and .ogg files) from your
-own official launcher install into the private client resource directory,
-verifying every object's SHA-1. Nothing is downloaded; the files stay in
-ignored .local/ and are never committed."""
-import argparse
-from pathlib import Path
-import shutil
-
-import lab
-
-
-def main():
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument('--minecraft-dir', type=Path,
-                        help="official launcher game directory (default: the launcher's own)")
-    args = parser.parse_args()
-    lock, directory = lab.config()
-    manifest = lab.import_manifest(lock, directory, args.minecraft_dir)
-    store, index = lab.launcher_assets(manifest, args.minecraft_dir)
-    target = lab.LOCAL / 'horizon-client' / manifest['id']
-    target.mkdir(parents=True, exist_ok=True)
-    shutil.copyfile(index, target / 'asset-index.json')
-    objects = lab.json.loads(index.read_text())['objects']
-    wanted = {name: info for name, info in objects.items()
-              if name == 'minecraft/sounds.json' or name.startswith('minecraft/sounds/')}
-    total = 0
-    for name, info in wanted.items():
-        source = lab.launcher_object(store, info['hash'])
-        lab.import_copy(source, target / 'assets' / name, info['hash'])
-        total += info['size']
-    print(f'Sound assets ready: {len(wanted)} files, {total / 1e6:.1f} MB')
-
-
-if __name__ == '__main__':
-    main()
diff --git a/tools/package_native_client.py b/tools/package_native_client.py
index 9b477c8f7..92498436a 100644
--- a/tools/package_native_client.py
+++ b/tools/package_native_client.py
@@ -87,7 +87,7 @@ def main():
     if not (args.resources / 'horizon-resources.json').is_file():
         raise SystemExit(f'missing prepared resources in {args.resources}: run horizon-prepare --prepare (cargo run --release -p horizon-prepare -- --prepare)')
     if not (args.resources / 'assets/minecraft/sounds.json').is_file():
-        print('warning: no sound assets; run tools/fetch_sounds.py for audio')
+        print('warning: no sound assets; run cargo run -p horizon-prepare -- sounds for audio')
 
     system = {'Linux': 'linux', 'Darwin': 'macos'}.get(platform.system())
     if system is None:

From e905c104004db1f5cefb0a31eeb397879c12d109 Mon Sep 17 00:00:00 2001
From: Cosmic <84875247+Online5277@users.noreply.github.com>
Date: Wed, 14 Oct 2026 12:11:53 -0400
Subject: [PATCH 06/30] Address creative inventory review on current main

---
 crates/horizon-client/src/creative.rs       |  20 ++++
 crates/horizon-client/src/game.rs           | 115 ++++++++++++++++----
 tests/test_creative_inventory_transition.py |  58 ----------
 tests/test_drop_modifier_policy.py          |  55 ----------
 tests/test_hand_frame_policy.py             |  62 -----------
 5 files changed, 115 insertions(+), 195 deletions(-)
 delete mode 100644 tests/test_creative_inventory_transition.py
 delete mode 100644 tests/test_drop_modifier_policy.py
 delete mode 100644 tests/test_hand_frame_policy.py

diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs
index 6ea7e6b14..7f67aa7e2 100644
--- a/crates/horizon-client/src/creative.rs
+++ b/crates/horizon-client/src/creative.rs
@@ -443,6 +443,26 @@ mod tests {
         }));
     }
 
+    #[test]
+    fn inventory_tab_can_return_to_category_and_search() {
+        let mut c = creative(90);
+        for (selected, inventory, search) in [
+            (2, true, false),
+            (0, false, false),
+            (1, false, true),
+            (2, true, false),
+        ] {
+            c.search = "anvil".into();
+            c.scroll = 0.5;
+            c.select(selected);
+            assert_eq!(c.selected, selected);
+            assert_eq!(c.tab().inventory, inventory);
+            assert_eq!(c.tab().search, search);
+            assert!(c.search.is_empty());
+            assert_eq!(c.scroll, 0.0);
+        }
+    }
+
     #[test]
     fn hidden_tabs_are_skipped() {
         let c = creative(0);
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 5156e685c..67d4d776b 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -588,6 +588,22 @@ pub struct Resources {
     /// Enchantments, workstation recipes and brewing (game/stations.rs).
     stations: horizon_client::stations::StationData,
 }
+/// Ctrl+Q reads the physical keyboard, independently of sprint key mappings.
+fn drop_whole_stack(physical_keys: &HashSet) -> bool {
+    physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight)
+}
+
+fn select_creative_tab(
+    creative: &mut Creative,
+    clicks: &mut horizon_client::container_screen::Clicks,
+    tab: usize,
+) {
+    creative.select(tab);
+    *clicks = Default::default();
+    // Tabs are outside the panel; their release must not drop a carried stack.
+    clicks.skip_release();
+}
+
 struct Game<'a> {
     res: &'a mut Resources,
     collision: &'a BlockCollisionRegistry<'a>,
@@ -4170,8 +4186,7 @@ impl Game<'_> {
             (Some(n), _) => self.menu_click(Some(slot), n as i32, Input::Swap),
             (None, KeyCode::KeyF) => self.menu_click(Some(slot), 40, Input::Swap),
             (None, KeyCode::KeyQ) => {
-                let all = self.physical_keys.contains(&KeyCode::ControlLeft)
-                    || self.physical_keys.contains(&KeyCode::ControlRight);
+                let all = drop_whole_stack(&self.physical_keys);
                 self.menu_click(Some(slot), i32::from(all), Input::Throw)
             }
             _ => false,
@@ -4274,16 +4289,21 @@ impl Game<'_> {
     fn clicked_outside(&self, batch: &HudBatch) -> bool {
         use horizon_client::container_screen::{Book, Image, clicked_outside};
         let (ox, oy) = self.inventory_origin(batch);
-        let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
-            Some(stations::Kind::Merchant) => (-50.0, 276),
-            Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
-            _ => (0.0, 176),
+        let (shift, width, height) = if self.creative_inventory_open() {
+            (0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
+        } else {
+            let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
+                Some(stations::Kind::Merchant) => (-50.0, 276),
+                Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
+                _ => (0.0, 176),
+            };
+            (shift, width, self.screen_height() as i32)
         };
         let image = Image {
             left: (ox + shift) as i32,
             top: oy as i32,
             width,
-            height: self.screen_height() as i32,
+            height,
         };
         let book = self
             .recipe_book_area(batch)
@@ -7421,7 +7441,7 @@ impl Game<'_> {
         for (i, t) in tabs.iter().enumerate() {
             let (tx, ty) = Creative::tab_position(t);
             if cx >= ox + tx && cx < ox + tx + 26.0 && cy >= oy + ty && cy < oy + ty + 32.0 {
-                self.creative_screen.select(i);
+                select_creative_tab(&mut self.creative_screen, &mut self.inv_clicks, i);
                 self.inv_drag = None;
                 self.last_inv_click = None;
                 return;
@@ -7429,9 +7449,7 @@ impl Game<'_> {
         }
         if self.creative_inventory_open() {
             if Self::creative_trash_hovered(&batch, self.cursor) {
-                if self.keys.contains(&KeyCode::ShiftLeft)
-                    || self.keys.contains(&KeyCode::ShiftRight)
-                {
+                if self.has_shift_down() {
                     self.inventory.fill(None);
                     self.armor.fill(None);
                     self.offhand = None;
@@ -7441,12 +7459,8 @@ impl Game<'_> {
                     self.carried = None;
                 }
                 self.inv_drag = None;
-            } else if self.slot_at(&batch, cx, cy).is_some()
-                || !(cx >= ox
-                    && cx < ox + Creative::WIDTH
-                    && cy >= oy
-                    && cy < oy + Creative::HEIGHT)
-            {
+                self.inv_clicks = Default::default();
+            } else if self.slot_at(&batch, cx, cy).is_some() || self.clicked_outside(&batch) {
                 self.inventory_press(right);
             }
             return;
@@ -8002,8 +8016,7 @@ impl Game<'_> {
                 self.using = None;
             }
             KeyCode::KeyQ if self.screen == Screen::Playing => {
-                let all = self.physical_keys.contains(&KeyCode::ControlLeft)
-                    || self.physical_keys.contains(&KeyCode::ControlRight);
+                let all = drop_whole_stack(&self.physical_keys);
                 self.drop_held(all);
             }
             KeyCode::Digit1
@@ -8453,7 +8466,7 @@ impl ApplicationHandler for Game<'_> {
                             self.click_creative(button == MouseButton::Right);
                         }
                         Screen::Creative if self.creative_screen.tab().inventory => {
-                            self.inventory_release();
+                            self.inventory_mouse_release(button == MouseButton::Right);
                         }
                         Screen::Creative if button == MouseButton::Left => {
                             self.creative_screen.release();
@@ -9280,3 +9293,65 @@ pub fn run() -> Result<()> {
     }
     Ok(())
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use horizon_client::container_screen::{Button, Clicks, Release, Target};
+    use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys};
+
+    #[test]
+    fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() {
+        let mut creative = Creative::from_json(&serde_json::json!({
+            "schema": 2,
+            "tabs": [{"type": "CATEGORY"}, {"type": "INVENTORY"}]
+        }))
+        .unwrap();
+        for button in [Button::Left, Button::Right] {
+            let mut clicks = Clicks::default();
+            for tab in [1, 1, 0, 1] {
+                select_creative_tab(&mut creative, &mut clicks, tab);
+                assert_eq!(creative.selected, tab);
+                assert_eq!(creative.tab().inventory, tab == 1);
+                assert_eq!(
+                    clicks.release(
+                        &Target::::Outside,
+                        button,
+                        false,
+                        false,
+                        false,
+                        false
+                    ),
+                    Release::Nothing
+                );
+            }
+        }
+    }
+
+    #[test]
+    fn stack_drop_requires_physical_ctrl_even_with_sprint_latched() {
+        for sprint in [false, true] {
+            let mut toggles = ToggleKeys::default();
+            if sprint {
+                toggles.key(SPRINT, KeyAction::Press, false, true);
+                toggles.key(SPRINT, KeyAction::Release, false, true);
+            }
+            assert_eq!(toggles.is_down(SPRINT), sprint);
+
+            for held in 0..4 {
+                let mut physical_keys = HashSet::from([KeyCode::ShiftLeft, KeyCode::KeyQ]);
+                if held & 1 != 0 {
+                    physical_keys.insert(KeyCode::ControlLeft);
+                }
+                if held & 2 != 0 {
+                    physical_keys.insert(KeyCode::ControlRight);
+                }
+                assert_eq!(drop_whole_stack(&physical_keys), held != 0);
+                physical_keys.remove(&KeyCode::ControlLeft);
+                physical_keys.remove(&KeyCode::ControlRight);
+                assert!(!drop_whole_stack(&physical_keys));
+                assert_eq!(toggles.is_down(SPRINT), sprint);
+            }
+        }
+    }
+}
diff --git a/tests/test_creative_inventory_transition.py b/tests/test_creative_inventory_transition.py
deleted file mode 100644
index 2c3a5d7b1..000000000
--- a/tests/test_creative_inventory_transition.py
+++ /dev/null
@@ -1,58 +0,0 @@
-"""Exercise the real creative-tab selection branch without a desktop window."""
-from pathlib import Path
-import shutil
-import subprocess
-import tempfile
-import unittest
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class CreativeInventoryTransitionTests(unittest.TestCase):
-    @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the tab-selection probe")
-    def test_inventory_tab_stays_in_the_creative_screen(self):
-        source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
-        click = source.split("fn click_creative(&mut self, right: bool)", 1)[1]
-        branch = click.split("if cx >= ox + tx", 1)[1]
-        branch = branch.split("{", 1)[1].split("\n            }\n", 1)[0]
-        program = """
-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
-enum Screen { Creative, Inventory }
-struct Tab { inventory: bool }
-struct Creative { selected: usize, tabs: [Tab; 2] }
-impl Creative { fn select(&mut self, i: usize) { self.selected = i; } }
-struct Game { screen: Screen, creative_screen: Creative, inv_drag: Option, last_inv_click: Option }
-impl Game {
-    fn click_tab(&mut self, i: usize) {
-        let t = &self.creative_screen.tabs[i];
-        SELECTION
-    }
-}
-#[test]
-fn inventory_and_back_preserve_the_creative_screen() {
-    let mut game = Game { screen: Screen::Creative,
-        creative_screen: Creative { selected: 0, tabs: [Tab { inventory: false }, Tab { inventory: true }] },
-        inv_drag: Some(1), last_inv_click: Some(2) };
-    game.click_tab(1);
-    assert_eq!(game.screen, Screen::Creative);
-    assert_eq!(game.creative_screen.selected, 1);
-    assert!(game.inv_drag.is_none() && game.last_inv_click.is_none());
-    game.click_tab(0);
-    assert_eq!(game.screen, Screen::Creative);
-    assert_eq!(game.creative_screen.selected, 0);
-}
-""".replace("SELECTION", branch)
-        with tempfile.TemporaryDirectory(prefix="horizon-creative-tab-") as directory:
-            path = Path(directory)
-            (path / "probe.rs").write_text(program)
-            compiled = subprocess.run(
-                ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
-                capture_output=True, text=True, check=False,
-            )
-            self.assertEqual(compiled.returncode, 0, compiled.stderr)
-            result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
-            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
-
-
-if __name__ == "__main__":
-    unittest.main()
diff --git a/tests/test_drop_modifier_policy.py b/tests/test_drop_modifier_policy.py
deleted file mode 100644
index 76415f876..000000000
--- a/tests/test_drop_modifier_policy.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""Drop modifiers must come from physical Ctrl, not the sprint key mapping."""
-from pathlib import Path
-import shutil
-import subprocess
-import tempfile
-import unittest
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class DropModifierPolicyTests(unittest.TestCase):
-    @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the drop-policy probe")
-    def test_playing_and_inventory_drop_ignore_latched_sprint(self):
-        source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
-        inventory = source.split("fn inventory_hotkey(", 1)[1]
-        playing = source.split("KeyCode::KeyQ if self.screen == Screen::Playing =>", 1)[1]
-        expressions = [section.split("let all = ", 1)[1].split(";", 1)[0]
-                       for section in (inventory, playing)]
-        program = """
-use std::collections::HashSet;
-#[derive(PartialEq, Eq, Hash)] enum KeyCode { ControlLeft, ControlRight }
-struct Game { keys: HashSet, physical_keys: HashSet }
-impl Game {
-    fn inventory_drop_all(&self) -> bool { INVENTORY }
-    fn playing_drop_all(&self) -> bool { PLAYING }
-}
-#[test]
-fn sprint_and_control_are_independent() {
-    for sprint in [false, true] {
-        for held in 0..4 {
-            let ctrl = held != 0;
-            let mut game = Game { keys: HashSet::new(), physical_keys: HashSet::new() };
-            if held & 1 != 0 { game.physical_keys.insert(KeyCode::ControlLeft); }
-            if held & 2 != 0 { game.physical_keys.insert(KeyCode::ControlRight); }
-            if sprint { game.keys.insert(KeyCode::ControlLeft); }
-            assert_eq!(game.inventory_drop_all(), ctrl, "inventory: sprint={sprint}, ctrl={ctrl}");
-            assert_eq!(game.playing_drop_all(), ctrl, "playing: sprint={sprint}, ctrl={ctrl}");
-        }
-    }
-}
-""".replace("INVENTORY", expressions[0]).replace("PLAYING", expressions[1])
-        with tempfile.TemporaryDirectory(prefix="horizon-drop-policy-") as directory:
-            path = Path(directory)
-            (path / "probe.rs").write_text(program)
-            compiled = subprocess.run(
-                ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
-                capture_output=True, text=True, check=False,
-            )
-            self.assertEqual(compiled.returncode, 0, compiled.stderr)
-            result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
-            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
-
-
-if __name__ == "__main__":
-    unittest.main()
diff --git a/tests/test_hand_frame_policy.py b/tests/test_hand_frame_policy.py
deleted file mode 100644
index e9a83245a..000000000
--- a/tests/test_hand_frame_policy.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""Compile the real frame hand-selection expression without opening a window."""
-from pathlib import Path
-import re
-import shutil
-import subprocess
-import tempfile
-import unittest
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-class HandFramePolicyTests(unittest.TestCase):
-    @unittest.skipUnless(shutil.which("rustc"), "rustc is needed for the frame-policy probe")
-    def test_inventory_screen_does_not_suppress_first_person_geometry(self):
-        source = (ROOT / "crates/horizon-client/src/game.rs").read_text()
-        match = re.search(r"let hand = (if .*?);\s*let screen =", source, re.S)
-        self.assertIsNotNone(match, "frame hand-selection seam changed")
-        selection = match.group(1)
-        # Only geometry generation is stubbed; execute the actual frame guard.
-        program = """
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum Screen { Playing, Creative, Inventory }
-struct Game { screen: Screen, scoping: bool }
-impl Game {
-    fn scoping(&self) -> bool { self.scoping }
-    fn hand_geometry(&mut self, _: f64) -> Vec { vec![1] }
-    fn hand_len(&mut self, title: bool) -> usize {
-        let alpha = 0.0;
-        let hand = SELECTION;
-        hand.len()
-    }
-}
-#[test]
-fn creative_inventory_and_return_keep_the_hand() {
-    let mut game = Game { screen: Screen::Playing, scoping: false };
-    for screen in [Screen::Playing, Screen::Creative, Screen::Inventory, Screen::Playing] {
-        game.screen = screen;
-        assert_eq!(game.hand_len(false), 1);
-    }
-}
-#[test]
-fn title_and_spyglass_still_hide_the_hand() {
-    let mut game = Game { screen: Screen::Inventory, scoping: false };
-    assert_eq!(game.hand_len(true), 0);
-    game.scoping = true;
-    assert_eq!(game.hand_len(false), 0);
-}
-""".replace("SELECTION", selection)
-        with tempfile.TemporaryDirectory(prefix="horizon-hand-policy-") as directory:
-            path = Path(directory)
-            (path / "probe.rs").write_text(program)
-            compiled = subprocess.run(
-                ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")],
-                capture_output=True, text=True, check=False,
-            )
-            self.assertEqual(compiled.returncode, 0, compiled.stderr)
-            result = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False)
-            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
-
-
-if __name__ == "__main__":
-    unittest.main()

From b7330ac0cc7f627bf32b8e058a6164946d8c23e0 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 18:15:40 +0200
Subject: [PATCH 07/30] Controllers: gilrs input layer, in-game movement,
 camera, actions and hotbar

Vanilla 26.3 has no gamepad input, so this is Horizon's own, on Bedrock's
default layout (docs/controllers.md). gilrs reads the pads; the pure part
(bindings, radial deadzones, the look curve, button edges, the
horizon-controller.txt settings file) is in gamepad.rs with unit tests.

Buttons act as the vanilla key mapping they're bound to, through the same
path a rebound keyboard key takes (the keyboard's post-rebinding handling
moves into Game::mapped_key). The left stick is an analog move vector,
the right stick turns the view per frame, LB/RB step the hotbar, B and
Start leave screens and A respawns. horizon-ctl pad injects a virtual pad.

Co-Authored-By: Claude Opus 5.5 
---
 .github/workflows/ci.yml                      |   4 +-
 .github/workflows/release.yml                 |   4 +-
 Cargo.lock                                    | 110 ++++
 README.md                                     |   2 +-
 crates/horizon-client/Cargo.toml              |   2 +
 .../examples/scene_motion_probe.rs            |   1 +
 .../horizon-client/examples/sprint_probe.rs   |   1 +
 .../src/bin/horizon-ctl/commands.rs           |   4 +
 crates/horizon-client/src/game.rs             |  80 ++-
 crates/horizon-client/src/game/books.rs       |   2 +-
 crates/horizon-client/src/game/control.rs     |   2 +
 crates/horizon-client/src/game/pad.rs         | 435 +++++++++++++
 crates/horizon-client/src/game/remote.rs      |   5 +-
 crates/horizon-client/src/game/screens.rs     |   2 +-
 crates/horizon-client/src/game/sign_edit.rs   |   2 +-
 crates/horizon-client/src/gamepad.rs          | 596 ++++++++++++++++++
 crates/horizon-client/src/lib.rs              |   1 +
 crates/horizon-client/src/settings.rs         |  11 +
 crates/horizon-client/src/sprint.rs           |  21 +-
 tools/check_imports.py                        |   2 +-
 20 files changed, 1244 insertions(+), 43 deletions(-)
 create mode 100644 crates/horizon-client/src/game/pad.rs
 create mode 100644 crates/horizon-client/src/gamepad.rs

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0048a14e0..7b1a63710 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -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: |
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3ea634cb6..3476c4fc2 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -41,8 +41,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
diff --git a/Cargo.lock b/Cargo.lock
index 2a9d0cd47..393e942cc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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"
diff --git a/README.md b/README.md
index cf56bd042..db9482a25 100644
--- a/README.md
+++ b/README.md
@@ -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`:
 
diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml
index f602eac7b..984768c9d 100644
--- a/crates/horizon-client/Cargo.toml
+++ b/crates/horizon-client/Cargo.toml
@@ -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).
diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs
index a5c61c065..b2f16a277 100644
--- a/crates/horizon-client/examples/scene_motion_probe.rs
+++ b/crates/horizon-client/examples/scene_motion_probe.rs
@@ -274,6 +274,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"]))?,
diff --git a/crates/horizon-client/examples/sprint_probe.rs b/crates/horizon-client/examples/sprint_probe.rs
index 18d4b8fce..ab538ffe1 100644
--- a/crates/horizon-client/examples/sprint_probe.rs
+++ b/crates/horizon-client/examples/sprint_probe.rs
@@ -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<()> {
diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs
index 8683402a2..655609d5c 100644
--- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs
+++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs
@@ -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
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index a0d350a6b..e9a12e282 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -72,6 +72,7 @@ mod nautili;
 mod net_harness;
 mod options;
 mod packs;
+mod pad;
 mod paintings;
 mod passengers;
 mod persist;
@@ -660,6 +661,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,
@@ -2666,6 +2669,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);
@@ -2677,7 +2681,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();
@@ -2706,7 +2712,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;
         }
@@ -2971,6 +2979,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) {
@@ -8497,36 +8539,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();
@@ -8571,6 +8584,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()?;
@@ -8675,6 +8689,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();
@@ -8933,6 +8948,7 @@ pub fn run() -> Result<()> {
         started: now,
         previous: now,
         last_input: now,
+        pad: Default::default(),
         frames: 0,
         fps: 0.0,
         fps_frames: 0,
diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs
index b276b9a88..bebbbfc88 100644
--- a/crates/horizon-client/src/game/books.rs
+++ b/crates/horizon-client/src/game/books.rs
@@ -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);
     }
diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs
index 38a93c56b..2ab1245cf 100644
--- a/crates/horizon-client/src/game/control.rs
+++ b/crates/horizon-client/src/game/control.rs
@@ -134,10 +134,12 @@ impl Game<'_> {
                 .chain(super::render_control::HELP)
                 .chain(super::sculk::HELP)
                 .chain(super::agent::HELP)
+                .chain(super::pad::HELP)
                 .collect::>() }))),
             "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()?;
diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs
new file mode 100644
index 000000000..d59e60e01
--- /dev/null
+++ b/crates/horizon-client/src/game/pad.rs
@@ -0,0 +1,435 @@
+//! 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,
+    started: bool,
+    /// The pad last touched; only its input counts.
+    active: Option,
+    /// 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