From 48db367d4a32e7ad5ee6bfa51765052c375d25d9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 03:09:29 +0100 Subject: [PATCH 1/6] Mod API: zoom the camera, take the mouse wheel (render, input) render.set-zoom divides the field of view by up to 10, eased through the game's FOV easing or at once, with a turning scale (at least 0.05); only while playing, and the spyglass's own view wins. The strongest of several mods' zooms counts, and the built-in zoom keeps working beside it. input.claim-wheel takes the wheel from the hotbar while playing: its steps are the mod's wheel events. That is the one input a mod consumes; its keys never do (docs/api/stability.md). A screen opening now lets the mod's held keys up, and mod keys bound to mouse buttons (key.mouse.4) are heard. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/extras.rs | 27 +++++--- crates/horizon-client/src/game/mod_input.rs | 62 ++++++++++++++++- crates/horizon-client/src/game/mods.rs | 4 ++ crates/horizon-mod-sdk/wit/horizon.wit | 25 ++++++- crates/horizon-mods/src/manifest.rs | 4 +- crates/horizon-mods/src/runtime.rs | 68 ++++++++++++++++++- crates/horizon-mods/tests/sandbox.rs | 50 ++++++++++++++ crates/horizon-mods/tests/ui_guest/src/lib.rs | 21 +++++- docs/api/mods-reference.md | 17 ++++- docs/api/stability.md | 13 +++- docs/mods.md | 4 +- 12 files changed, 273 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5b04d8716..508122bca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10995,6 +10995,7 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Playing && self.sleeping.is_none() && self.player.is_some() + && !self.mod_wheel(d) && !self.extras_scroll(d) && let Some((wheel, (_, vertical_steps))) = self.mouse @@ -11165,6 +11166,7 @@ impl ApplicationHandler for Game<'_> { return Ok(()); } self.extras_mouse(button, pressed); + self.mod_mouse_key(button, pressed); match self.settings.keys.translate_mouse(button) { Some(Err(b)) => self.play_mouse(b, pressed)?, Some(Ok(k)) if pressed => { diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 4664f0c6f..1978d003f 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -229,25 +229,34 @@ impl Game<'_> { fn zoom_factor(&self) -> f32 { self.extras.zoom.factor(self.scoping()) } + /// The zoom in effect, the extra's or a mod's (`render.set-zoom`), + /// whichever is stronger: (factor, smooth, turning scale). + fn zoom_now(&self) -> (f32, bool, f64) { + let factor = self.zoom_factor(); + let e = &self.settings.extras; + let own = (factor, e.zoom_smooth, turn_scale(factor, e.zoom_sensitivity)); + match self.mod_zoom() { + Some(z) if z.factor > factor => (z.factor, z.smooth, f64::from(z.turn)), + _ => own, + } + } /// The field-of-view modifier target, divided by a smooth zoom. pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 { - if self.settings.extras.zoom_smooth { - fov_target(vanilla, self.zoom_factor()) - } else { - vanilla + match self.zoom_now() { + (factor, true, _) => fov_target(vanilla, factor), + _ => vanilla, } } /// The field of view in degrees, divided by an instant zoom. pub(super) fn zoomed_fov_degrees(&self, fov: f32) -> f32 { - if self.settings.extras.zoom_smooth { - fov - } else { - fov / self.zoom_factor() + match self.zoom_now() { + (factor, false, _) => fov / factor, + _ => fov, } } /// Mouse turning while zoomed. pub(super) fn zoom_turn_scale(&self) -> f64 { - turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity) + self.zoom_now().2 } /// The FPS counter and keystrokes, in the HUD layer (hidden with F1 by /// the caller). The top left corner gives way to the debug screen. diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index ac80e8e42..199669957 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -1,6 +1,7 @@ //! Capability `input` (docs/mods.md): the use button on items a mod claims, -//! and the mod's own keys. With no mod claiming items or keys, each hook -//! here returns after one check. +//! the mod's own keys and the mouse wheel; and `render`'s zoom. With no mod +//! claiming items, keys or the wheel, each hook here returns after one +//! check. use super::Game; use winit::{event::MouseButton, keyboard::KeyCode}; #[cfg(feature = "mods")] @@ -20,6 +21,21 @@ impl Game<'_> { false } pub(super) fn mod_key(&mut self, _key: KeyCode, _pressed: bool, _repeat: bool) {} + pub(super) fn mod_mouse_key(&mut self, _button: MouseButton, _pressed: bool) {} + pub(super) fn mod_wheel(&mut self, _steps: f32) -> bool { + false + } + pub(super) fn mod_zoom(&self) -> Option { + None + } +} + +/// A mod's zoom (`render.set-zoom`), clamped by the runtime. +#[derive(Clone, Copy)] +pub(super) struct ModZoom { + pub(super) factor: f32, + pub(super) smooth: bool, + pub(super) turn: f32, } #[cfg(feature = "mods")] @@ -89,4 +105,46 @@ impl Game<'_> { self.mods.mods.key(name, pressed); } } + /// A mouse button while playing: a mod's key bound to it + /// (`key.mouse.4`...), as `mod_key`. + pub(super) fn mod_mouse_key(&mut self, button: MouseButton, pressed: bool) { + if self.mods.mods.has_keys() { + let name = horizon_client::keybinds::mouse_name(button); + self.mods.mods.key(&name, pressed); + } + } + /// Wheel steps while playing: true when a mod holds the wheel, so the + /// hotbar doesn't move. + pub(super) fn mod_wheel(&mut self, steps: f32) -> bool { + self.mods.mods.wheel(steps) + } + /// Playing, with nothing over the world: mods' keys and zoom apply. + fn mod_playing(&self) -> bool { + self.screen == Screen::Playing + && self.title.is_none() + && self.sign_edit.is_none() + && self.book.is_none() + } + /// Once a frame, before the mods run: a screen that opened lets their + /// held keys up. + pub(super) fn mod_input_frame(&mut self) { + let playing = self.mod_playing(); + if self.mods.playing && !playing { + self.mods.mods.release_keys(); + } + self.mods.playing = playing; + } + /// The strongest zoom a mod asks for, while playing; the spyglass's + /// own view wins. + pub(super) fn mod_zoom(&self) -> Option { + if !self.mod_playing() || self.scoping() { + return None; + } + let z = self.mods.mods.zoom()?; + Some(ModZoom { + factor: z.factor, + smooth: z.smooth, + turn: z.turn, + }) + } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 9d6015ad7..63e6314fd 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -55,6 +55,9 @@ pub(super) struct ModsState { /// The HUD font's advances for `render.text-width`, made once. #[cfg(feature = "mods")] font_widths: std::sync::Arc<[f32]>, + /// Playing at the last frame, for `mod_input_frame`. + #[cfg(feature = "mods")] + pub(super) playing: bool, } /// The mappings `input.mapping` answers for, with the default key their @@ -399,6 +402,7 @@ impl Game<'_> { if !self.mods.mods.is_running() { return; } + self.mod_input_frame(); if self.mods.mods.wants_frames() { let snapshot = self.mod_snapshot(); self.mods.mods.set_snapshot(snapshot); diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index b787ff675..5cee9ef51 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -199,9 +199,13 @@ interface input { /// It came up again, or the item left the hand, or a screen opened. use-stop(item-use), /// A key `register-key` named went down or up while playing (no - /// screen open). The game's own mapping on that key still runs. + /// screen open). The game's own mapping on that key still runs. A + /// screen opening lets every held key up. key-down(string), key-up(string), + /// Mouse wheel steps while the mod holds the wheel (`claim-wheel`): + /// positive away from the player, as the hotbar reads them. + wheel(f32), } /// The items whose use the mod handles instead of the game, by id (at /// most 64). Replaces the previous list. @@ -214,6 +218,10 @@ interface input { held: func() -> option; /// The events since the last call, oldest first. poll: func() -> list; + /// Takes the mouse wheel while playing (true) or gives it back: while + /// taken, its steps are the mod's `wheel` events and the hotbar doesn't + /// move. The game gives it back when the mod stops. + claim-wheel: func(on: bool); /// A mapping as the player has bound it. record mapping-state { /// The bound key's name as Controls shows it: `W`, `Space`, `LMB`. @@ -331,6 +339,21 @@ interface render { } /// The game's frame counter, recomputed twice a second. frame-stats: func() -> frame-rate; + record zoom { + /// The field of view is divided by it: 1 is none, at most 10. + factor: f32, + /// Ease in and out through the game's field-of-view easing, as the + /// spyglass does, instead of at once. + smooth: bool, + /// Mouse turning is multiplied by it while zoomed: 1 keeps the + /// player's sensitivity, at least 0.05. + turn: f32, + } + /// Zooms the camera until the next call (`factor` 1 ends it), only + /// while playing: a screen opening or the spyglass's own view (which + /// wins) leave the camera vanilla's. With several mods, the strongest + /// zoom counts. + set-zoom: func(zoom: zoom); } /// What the game calls. Only the hooks `init` asks for are ever called. diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 9e998dae1..4dfd9af51 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -132,9 +132,9 @@ impl Capability { Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", Capability::Ui => "show its own screens and a settings page", - Capability::Render => "draw on your screen and shake the camera", + Capability::Render => "draw on your screen, shake and zoom the camera", Capability::Input => { - "see the keys you hold and your clicks, take over the use button on its own items, and add keys" + "see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys" } } } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index f33839fe7..538b7edd5 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -53,7 +53,7 @@ pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, I /// What capability `render` asks the game to draw (WIT `interface render`). pub use render_bindings::horizon::mods::render::{ Corner as RenderCorner, FillShape, FrameRate, ItemShape, Point as RenderPoint, QuadShape, - Rect as RenderRect, Shape, SpriteShape, TextShape, + Rect as RenderRect, Shape, SpriteShape, TextShape, Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; @@ -189,6 +189,8 @@ struct State { shapes: Vec, /// Capability `render`'s corner panel. corner: Option, + /// Capability `render`'s zoom, when the mod zooms. + zoom: Option, input: InputState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, @@ -331,6 +333,7 @@ impl Mods { ui: UiState::default(), shapes: Vec::new(), corner: None, + zoom: None, input: InputState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, @@ -587,6 +590,16 @@ impl Mods { .map(|k| k.name.clone()) .collect(); for name in names { + let held = input.down.iter().position(|n| *n == name); + match (down, held) { + (true, None) => input.down.push(name.clone()), + (false, Some(i)) => { + input.down.swap_remove(i); + } + // Already let go when a screen opened. + (false, None) => continue, + (true, Some(_)) => {} + } input.push(if down { InputEvent::KeyDown(name) } else { @@ -595,6 +608,35 @@ impl Mods { } } } + /// A screen opened, or the game stopped playing: every mod key held + /// lets go (`key-up`), so a key needs a new press afterwards. + pub fn release_keys(&mut self) { + for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) { + let input = &mut run.store.data_mut().input; + for name in std::mem::take(&mut input.down) { + input.push(InputEvent::KeyUp(name)); + } + } + } + /// Some running mod holds the mouse wheel. + pub fn wheel_claimed(&self) -> bool { + self.inputs().any(|i| i.wheel) + } + /// Wheel steps while playing: `wheel` to the mods holding it; false + /// when none does (the hotbar takes them). + pub fn wheel(&mut self, steps: f32) -> bool { + let event = InputEvent::Wheel(steps); + let claimed = self.wheel_claimed(); + self.push_input(|i| i.wheel, &event); + claimed + } + /// The strongest zoom a running mod asks for (capability `render`). + pub fn zoom(&self) -> Option { + self.entries + .iter() + .filter_map(|e| e.run.as_ref()?.store.data().zoom) + .max_by(|a, b| a.factor.total_cmp(&b.factor)) + } fn inputs(&self) -> impl Iterator { self.entries .iter() @@ -824,6 +866,10 @@ struct InputState { claimed: Vec, keys: Vec, events: std::collections::VecDeque, + /// The mod's keys held now, by name. + down: Vec, + /// It holds the mouse wheel. + wheel: bool, } /// Events kept for `poll`, items claimed and keys, per mod. const INPUT_EVENTS: usize = 256; @@ -889,12 +935,19 @@ impl input::Host for State { fn clicks_per_second(&mut self) -> (u32, u32) { self.snapshot.cps } + fn claim_wheel(&mut self, on: bool) { + self.input.wheel = on; + } } /// HUD shapes one mod may keep (capability `render`). const SHAPES: usize = 1024; /// The longest jolt `render.shake` makes, in seconds. const SHAKE_SECONDS: f32 = 10.0; +/// `render.set-zoom`'s limits: `Camera.tickFov` keeps the modifier at 0.1 +/// or more, and turning never stops. +const ZOOM_MAX: f32 = 10.0; +const TURN_MIN: f32 = 0.05; /// A mod's corner panel: shapes in a `width` × `height` box the game /// places in `corner`, stacked with the other overlays. @@ -963,6 +1016,19 @@ impl render::Host for State { .sum::() .ceil() } + fn set_zoom(&mut self, zoom: ModZoom) { + let finite = |v: f32, lo: f32, hi: f32| if v.is_finite() { v.clamp(lo, hi) } else { lo }; + let factor = finite(zoom.factor, 1.0, ZOOM_MAX); + self.zoom = (factor > 1.0).then(|| ModZoom { + factor, + smooth: zoom.smooth, + turn: if zoom.turn.is_finite() { + zoom.turn.clamp(TURN_MIN, 1.0) + } else { + 1.0 + }, + }); + } fn frame_stats(&mut self) -> FrameRate { let (fps, min, low) = self.snapshot.frame; FrameRate { fps, min, low } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index a9de4f55b..780899289 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -506,6 +506,56 @@ fn input_claims_keys_and_events() { }); assert!(mods.command("input_held")); assert_eq!(chat(&mut mods), ["holding minecraft:stick x3 in 2"]); + // A screen opening lets held keys up, once; the release that follows + // is not sent again. + mods.key("key.keyboard.r", true); + mods.release_keys(); + mods.release_keys(); + mods.key("key.keyboard.r", false); + assert!(mods.command("input_poll")); + assert_eq!(chat(&mut mods), ["key-down wheel", "key-up wheel"]); +} + +#[test] +fn input_wheel_is_the_mods_while_claimed() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let chat = |mods: &mut Mods| -> Vec { + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect() + }; + // Unclaimed, the hotbar keeps the wheel and the mod hears nothing. + assert!(!mods.wheel_claimed() && !mods.wheel(1.0)); + assert!(mods.command("input_wheel")); + assert!(mods.wheel_claimed()); + assert!(mods.wheel(1.0) && mods.wheel(-2.0)); + assert!(mods.command("input_poll")); + assert_eq!(chat(&mut mods), ["wheel 1", "wheel -2"]); + assert!(mods.command("input_wheel off")); + assert!(!mods.wheel(1.0)); +} + +#[test] +fn render_zoom_is_clamped_and_the_strongest_counts() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let zoom = |mods: &mut Mods, args: &str| { + assert!(mods.command(&format!("zoom {args}"))); + mods.zoom().map(|z| (z.factor, z.smooth, z.turn)) + }; + assert!(mods.zoom().is_none()); + assert_eq!(zoom(&mut mods, "4 1 0.25"), Some((4.0, true, 0.25))); + // Over 10 and a turn under 0.05 are clamped. + assert_eq!(zoom(&mut mods, "50 0 0"), Some((10.0, false, 0.05))); + // A NaN turn keeps the player's sensitivity. + assert_eq!(zoom(&mut mods, "2 0 x"), Some((2.0, false, 1.0))); + // 1, under 1 and NaN end the zoom. + assert_eq!(zoom(&mut mods, "1 0 1"), None); + assert_eq!(zoom(&mut mods, "0.5 0 1"), None); + assert_eq!(zoom(&mut mods, "x 0 1"), None); } #[test] diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index ae6e4dfc4..1555b44f0 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -2,7 +2,8 @@ //! of each widget, `/ui_settings` sets a settings page, `/ui_close` closes //! the screen; the `ui-events` calls answer in chat so the host sees them. //! `/render_hud`, `/render_clear` and `/render_shake` test `render`; -//! `/input_claim`, `/input_poll` and `/input_held` test `input`; +//! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test +//! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use. use horizon_mod_sdk::{ Mod, Registration, chat, @@ -93,6 +94,8 @@ impl Mod for Guest { "input_claim", "input_poll", "input_held", + "input_wheel", + "zoom", "corner", "readings", ] @@ -100,7 +103,7 @@ impl Mod for Guest { .fold(Registration::new(), Registration::command); Ok((Guest, hooks)) } - fn command(&mut self, name: &str, _args: &str) -> Result, String> { + fn command(&mut self, name: &str, args: &str) -> Result, String> { match name { "ui_screen" => ui::open_screen(&Screen { title: "Guest's screen".into(), @@ -167,6 +170,7 @@ impl Mod for Guest { Event::UseStop(u) => format!("use-stop {} {}", u.item.id, u.ticks), Event::KeyDown(k) => format!("key-down {k}"), Event::KeyUp(k) => format!("key-up {k}"), + Event::Wheel(steps) => format!("wheel {steps}"), }); } } @@ -176,6 +180,19 @@ impl Mod for Guest { }); chat::show(&format!("holding {held}")); } + "input_wheel" => input::claim_wheel(args != "off"), + "zoom" => { + let mut words = args.split(' '); + let mut number = || words.next().and_then(|w| w.parse().ok()).unwrap_or(f32::NAN); + let factor = number(); + let smooth = number() == 1.0; + let turn = number(); + render::set_zoom(render::Zoom { + factor, + smooth, + turn, + }); + } // Clamped to (1, 10); the two after it shake nothing. "render_shake" => { render::shake(2.0, 99.0); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 333b65bd0..209a8298d 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -13,8 +13,8 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`, | `storage` | [`storage`](#storage) | save its own settings to disk | | `registries` | data files (`assets/`, `data/`), no interface | add blocks and items to your worlds | | `ui` | [`ui`](#ui) | show its own screens and a settings page | -| `render` | [`render`](#render) | draw on your screen and shake the camera | -| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items, and add keys | +| `render` | [`render`](#render) | draw on your screen, shake and zoom the camera | +| `input` | [`input`](#input) | see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys | ## World `horizon-mod` @@ -251,8 +251,9 @@ The main hand's stack. | --- | --- | --- | | `use-start` | `item-use` | The use button went down with a claimed item in the main hand. The game does nothing else with the click: no placing, no eating, no swing. | | `use-stop` | `item-use` | It came up again, or the item left the hand, or a screen opened. | -| `key-down` | `string` | A key `register-key` named went down or up while playing (no screen open). The game's own mapping on that key still runs. | +| `key-down` | `string` | A key `register-key` named went down or up while playing (no screen open). The game's own mapping on that key still runs. A screen opening lets every held key up. | | `key-up` | `string` | | +| `wheel` | `f32` | Mouse wheel steps while the mod holds the wheel (`claim-wheel`): positive away from the player, as the hotbar reads them. | ### record `mapping-state` @@ -269,6 +270,7 @@ A mapping as the player has bound it. | `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`). At most 16; an unknown key is an error. | | `held` | `func() -> option` | The main hand's stack, as of this tick; none when it is empty. | | `poll` | `func() -> list` | The events since the last call, oldest first. | +| `claim-wheel` | `func(on: bool)` | Takes the mouse wheel while playing (true) or gives it back: while taken, its steps are the mod's `wheel` events and the hotbar doesn't move. The game gives it back when the mod stops. | | `mapping` | `func(name: string) -> option` | A movement or click mapping as the player has bound it: `key.forward`, `key.left`, `key.back`, `key.right`, `key.jump`, `key.sneak`, `key.sprint`, `key.attack` or `key.use`. None for another name. | | `clicks-per-second` | `func() -> tuple` | Clicks of the attack and use buttons in the last second. | @@ -369,6 +371,14 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `min` | `u32` | The slowest frame's rate, and the 1% low (the 99th percentile frame time's rate), over the last 5 seconds. | | `low` | `u32` | | +### record `zoom` + +| Field | Type | | +| --- | --- | --- | +| `factor` | `f32` | The field of view is divided by it: 1 is none, at most 10. | +| `smooth` | `bool` | Ease in and out through the game's field-of-view easing, as the spyglass does, instead of at once. | +| `turn` | `f32` | Mouse turning is multiplied by it while zoomed: 1 keeps the player's sensitivity, at least 0.05. | + | Function | Signature | What it does | | --- | --- | --- | | `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | @@ -378,6 +388,7 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `clear-corner` | `func()` | Removes the mod's corner panel. | | `text-width` | `func(text: string) -> f32` | The width of one line of text in GUI pixels, in the HUD's font: exact for Latin letters (U+0000 to U+024F), 6 per other character. | | `frame-stats` | `func() -> frame-rate` | The game's frame counter, recomputed twice a second. | +| `set-zoom` | `func(zoom: zoom)` | Zooms the camera until the next call (`factor` 1 ends it), only while playing: a screen opening or the spyglass's own view (which wins) leave the camera vanilla's. With several mods, the strongest zoom counts. | ## `events` diff --git a/docs/api/stability.md b/docs/api/stability.md index b513d5ddf..485d805af 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -88,8 +88,8 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | --- | --- | --- | | Mod API: `log`, `game`, `chat`, `hud`, `storage`, `events` | preview | 0.1.0 | | Mod API: `ui`, `ui-events` (a mod's screens and settings page) | experimental | manifest `experimental = ["ui"]` | -| Mod API: `render` (HUD shapes, camera shake; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | -| Mod API: `input` (claimed items' use, the mod's keys) | experimental | manifest `experimental = ["input"]` | +| Mod API: `render` (HUD shapes, camera shake and zoom; drawn by the game, no mod shaders) | experimental | manifest `experimental = ["render"]` | +| Mod API: `input` (claimed items' use, the mod's keys, the mouse wheel) | experimental | manifest `experimental = ["input"]` | | Content mods (`registries`: data-driven blocks and items) | preview | manifest `api = "0.2"` | | Server mods (events, world, server commands) | not started | manifest `api = "0.3"`, experimental first | | Script mods (Lua run by an interpreter mod, [mods.md](mods.md#ways-in)) | not started | | @@ -104,3 +104,12 @@ Deprecations and breaking changes are in bold. The release notes of the game rel | Telemetry batch and consent | stable | `"schema": 1`, consent `2` | | `horizon-graphics.txt`, `horizon-extras.txt`, `horizon-mods.txt` | preview | none | | `SHA256SUMS` and `SHA256SUMS.sig` | stable | | + +### The experimental mod APIs' choices + +- **What a mod may take from the game.** `input.claim-wheel` is the one input a mod consumes: while it holds the + wheel, the steps are its `wheel` events and the hotbar doesn't move. `claim-items` takes the use button only on the + items it names. A mod's keys (`register-key`) never consume: vanilla's mapping on the same key still runs. Whether + keys may consume too is decided before `input` becomes preview. +- **`input`'s `wheel` event** is a new case in a variant the game sends, so it breaks mods built before it (allowed + because `input` is experimental): an `input` mod that calls `poll` needs a rebuild against the new WIT. diff --git a/docs/mods.md b/docs/mods.md index d92c88fa6..9a75badb6 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,8 +87,8 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | -| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects. The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | -| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | +| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | +| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | | Hook (export) | When | |---|---| From de294e34bbddb7bb2e8dc48c86efe1c662421e53 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:19:07 +0100 Subject: [PATCH 2/6] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/extras.rs | 6 +++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 1978d003f..a04196b69 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -234,7 +234,11 @@ impl Game<'_> { fn zoom_now(&self) -> (f32, bool, f64) { let factor = self.zoom_factor(); let e = &self.settings.extras; - let own = (factor, e.zoom_smooth, turn_scale(factor, e.zoom_sensitivity)); + let own = ( + factor, + e.zoom_smooth, + turn_scale(factor, e.zoom_sensitivity), + ); match self.mod_zoom() { Some(z) if z.factor > factor => (z.factor, z.smooth, f64::from(z.turn)), _ => own, diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 1555b44f0..9bede11f9 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -183,7 +183,12 @@ impl Mod for Guest { "input_wheel" => input::claim_wheel(args != "off"), "zoom" => { let mut words = args.split(' '); - let mut number = || words.next().and_then(|w| w.parse().ok()).unwrap_or(f32::NAN); + let mut number = || { + words + .next() + .and_then(|w| w.parse().ok()) + .unwrap_or(f32::NAN) + }; let factor = number(); let smooth = number() == 1.0; let turn = number(); From 7e4012c83ec859b5fa18f6f5975e49f97719854a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 04:41:12 +0100 Subject: [PATCH 3/6] Mod API: a key widget, so players bind a mod's keys (ui, input) A ui page's key widget shows one of the mod's keys as Key Binds does ("Zoom: Z"). A click waits for the next key or mouse button, which becomes the key; Esc binds none. The game keeps the choice in horizon-mods.txt (key..:key.keyboard.z), applies it when the mods load and to keys registered later, and lets a held key go when it is rebound. register-key's key is now the default. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 7 +- crates/horizon-client/src/game/mods.rs | 123 +++++++++++++++++- crates/horizon-client/src/mod_list.rs | 52 +++++++- crates/horizon-mod-sdk/wit/horizon.wit | 15 ++- crates/horizon-mods/src/runtime.rs | 67 +++++++++- crates/horizon-mods/tests/sandbox.rs | 41 +++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 11 +- docs/api/mods-reference.md | 12 +- docs/mods.md | 2 +- 9 files changed, 312 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 3f7450501..bb68dc590 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10451,6 +10451,9 @@ impl Game<'_> { } return Ok(()); } + if self.screen == Screen::Mod && self.mod_screen_key(key) { + return Ok(()); + } if self.sort_key_press(key) { return Ok(()); } @@ -11363,9 +11366,7 @@ impl ApplicationHandler for Game<'_> { .map_or([1, 1], |r| [r.config.width, r.config.height]); self.stats_click(size); } - Screen::Mod if pressed && button == MouseButton::Left => { - self.mod_screen_click() - } + Screen::Mod if pressed => self.mod_screen_click(button), _ => {} } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 6211f43b1..66d00b233 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -29,6 +29,7 @@ use { }, horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, std::time::Instant, + winit::{event::MouseButton, keyboard::KeyCode}, }; #[derive(Default)] @@ -101,6 +102,8 @@ struct ModScreen { under: Screen, /// One scroll per `list` widget, in widget order. scrolls: Vec, + /// A key widget waiting for the key to bind: the mod key's name. + binding: Option, } impl ModsState { /// The chat's command tree: vanilla's, plus the running mods' commands. @@ -240,7 +243,10 @@ impl Game<'_> { pub(super) fn open_mod_screen(&mut self, _owner: usize, _settings: bool) {} pub(super) fn close_mod_screen(&mut self, _tell: bool) {} pub(super) fn draw_mod_screen(&mut self, _batch: &mut HudBatch) {} - pub(super) fn mod_screen_click(&mut self) {} + pub(super) fn mod_screen_click(&mut self, _button: winit::event::MouseButton) {} + pub(super) fn mod_screen_key(&mut self, _key: winit::keyboard::KeyCode) -> bool { + false + } pub(super) fn mod_screen_scroll(&mut self, _delta: f32) {} } @@ -263,6 +269,8 @@ impl Game<'_> { let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id); let mods = Mods::load(&paths, on, vanilla_command); self.mods.mods = mods; + let chosen = &self.settings.mods; + self.mods.mods.set_bindings(|id| chosen.keys_of(id)); // Entries were replaced wholesale: a screen's owner index is stale. self.mods.screen = None; self.list_mods(); @@ -429,6 +437,8 @@ impl Game<'_> { { self.mods.checked = Some(Instant::now()); if self.mods.mods.reload_changed(vanilla_command) { + let chosen = &self.settings.mods; + self.mods.mods.set_bindings(|id| chosen.keys_of(id)); self.list_mods(); self.sync_mod_commands(); self.system_message(Text::literal("Mods reloaded").with_color(text::GRAY)); @@ -579,6 +589,72 @@ impl Game<'_> { Some((s.title.as_str(), s.widgets.as_slice())) } } + /// A key widget's label as Key Binds shows one, "Zoom: Z", marked + /// "> Zoom: Z <" in yellow while it waits for the new key. + fn mod_key_label(mods: &Mods, owner: usize, name: &str, waiting: bool) -> Text { + let (label, key) = mods + .keys_of(owner) + .iter() + .find(|k| k.name == name) + .map_or((name, "key.keyboard.unknown"), |k| { + (k.label.as_str(), k.key.as_str()) + }); + let value = format!("{label}: {}", keybinds::display_name(key).plain()); + if waiting { + Text::literal(format!("> {value} <")).with_color(text::YELLOW) + } else { + Text::literal(value) + } + } + /// The player bound the key widget that waited to `key`: the mod's key + /// follows it now and at the next start (`horizon-mods.txt`). + fn bind_mod_key(&mut self, key: String) { + let Some(ms) = self.mods.screen.as_mut() else { + return; + }; + let Some(name) = ms.binding.take() else { + return; + }; + let owner = ms.owner; + if !self.mods.mods.rebind(owner, &name, &key) { + return; + } + let Some(id) = self + .mods + .mods + .entries() + .get(owner) + .and_then(|e| e.manifest.as_ref()) + .map(|m| m.id.clone()) + else { + return; + }; + self.settings + .mods + .keys + .entry(id) + .or_default() + .insert(name, key); + self.settings.save(&Self::options_path()); + } + /// A key while a mod screen is up: true when a key widget waited for + /// it (Key Binds: Escape binds none). + pub(super) fn mod_screen_key(&mut self, key: KeyCode) -> bool { + if self + .mods + .screen + .as_ref() + .is_none_or(|ms| ms.binding.is_none()) + { + return false; + } + let value = match key { + KeyCode::Escape => None, + k => keybinds::key_name(k), + }; + self.bind_mod_key(value.unwrap_or("key.keyboard.unknown").to_owned()); + true + } /// The layout the mod screen's widgets get at `h`: (widget, top, /// height), the column being `COLUMN` wide down the middle. fn mod_ui_layout(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { @@ -587,7 +663,7 @@ impl Game<'_> { for w in widgets { let wh = match w { UiWidget::Text(_) => 12.0, - UiWidget::Item(_) | UiWidget::Button(_) => 20.0, + UiWidget::Item(_) | UiWidget::Button(_) | UiWidget::Key(_) => 20.0, UiWidget::List(l) => (l.rows.len().min(6) as f32 * 12.0) + 8.0, }; // Nothing may cover Done; a crowded mod loses what won't fit. @@ -617,6 +693,7 @@ impl Game<'_> { settings, under: self.screen, scrolls: Vec::new(), + binding: None, }); self.screen = Screen::Mod; if self.player.is_some() { @@ -697,6 +774,22 @@ impl Game<'_> { hover, ); } + UiWidget::Key(k) => { + let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); + let waiting = ms.binding.as_deref() == Some(k.key.as_str()); + let label = Self::mod_key_label(&self.mods.mods, ms.owner, &k.key, waiting); + ui::button( + batch, + atlas, + x, + wy, + MOD_UI_COLUMN, + 20.0, + &label, + true, + hover, + ); + } UiWidget::Text(t) => { let color = if t.color == 0 { u32::MAX @@ -798,7 +891,20 @@ impl Game<'_> { } /// A click on the mod screen: Done leaves it, a `list` row is the mod's /// `ui-events::select`. - pub(super) fn mod_screen_click(&mut self) { + pub(super) fn mod_screen_click(&mut self, button: MouseButton) { + // Key Binds: a mouse button pressed while waiting binds it. + if self + .mods + .screen + .as_ref() + .is_some_and(|ms| ms.binding.is_some()) + { + self.bind_mod_key(keybinds::mouse_name(button)); + return; + } + if button != MouseButton::Left { + return; + } let (w, h) = self.gui_size(); let cursor = self.cursor; if ui::hovered(cursor, (w / 2.0).floor() - 100.0, h - 27.0, 200.0, 20.0) { @@ -829,6 +935,17 @@ impl Game<'_> { self.show_mod_output(); return; } + // A key widget waits for the key to bind. + if let UiWidget::Key(k) = w + && ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) + { + self.audio.play_button_click(); + let name = k.key.clone(); + if let Some(ms) = self.mods.screen.as_mut() { + ms.binding = Some(name); + } + return; + } let UiWidget::List(l) = w else { continue }; let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default(); list_i += 1; diff --git a/crates/horizon-client/src/mod_list.rs b/crates/horizon-client/src/mod_list.rs index db2ea9194..325839738 100644 --- a/crates/horizon-client/src/mod_list.rs +++ b/crates/horizon-client/src/mod_list.rs @@ -1,7 +1,11 @@ //! Which of the installed Horizon mods are on (`docs/mods.md`), kept in //! `horizon-mods.txt` beside `options.txt` as `mod.:true` lines. Every //! mod is off until the player turns it on in Options > Mods. -use std::{collections::BTreeSet, fs, path::Path}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, +}; pub const FILE: &str = "horizon-mods.txt"; /// The folder holding `.hmod` files, beside `options.txt`. @@ -11,6 +15,9 @@ pub const DIR: &str = "horizon-mods"; pub struct ModList { /// Ids of the mods the player turned on. pub enabled: BTreeSet, + /// The keys the player chose for mods' keys, mod id → key name → key + /// (`key..:key.keyboard.x` lines). + pub keys: BTreeMap>, /// What the Mods page shows, filled by the game from the mods it found. pub installed: Vec, } @@ -45,20 +52,41 @@ impl ModList { .filter_map(|(k, _)| k.trim().strip_prefix("mod.")) .map(str::to_owned) .collect(); + let mut keys: BTreeMap> = BTreeMap::new(); + for (k, v) in text.lines().filter_map(|l| l.split_once(':')) { + // Mod ids have no dots; a key's name may. + if let Some((id, name)) = k + .trim() + .strip_prefix("key.") + .and_then(|r| r.split_once('.')) + { + let entry = keys.entry(id.to_owned()).or_default(); + entry.insert(name.to_owned(), v.trim().to_owned()); + } + } Self { enabled, + keys, installed: Vec::new(), } } pub fn serialize(&self) -> String { - self.enabled - .iter() - .map(|id| format!("mod.{id}:true\n")) - .collect() + let on = self.enabled.iter().map(|id| format!("mod.{id}:true\n")); + let keys = self.keys.iter().flat_map(|(id, keys)| { + keys.iter() + .map(move |(name, key)| format!("key.{id}.{name}:{key}\n")) + }); + on.chain(keys).collect() + } + /// Mod `id`'s chosen keys, for `Mods::set_bindings`. + pub fn keys_of(&self, id: &str) -> Vec<(&str, &str)> { + self.keys.get(id).map_or_else(Vec::new, |k| { + k.iter().map(|(n, k)| (n.as_str(), k.as_str())).collect() + }) } pub fn save(&self, dir: &Path) { let path = dir.join(FILE); - if self.enabled.is_empty() && !path.exists() { + if self.enabled.is_empty() && self.keys.is_empty() && !path.exists() { return; } let _ = fs::write(path, self.serialize()); @@ -91,6 +119,18 @@ mod tests { assert_eq!(ModList::default().serialize(), ""); } + #[test] + fn keeps_the_keys_players_chose() { + let text = "mod.zoom:true\nkey.zoom.zoom.in:key.mouse.4\nkey.zoom.out:key.keyboard.x\n"; + let list = ModList::parse(text); + assert_eq!( + list.keys_of("zoom"), + [("out", "key.keyboard.x"), ("zoom.in", "key.mouse.4")] + ); + assert!(list.keys_of("other").is_empty()); + assert_eq!(ModList::parse(&list.serialize()), list); + } + #[test] fn toggles_installed_mods_but_not_dev_ones() { let installed = |id: &str, dev| Installed { diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 820a82483..f9c147cfa 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -137,6 +137,16 @@ interface ui { /// Up to 256 characters. label: string, } + /// One of the mod's keys (`input.register-key`) as Controls shows a + /// binding, "Zoom: Z". A click waits for the next key or mouse button, + /// which becomes the key (Esc: none). The game keeps the player's + /// choice across starts; the mod's `key-down` and `key-up` follow it. + record key-widget { + /// The mod's own name for the widget. + id: u32, + /// The name the mod registered the key under. + key: string, + } variant widget { /// Text the player reads. text(text-widget), @@ -146,6 +156,8 @@ interface ui { item(item-widget), /// Rows the player picks from. %list(list-widget), + /// A key the player binds. + key(key-widget), } /// A screen the mod owns: a title over widgets stacked down the middle, /// the Done button the game adds, and Esc to leave it. @@ -220,7 +232,8 @@ interface input { claim-items: func(ids: list); /// A key of the mod's: `name` comes back in `key-down` and `key-up`, /// `label` says what it does, `key` is the key as options.txt writes - /// it (`key.keyboard.r`). At most 16; an unknown key is an error. + /// it (`key.keyboard.r`), the default: a key the player chose for it + /// (`ui`'s key widget) wins. At most 16; an unknown key is an error. register-key: func(name: string, label: string, key: string) -> result<_, string>; /// The main hand's stack, as of this tick; none when it is empty. held: func() -> option; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 0e7c079d2..f596db81c 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -37,7 +37,8 @@ use bindings::{ /// The widget model a `ui` screen or settings page shows (WIT `interface /// ui`), for the game to draw with its menus' own widgets. pub use ui_bindings::horizon::mods::ui::{ - ButtonWidget, ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, + ButtonWidget, ItemWidget, KeyWidget, ListWidget, Screen as UiScreen, TextWidget, + Widget as UiWidget, }; use ui_bindings::{UiHost, horizon::mods::ui}; /// Capability `render`'s imports (docs/mods.md): the game draws the shapes. @@ -564,6 +565,48 @@ impl Mods { d.input.keys.iter().map(move |k| (d.name.as_str(), k)) }) } + /// Mod `i`'s keys, as it registered them (with the player's choices). + pub fn keys_of(&self, i: usize) -> &[ModKey] { + self.entries + .get(i) + .and_then(|e| e.run.as_ref()) + .map_or(&[], |r| r.store.data().input.keys.as_slice()) + } + /// The keys the player chose (`ui`'s key widget), by mod id: each + /// running mod's `name → key`. They replace the defaults registered + /// so far and later ones. Keys that aren't keys are skipped. + pub fn set_bindings<'a>(&mut self, chosen: impl Fn(&str) -> Vec<(&'a str, &'a str)>) { + for e in &mut self.entries { + let (Some(m), Some(run)) = (&e.manifest, e.run.as_mut()) else { + continue; + }; + let input = &mut run.store.data_mut().input; + input.bindings = chosen(&m.id) + .into_iter() + .filter(|(_, key)| key_ok(key)) + .map(|(n, k)| (n.to_owned(), k.to_owned())) + .collect(); + for (name, key) in input.bindings.clone() { + input.rebind(&name, key); + } + } + } + /// The player binds mod `i`'s key `name` to `key` (`key.keyboard.x`, + /// `key.mouse.4`, `key.keyboard.unknown` for none). False when the mod + /// has no such key or `key` isn't one. + pub fn rebind(&mut self, i: usize, name: &str, key: &str) -> bool { + let Some(run) = self.entries.get_mut(i).and_then(|e| e.run.as_mut()) else { + return false; + }; + let input = &mut run.store.data_mut().input; + if !key_ok(key) || !input.keys.iter().any(|k| k.name == name) { + return false; + } + input.bindings.retain(|(n, _)| n != name); + input.bindings.push((name.to_owned(), key.to_owned())); + input.rebind(name, key.to_owned()); + true + } /// The use button went down with `item`: `use-start` to each mod that /// claimed it. pub fn use_start(&mut self, item: &HeldItem) { @@ -813,6 +856,10 @@ fn clip_widgets(widgets: Vec) -> Vec { l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len()); UiWidget::List(l) } + UiWidget::Key(mut k) => { + k.key = clip(k.key); + UiWidget::Key(k) + } }) .collect() } @@ -873,6 +920,9 @@ struct InputState { down: Vec, /// It holds the mouse wheel. wheel: bool, + /// The keys the player chose, `name → key`: they win over + /// `register-key`'s. + bindings: Vec<(String, String)>, } /// Events kept for `poll`, items claimed and keys, per mod. const INPUT_EVENTS: usize = 256; @@ -893,6 +943,17 @@ fn key_ok(key: &str) -> bool { } impl InputState { + /// Key `name` is `key` now; held, it lets go first. + fn rebind(&mut self, name: &str, key: String) { + let Some(k) = self.keys.iter_mut().find(|k| k.name == name) else { + return; + }; + k.key = key; + if let Some(i) = self.down.iter().position(|n| n == name) { + let name = self.down.swap_remove(i); + self.push(InputEvent::KeyUp(name)); + } + } fn push(&mut self, event: InputEvent) { if self.events.len() == INPUT_EVENTS { self.events.pop_front(); @@ -912,6 +973,10 @@ impl input::Host for State { )); } let (name, label) = (clip(name), clip(label)); + let key = match self.input.bindings.iter().find(|(n, _)| *n == name) { + Some((_, chosen)) => chosen.clone(), + None => key, + }; if let Some(k) = self.input.keys.iter_mut().find(|k| k.name == name) { (k.label, k.key) = (label, key); return Ok(()); diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 29577a9c6..793d03db6 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -449,7 +449,7 @@ fn ui_screens_settings_and_events() { assert_eq!(mods.settings_widgets(0).len(), 3); assert!(mods.entries()[0].has_ui_settings()); mods.ui_settings_opened(0); - assert_eq!(mods.settings_widgets(0).len(), 2); + assert_eq!(mods.settings_widgets(0).len(), 3); // `/ui_close` closes the mod's own screen. assert!(mods.command("ui_close")); assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 })); @@ -553,6 +553,45 @@ fn input_claims_keys_and_events() { assert_eq!(chat(&mut mods), ["key-down wheel", "key-up wheel"]); } +#[test] +fn the_players_key_choice_wins() { + let chat = |mods: &mut Mods| -> Vec { + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text), + _ => None, + }) + .collect() + }; + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + assert!(mods.command("input_claim")); + assert!(matches!( + &mods.settings_widgets(0)[0], + horizon_mods::UiWidget::Key(k) if k.id == 9 && k.key == "wheel" + )); + // Rebinding while held lets the old key go. + mods.key("key.keyboard.r", true); + assert!(mods.rebind(0, "wheel", "key.mouse.4")); + assert_eq!(mods.keys_of(0)[0].key, "key.mouse.4"); + mods.key("key.keyboard.r", false); + mods.key("key.mouse.4", true); + assert!(!mods.rebind(0, "wheel", "R") && !mods.rebind(0, "nope", "key.keyboard.g")); + chat(&mut mods); + assert!(mods.command("input_poll")); + assert_eq!( + chat(&mut mods), + ["key-down wheel", "key-up wheel", "key-down wheel"] + ); + // A choice saved earlier replaces the default, registered before or after. + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + mods.set_bindings(|_| vec![("wheel", "key.keyboard.g"), ("bad", "G")]); + assert!(mods.command("input_claim")); + assert_eq!(mods.keys_of(0)[0].key, "key.keyboard.g"); + mods.set_bindings(|_| vec![("wheel", "key.keyboard.h")]); + assert_eq!(mods.keys_of(0)[0].key, "key.keyboard.h"); +} + #[test] fn input_wheel_is_the_mods_while_claimed() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 9bede11f9..f2765e8da 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -9,7 +9,7 @@ use horizon_mod_sdk::{ Mod, Registration, chat, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, - ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, + ui::{self, ItemWidget, KeyWidget, ListWidget, Screen, TextWidget, Widget}, }; /// One of each shape, the text too long by 44 characters. @@ -162,6 +162,10 @@ impl Mod for Guest { // Not a key: refused. let bad = input::register_key("bad", "Bad", "R").unwrap_err(); chat::show(&format!("claimed; {bad}")); + ui::set_settings(&[Widget::Key(KeyWidget { + id: 9, + key: "wheel".into(), + })]); } "input_poll" => { for event in input::poll() { @@ -225,6 +229,11 @@ impl Mod for Guest { id: 3, label: "Corner: Top Right".into(), }), + // `/input_claim`'s key; drawn as its name until registered. + Widget::Key(KeyWidget { + id: 9, + key: "wheel".into(), + }), ]); chat::show("settings opened"); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 0deeb0ddd..f525ace89 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -197,6 +197,15 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `id` | `u32` | The mod's own name for the widget. | | `label` | `string` | Up to 256 characters. | +### record `key-widget` + +One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: Z". A click waits for the next key or mouse button, which becomes the key (Esc: none). The game keeps the player's choice across starts; the mod's `key-down` and `key-up` follow it. + +| Field | Type | | +| --- | --- | --- | +| `id` | `u32` | The mod's own name for the widget. | +| `key` | `string` | The name the mod registered the key under. | + ### variant `widget` | Case | Payload | | @@ -205,6 +214,7 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `button` | `button-widget` | A button. | | `item` | `item-widget` | An item's icon and name. | | `list` | `list-widget` | Rows the player picks from. | +| `key` | `key-widget` | A key the player binds. | ### record `screen` @@ -278,7 +288,7 @@ A mapping as the player has bound it. | Function | Signature | What it does | | --- | --- | --- | | `claim-items` | `func(ids: list)` | The items whose use the mod handles instead of the game, by id (at most 64). Replaces the previous list. | -| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`). At most 16; an unknown key is an error. | +| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: a key the player chose for it (`ui`'s key widget) wins. At most 16; an unknown key is an error. | | `held` | `func() -> option` | The main hand's stack, as of this tick; none when it is empty. | | `poll` | `func() -> list` | The events since the last call, oldest first. | | `claim-wheel` | `func(on: bool)` | Takes the mouse wheel while playing (true) or gives it back: while taken, its steps are the mod's `wheel` events and the hotbar doesn't move. The game gives it back when the mod stops. | diff --git a/docs/mods.md b/docs/mods.md index 235574d6c..108e854be 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,7 +87,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item, list and key widgets the game lays out and draws with its own menus' code. A key widget binds one of the mod's keys (`input.register-key`) as Key Binds does: click, then press the key or mouse button (Esc: none); the game keeps the choice in `horizon-mods.txt` (`key..:key.keyboard.z`) and the mod's `key-down` follows it. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | From 53289d3565bb70df52876cc8cf23603a54901eb5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:08:36 +0100 Subject: [PATCH 4/6] Official mod: Zoom, the zoom extra as a mod mods/official/zoom: hold the key (Z) to zoom in at the starting zoom, the wheel changes it while held (x1.25 a step, 1.25 to 10), smooth easing and slower turning as options. Same settings page as the extra, with the key widget for the key. Built on render.set-zoom, input.claim-wheel and ui's key widget. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 7 ++ Cargo.toml | 2 +- docs/mods.md | 3 +- mods/official/zoom/Cargo.toml | 16 +++ mods/official/zoom/horizon-mod.toml | 9 ++ mods/official/zoom/src/lib.rs | 145 ++++++++++++++++++++++++++++ 6 files changed, 180 insertions(+), 2 deletions(-) create mode 100644 mods/official/zoom/Cargo.toml create mode 100644 mods/official/zoom/horizon-mod.toml create mode 100644 mods/official/zoom/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 6e9b41b33..30c0b14d7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5330,6 +5330,13 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zoom" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "zopfli" version = "0.8.4" diff --git a/Cargo.toml b/Cargo.toml index cc88441a4..259734b98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "mods/official/fps-overlay", "mods/official/keystrokes", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/docs/mods.md b/docs/mods.md index 13273fa2e..bfa196cb1 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | -| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes | +| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | @@ -426,6 +426,7 @@ so the same rustc and `Cargo.lock` give the same file. |---|---|---|---| | FPS Counter | `fps_overlay` | Extras > FPS counter | `corner`: `top_left` (default), `top_right`, `bottom_left`, `bottom_right`; `lows`: `false` (default), `true` | | Keystrokes | `keystrokes` | Extras > Keystrokes | `corner`: as above, default `top_left`; `cps`: `true` (default), `false` | +| Zoom | `zoom` | Extras > Zoom | `level`: `2`, `3`, `4` (default), `6`, `8`, `10`; `smooth`: `true` (default), `false`; `sensitivity` (slower turning): `true` (default), `false`. The key is the game's: `key.zoom.zoom` in `horizon-mods.txt`, default `key.keyboard.z` | ## Versions and compatibility diff --git a/mods/official/zoom/Cargo.toml b/mods/official/zoom/Cargo.toml new file mode 100644 index 000000000..2225b00e8 --- /dev/null +++ b/mods/official/zoom/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "zoom" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official zoom: hold a key to zoom, the wheel changes it while held." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/zoom/horizon-mod.toml b/mods/official/zoom/horizon-mod.toml new file mode 100644 index 000000000..bd699d0b5 --- /dev/null +++ b/mods/official/zoom/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "zoom" +name = "Zoom" +version = "1.0.0" +description = "Hold a key to zoom in; the mouse wheel changes the zoom while you hold it. Horizon's own, formerly an extra." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["render", "input", "ui", "storage"] +experimental = ["render", "input", "ui"] diff --git a/mods/official/zoom/src/lib.rs b/mods/official/zoom/src/lib.rs new file mode 100644 index 000000000..f55f10235 --- /dev/null +++ b/mods/official/zoom/src/lib.rs @@ -0,0 +1,145 @@ +//! Horizon's official zoom, formerly the built-in extra: hold the key (Z +//! by default) to zoom in, and turn the mouse wheel while holding it to zoom +//! further in or out. Its settings page has the extra's four options. The +//! key is bound on the page and kept by the game (`horizon-mods.txt`); the +//! rest is kept in the mod's storage (`level`, `smooth`, `sensitivity`), +//! where the game writes a player's old extra settings when it installs the +//! mod for them. +use horizon_mod_sdk::{ + Mod, Registration, + input::{self, Event}, + render::{self, Zoom as ZoomView}, + storage, + ui::{self, ButtonWidget, KeyWidget, Widget}, +}; + +/// The key's name for `register-key` and the settings page. +const KEY: &str = "zoom"; +/// The zooms the starting zoom cycles through, and the wheel's limits. +const LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10]; +const MIN: f32 = 1.25; +const MAX: f32 = 10.0; +/// Each wheel step multiplies the zoom by this. +const STEP: f32 = 1.25; +/// Settings page widgets. +const KEY_WIDGET: u32 = 1; +const LEVEL_BUTTON: u32 = 2; +const SMOOTH_BUTTON: u32 = 3; +const SENSITIVITY_BUTTON: u32 = 4; + +struct Zoom { + /// The zoom the key starts at, one of `LEVELS`. + level: u8, + /// Ease in and out like the spyglass. + smooth: bool, + /// Turn slower the more you zoom in. + sensitivity: bool, + /// The zoom while the key is held; None when it is up. + held: Option, +} + +impl Zoom { + /// Tells the game the zoom in effect. + fn show(&self) { + let factor = self.held.unwrap_or(1.0); + render::set_zoom(ZoomView { + factor, + smooth: self.smooth, + turn: if self.sensitivity { 1.0 / factor } else { 1.0 }, + }); + } + fn page(&self) { + let on = |b: bool| if b { "ON" } else { "OFF" }; + ui::set_settings(&[ + Widget::Key(KeyWidget { + id: KEY_WIDGET, + key: KEY.into(), + }), + Widget::Button(ButtonWidget { + id: LEVEL_BUTTON, + label: format!("Starting zoom: {}x", self.level), + }), + Widget::Button(ButtonWidget { + id: SMOOTH_BUTTON, + label: format!("Smooth zoom: {}", on(self.smooth)), + }), + Widget::Button(ButtonWidget { + id: SENSITIVITY_BUTTON, + label: format!("Slower turning: {}", on(self.sensitivity)), + }), + ]); + } + fn save(&self) { + let flag = |b: bool| if b { &b"true"[..] } else { &b"false"[..] }; + let _ = storage::set("level", self.level.to_string().as_bytes()); + let _ = storage::set("smooth", flag(self.smooth)); + let _ = storage::set("sensitivity", flag(self.sensitivity)); + } +} + +fn stored(key: &str) -> Option { + storage::get(key).and_then(|v| String::from_utf8(v).ok()) +} + +impl Mod for Zoom { + fn init() -> Result<(Self, Registration), String> { + input::register_key(KEY, "Zoom", "key.keyboard.z")?; + // The extra's defaults: 4x, smooth, slower turning. + let level = stored("level") + .and_then(|v| v.trim().parse::().ok()) + .map_or(4, |v| v.clamp(2, MAX as u8)); + let flag = |key: &str| stored(key).is_none_or(|v| v.trim() != "false"); + let zoom = Zoom { + level, + smooth: flag("smooth"), + sensitivity: flag("sensitivity"), + held: None, + }; + zoom.page(); + Ok((zoom, Registration::new().on_frame())) + } + fn frame(&mut self, _seconds: f32) { + let mut changed = false; + for event in input::poll() { + match event { + Event::KeyDown(k) if k == KEY => { + self.held = Some(f32::from(self.level).clamp(MIN, MAX)); + // While held, the wheel zooms instead of moving the hotbar. + input::claim_wheel(true); + } + Event::KeyUp(k) if k == KEY => { + self.held = None; + input::claim_wheel(false); + } + Event::Wheel(steps) => { + let Some(z) = &mut self.held else { continue }; + *z = (*z * STEP.powf(steps)).clamp(MIN, MAX); + } + _ => continue, + } + changed = true; + } + if changed { + self.show(); + } + } + fn ui_select(&mut self, id: u32, _row: u32) { + match id { + LEVEL_BUTTON => { + // As the extra cycled: an unknown level counts as the first. + let i = LEVELS.iter().position(|&l| l == self.level).unwrap_or(0); + self.level = LEVELS[(i + 1) % LEVELS.len()]; + } + SMOOTH_BUTTON => self.smooth = !self.smooth, + SENSITIVITY_BUTTON => self.sensitivity = !self.sensitivity, + _ => return, + } + self.save(); + self.page(); + } + fn ui_settings_opened(&mut self) { + self.page(); + } +} + +horizon_mod_sdk::export_mod!(Zoom); From 3e3c0cebb51fa5deb0022ff1c0ca8fa4ba9fc42d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:34:49 +0100 Subject: [PATCH 5/6] Mod keys: rows the game adds to the settings page, not a WIT widget A new case in ui's widget variant stops every ui mod built before it from loading: the runtime links a component only when each imported function's types match exactly ("expected variant of 5 cases, found 4"), so the published FPS Counter and Keystrokes would break. Instead, the game lists a mod's keys first on its page in Options > Mods, as Key Binds rows, and a mod with keys gets a page even without ui. No WIT type changes. docs/api/stability.md said a new case the mod sends isn't breaking; it is, and now says so. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/mods.rs | 113 ++++++++++-------- crates/horizon-mod-sdk/wit/horizon.wit | 17 +-- crates/horizon-mods/src/runtime.rs | 17 ++- crates/horizon-mods/tests/sandbox.rs | 8 +- crates/horizon-mods/tests/ui_guest/src/lib.rs | 11 +- docs/api/mods-reference.md | 12 +- docs/api/stability.md | 9 +- docs/mods.md | 4 +- 8 files changed, 86 insertions(+), 105 deletions(-) diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 66d00b233..e55a87d46 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -27,7 +27,7 @@ use { text::{self, Text}, ui, }, - horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, + horizon_mods::{Clock, ModKey, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget}, std::time::Instant, winit::{event::MouseButton, keyboard::KeyCode}, }; @@ -102,7 +102,7 @@ struct ModScreen { under: Screen, /// One scroll per `list` widget, in widget order. scrolls: Vec, - /// A key widget waiting for the key to bind: the mod key's name. + /// A key row waiting for the key to bind: the mod key's name. binding: Option, } impl ModsState { @@ -575,7 +575,7 @@ impl Game<'_> { fn mod_ui_view<'a>(mods: &'a Mods, ms: &ModScreen) -> Option<(&'a str, &'a [UiWidget])> { if ms.settings { let widgets = mods.settings_widgets(ms.owner); - if widgets.is_empty() { + if widgets.is_empty() && mods.keys_of(ms.owner).is_empty() { return None; } let name = mods @@ -589,24 +589,25 @@ impl Game<'_> { Some((s.title.as_str(), s.widgets.as_slice())) } } - /// A key widget's label as Key Binds shows one, "Zoom: Z", marked + /// The keys a settings page lists first: the mod's own (`input`). + fn mod_page_keys<'a>(mods: &'a Mods, ms: &ModScreen) -> &'a [ModKey] { + if ms.settings { + mods.keys_of(ms.owner) + } else { + &[] + } + } + /// A key row's label as Key Binds shows one, "Zoom: Z", marked /// "> Zoom: Z <" in yellow while it waits for the new key. - fn mod_key_label(mods: &Mods, owner: usize, name: &str, waiting: bool) -> Text { - let (label, key) = mods - .keys_of(owner) - .iter() - .find(|k| k.name == name) - .map_or((name, "key.keyboard.unknown"), |k| { - (k.label.as_str(), k.key.as_str()) - }); - let value = format!("{label}: {}", keybinds::display_name(key).plain()); + fn mod_key_label(k: &ModKey, waiting: bool) -> Text { + let value = format!("{}: {}", k.label, keybinds::display_name(&k.key).plain()); if waiting { Text::literal(format!("> {value} <")).with_color(text::YELLOW) } else { Text::literal(value) } } - /// The player bound the key widget that waited to `key`: the mod's key + /// The player bound the key row that waited to `key`: the mod's key /// follows it now and at the next start (`horizon-mods.txt`). fn bind_mod_key(&mut self, key: String) { let Some(ms) = self.mods.screen.as_mut() else { @@ -637,7 +638,7 @@ impl Game<'_> { .insert(name, key); self.settings.save(&Self::options_path()); } - /// A key while a mod screen is up: true when a key widget waited for + /// A key while a mod screen is up: true when a key row waited for /// it (Key Binds: Escape binds none). pub(super) fn mod_screen_key(&mut self, key: KeyCode) -> bool { if self @@ -657,13 +658,13 @@ impl Game<'_> { } /// The layout the mod screen's widgets get at `h`: (widget, top, /// height), the column being `COLUMN` wide down the middle. - fn mod_ui_layout(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { + fn mod_ui_layout(h: f32, top: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> { let mut out = Vec::with_capacity(widgets.len()); - let mut y = MOD_UI_TOP; + let mut y = top; for w in widgets { let wh = match w { UiWidget::Text(_) => 12.0, - UiWidget::Item(_) | UiWidget::Button(_) | UiWidget::Key(_) => 20.0, + UiWidget::Item(_) | UiWidget::Button(_) => 20.0, UiWidget::List(l) => (l.rows.len().min(6) as f32 * 12.0) + 8.0, }; // Nothing may cover Done; a crowded mod loses what won't fit. @@ -683,7 +684,8 @@ impl Game<'_> { } if settings { self.mods.mods.ui_settings_opened(owner); - if self.mods.mods.settings_widgets(owner).is_empty() { + let keys = self.mods.mods.keys_of(owner); + if self.mods.mods.settings_widgets(owner).is_empty() && keys.is_empty() { self.show_mod_output(); return; } @@ -755,7 +757,27 @@ impl Game<'_> { ); let cx = (batch.width / 2.0).floor(); let x = cx - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(batch.height, widgets); + // A settings page starts with the mod's keys, as Key Binds rows. + let keys = Self::mod_page_keys(&self.mods.mods, ms); + for (i, k) in keys.iter().enumerate() { + let wy = MOD_UI_TOP + i as f32 * MOD_UI_KEY_ROW; + let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); + let waiting = ms.binding.as_deref() == Some(k.name.as_str()); + let label = Self::mod_key_label(k, waiting); + ui::button( + batch, + atlas, + x, + wy, + MOD_UI_COLUMN, + 20.0, + &label, + true, + hover, + ); + } + let top = MOD_UI_TOP + keys.len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(batch.height, top, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { match w { @@ -774,22 +796,6 @@ impl Game<'_> { hover, ); } - UiWidget::Key(k) => { - let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0); - let waiting = ms.binding.as_deref() == Some(k.key.as_str()); - let label = Self::mod_key_label(&self.mods.mods, ms.owner, &k.key, waiting); - ui::button( - batch, - atlas, - x, - wy, - MOD_UI_COLUMN, - 20.0, - &label, - true, - hover, - ); - } UiWidget::Text(t) => { let color = if t.color == 0 { u32::MAX @@ -920,7 +926,22 @@ impl Game<'_> { }; let owner = ms.owner; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(h, widgets); + // A key row waits for the key to bind. + let keys = Self::mod_page_keys(&self.mods.mods, ms); + let picked = (0..keys.len()).find(|&i| { + let wy = MOD_UI_TOP + i as f32 * MOD_UI_KEY_ROW; + ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) + }); + if let Some(i) = picked { + let name = keys[i].name.clone(); + self.audio.play_button_click(); + if let Some(ms) = self.mods.screen.as_mut() { + ms.binding = Some(name); + } + return; + } + let top = MOD_UI_TOP + keys.len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(h, top, widgets); let mut list_i = 0usize; // The `ui_select` call needs `&mut`: find the pick first. let mut hit = None; @@ -935,17 +956,6 @@ impl Game<'_> { self.show_mod_output(); return; } - // A key widget waits for the key to bind. - if let UiWidget::Key(k) = w - && ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0) - { - self.audio.play_button_click(); - let name = k.key.clone(); - if let Some(ms) = self.mods.screen.as_mut() { - ms.binding = Some(name); - } - return; - } let UiWidget::List(l) = w else { continue }; let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default(); list_i += 1; @@ -975,7 +985,9 @@ impl Game<'_> { return; }; let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0; - let layout = Self::mod_ui_layout(h, widgets); + let top = + MOD_UI_TOP + Self::mod_page_keys(&self.mods.mods, ms).len() as f32 * MOD_UI_KEY_ROW; + let layout = Self::mod_ui_layout(h, top, widgets); let mut list_i = 0usize; for (w, &(wy, wh)) in widgets.iter().zip(&layout) { let UiWidget::List(l) = w else { continue }; @@ -995,3 +1007,6 @@ impl Game<'_> { const MOD_UI_TOP: f32 = 40.0; #[cfg(feature = "mods")] const MOD_UI_COLUMN: f32 = 200.0; +/// A key row's height with its gap, as the widgets below it space out. +#[cfg(feature = "mods")] +const MOD_UI_KEY_ROW: f32 = 26.0; diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index f9c147cfa..9088c0c39 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -137,16 +137,6 @@ interface ui { /// Up to 256 characters. label: string, } - /// One of the mod's keys (`input.register-key`) as Controls shows a - /// binding, "Zoom: Z". A click waits for the next key or mouse button, - /// which becomes the key (Esc: none). The game keeps the player's - /// choice across starts; the mod's `key-down` and `key-up` follow it. - record key-widget { - /// The mod's own name for the widget. - id: u32, - /// The name the mod registered the key under. - key: string, - } variant widget { /// Text the player reads. text(text-widget), @@ -156,8 +146,6 @@ interface ui { item(item-widget), /// Rows the player picks from. %list(list-widget), - /// A key the player binds. - key(key-widget), } /// A screen the mod owns: a title over widgets stacked down the middle, /// the Done button the game adds, and Esc to leave it. @@ -232,8 +220,9 @@ interface input { claim-items: func(ids: list); /// A key of the mod's: `name` comes back in `key-down` and `key-up`, /// `label` says what it does, `key` is the key as options.txt writes - /// it (`key.keyboard.r`), the default: a key the player chose for it - /// (`ui`'s key widget) wins. At most 16; an unknown key is an error. + /// it (`key.keyboard.r`), the default: the player can bind another + /// one on the mod's page in Options > Mods, and that one wins. At most + /// 16; an unknown key is an error. register-key: func(name: string, label: string, key: string) -> result<_, string>; /// The main hand's stack, as of this tick; none when it is empty. held: func() -> option; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index f596db81c..0011fa99d 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -37,8 +37,7 @@ use bindings::{ /// The widget model a `ui` screen or settings page shows (WIT `interface /// ui`), for the game to draw with its menus' own widgets. pub use ui_bindings::horizon::mods::ui::{ - ButtonWidget, ItemWidget, KeyWidget, ListWidget, Screen as UiScreen, TextWidget, - Widget as UiWidget, + ButtonWidget, ItemWidget, ListWidget, Screen as UiScreen, TextWidget, Widget as UiWidget, }; use ui_bindings::{UiHost, horizon::mods::ui}; /// Capability `render`'s imports (docs/mods.md): the game draws the shapes. @@ -153,11 +152,13 @@ pub struct Entry { } impl Entry { /// The running mod has a settings page (capability `ui` set widgets - /// with `ui.set-settings`): its row in Options > Mods gains a button. + /// with `ui.set-settings`, or `input` registered keys the player may + /// bind there): its row in Options > Mods gains a button. pub fn has_ui_settings(&self) -> bool { - self.run - .as_ref() - .is_some_and(|r| !r.store.data().ui.settings.is_empty()) + self.run.as_ref().is_some_and(|r| { + let d = r.store.data(); + !d.ui.settings.is_empty() || !d.input.keys.is_empty() + }) } } @@ -856,10 +857,6 @@ fn clip_widgets(widgets: Vec) -> Vec { l.selected = l.selected.filter(|&s| (s as usize) < l.rows.len()); UiWidget::List(l) } - UiWidget::Key(mut k) => { - k.key = clip(k.key); - UiWidget::Key(k) - } }) .collect() } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 793d03db6..3b33ab4b2 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -449,7 +449,7 @@ fn ui_screens_settings_and_events() { assert_eq!(mods.settings_widgets(0).len(), 3); assert!(mods.entries()[0].has_ui_settings()); mods.ui_settings_opened(0); - assert_eq!(mods.settings_widgets(0).len(), 3); + assert_eq!(mods.settings_widgets(0).len(), 2); // `/ui_close` closes the mod's own screen. assert!(mods.command("ui_close")); assert!(mods.drain().contains(&Output::CloseScreen { owner: 0 })); @@ -566,10 +566,8 @@ fn the_players_key_choice_wins() { }; let mut mods = load("horizon_mods_test_ui_guest.hmod"); assert!(mods.command("input_claim")); - assert!(matches!( - &mods.settings_widgets(0)[0], - horizon_mods::UiWidget::Key(k) if k.id == 9 && k.key == "wheel" - )); + // Its keys alone give it a page in Options > Mods, where the game lists them. + assert!(mods.settings_widgets(0).is_empty() && mods.entries()[0].has_ui_settings()); // Rebinding while held lets the old key go. mods.key("key.keyboard.r", true); assert!(mods.rebind(0, "wheel", "key.mouse.4")); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index f2765e8da..9bede11f9 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -9,7 +9,7 @@ use horizon_mod_sdk::{ Mod, Registration, chat, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, - ui::{self, ItemWidget, KeyWidget, ListWidget, Screen, TextWidget, Widget}, + ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, }; /// One of each shape, the text too long by 44 characters. @@ -162,10 +162,6 @@ impl Mod for Guest { // Not a key: refused. let bad = input::register_key("bad", "Bad", "R").unwrap_err(); chat::show(&format!("claimed; {bad}")); - ui::set_settings(&[Widget::Key(KeyWidget { - id: 9, - key: "wheel".into(), - })]); } "input_poll" => { for event in input::poll() { @@ -229,11 +225,6 @@ impl Mod for Guest { id: 3, label: "Corner: Top Right".into(), }), - // `/input_claim`'s key; drawn as its name until registered. - Widget::Key(KeyWidget { - id: 9, - key: "wheel".into(), - }), ]); chat::show("settings opened"); } diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index f525ace89..a51fb904b 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -197,15 +197,6 @@ A thing on a mod's screen or settings page. A button as the options pages have t | `id` | `u32` | The mod's own name for the widget. | | `label` | `string` | Up to 256 characters. | -### record `key-widget` - -One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: Z". A click waits for the next key or mouse button, which becomes the key (Esc: none). The game keeps the player's choice across starts; the mod's `key-down` and `key-up` follow it. - -| Field | Type | | -| --- | --- | --- | -| `id` | `u32` | The mod's own name for the widget. | -| `key` | `string` | The name the mod registered the key under. | - ### variant `widget` | Case | Payload | | @@ -214,7 +205,6 @@ One of the mod's keys (`input.register-key`) as Controls shows a binding, "Zoom: | `button` | `button-widget` | A button. | | `item` | `item-widget` | An item's icon and name. | | `list` | `list-widget` | Rows the player picks from. | -| `key` | `key-widget` | A key the player binds. | ### record `screen` @@ -288,7 +278,7 @@ A mapping as the player has bound it. | Function | Signature | What it does | | --- | --- | --- | | `claim-items` | `func(ids: list)` | The items whose use the mod handles instead of the game, by id (at most 64). Replaces the previous list. | -| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: a key the player chose for it (`ui`'s key widget) wins. At most 16; an unknown key is an error. | +| `register-key` | `func(name: string, label: string, key: string) -> result<_, string>` | A key of the mod's: `name` comes back in `key-down` and `key-up`, `label` says what it does, `key` is the key as options.txt writes it (`key.keyboard.r`), the default: the player can bind another one on the mod's page in Options > Mods, and that one wins. At most 16; an unknown key is an error. | | `held` | `func() -> option` | The main hand's stack, as of this tick; none when it is empty. | | `poll` | `func() -> list` | The events since the last call, oldest first. | | `claim-wheel` | `func(on: bool)` | Takes the mouse wheel while playing (true) or gives it back: while taken, its steps are the mod's `wheel` events and the hotbar doesn't move. The game gives it back when the mod stops. | diff --git a/docs/api/stability.md b/docs/api/stability.md index 132c971f9..d5bd0e545 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -26,12 +26,13 @@ promise, how something is deprecated and removed, and the tests that keep old mo ## What counts as a breaking change Breaking: removing or renaming anything; changing a type, a default, a unit or a meaning; making something optional -required; refusing input that was accepted; a new case in a WIT `enum` or `variant` the game sends to mods (an older -component cannot decode it); a JSON field that changes type. +required; refusing input that was accepted; any change to a WIT type a function uses, a new `enum` or `variant` case +included, in either direction (the runtime links a component only when each imported function's types match exactly: +a mod built before the change no longer loads); a JSON field that changes type. Not breaking: a new function, interface, capability, command, endpoint, tool or `server.toml` key; a new optional -argument or JSON field (readers must ignore fields they don't know); a new WIT case the mod *sends* (the game decodes -every case it ever served); faster, or fixing behaviour to what the reference already says. +argument or JSON field (readers must ignore fields they don't know); a new WIT function or type (mods built earlier +don't import it); faster, or fixing behaviour to what the reference already says. ## Stability levels diff --git a/docs/mods.md b/docs/mods.md index 108e854be..a8d8da851 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,9 +87,9 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | -| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item, list and key widgets the game lays out and draws with its own menus' code. A key widget binds one of the mod's keys (`input.register-key`) as Key Binds does: click, then press the key or mouse button (Esc: none); the game keeps the choice in `horizon-mods.txt` (`key..:key.keyboard.z`) and the mod's `key-down` follows it. **Experimental:** the manifest needs `experimental = ["ui"]` | +| `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | -| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | +| `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | | Hook (export) | When | |---|---| From 8fdb27f9493ff31a664f3c6683e5ce8c57dd7084 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 05:35:16 +0100 Subject: [PATCH 6/6] Zoom: the game lists its key on the settings page, as "Zoom key: Z" Co-Authored-By: Claude Opus 5.5 --- mods/official/zoom/src/lib.rs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/mods/official/zoom/src/lib.rs b/mods/official/zoom/src/lib.rs index f55f10235..072a40eb0 100644 --- a/mods/official/zoom/src/lib.rs +++ b/mods/official/zoom/src/lib.rs @@ -1,8 +1,9 @@ //! Horizon's official zoom, formerly the built-in extra: hold the key (Z //! by default) to zoom in, and turn the mouse wheel while holding it to zoom -//! further in or out. Its settings page has the extra's four options. The -//! key is bound on the page and kept by the game (`horizon-mods.txt`); the -//! rest is kept in the mod's storage (`level`, `smooth`, `sensitivity`), +//! further in or out. Its settings page has the extra's four options: the +//! game lists the key there first and keeps the player's choice +//! (`horizon-mods.txt`); the rest is kept in the mod's storage (`level`, +//! `smooth`, `sensitivity`), //! where the game writes a player's old extra settings when it installs the //! mod for them. use horizon_mod_sdk::{ @@ -10,10 +11,10 @@ use horizon_mod_sdk::{ input::{self, Event}, render::{self, Zoom as ZoomView}, storage, - ui::{self, ButtonWidget, KeyWidget, Widget}, + ui::{self, ButtonWidget, Widget}, }; -/// The key's name for `register-key` and the settings page. +/// The key's name for `register-key`. const KEY: &str = "zoom"; /// The zooms the starting zoom cycles through, and the wheel's limits. const LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10]; @@ -21,8 +22,7 @@ const MIN: f32 = 1.25; const MAX: f32 = 10.0; /// Each wheel step multiplies the zoom by this. const STEP: f32 = 1.25; -/// Settings page widgets. -const KEY_WIDGET: u32 = 1; +/// Settings page buttons, under the key's row. const LEVEL_BUTTON: u32 = 2; const SMOOTH_BUTTON: u32 = 3; const SENSITIVITY_BUTTON: u32 = 4; @@ -51,10 +51,6 @@ impl Zoom { fn page(&self) { let on = |b: bool| if b { "ON" } else { "OFF" }; ui::set_settings(&[ - Widget::Key(KeyWidget { - id: KEY_WIDGET, - key: KEY.into(), - }), Widget::Button(ButtonWidget { id: LEVEL_BUTTON, label: format!("Starting zoom: {}x", self.level), @@ -83,7 +79,7 @@ fn stored(key: &str) -> Option { impl Mod for Zoom { fn init() -> Result<(Self, Registration), String> { - input::register_key(KEY, "Zoom", "key.keyboard.z")?; + input::register_key(KEY, "Zoom key", "key.keyboard.z")?; // The extra's defaults: 4x, smooth, slower turning. let level = stored("level") .and_then(|v| v.trim().parse::().ok())