Merge pull request #2013 from ludovic111/feat/mod-api-zoom

🤖 Agent: Mod API (experimental): render.set-zoom and input.claim-wheel, held mod keys let go when a screen opens, mod keys on mouse buttons. The consume choice is in stability.md. Verified: pr_ready (1300 tests), sandbox tests, in game 22/22 in-frame and on the server thread.
This commit is contained in:
Ludovic Marie
2026-10-26 05:12:07 +01:00
committed by GitHub
12 changed files with 282 additions and 24 deletions
+2
View File
@@ -11288,6 +11288,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
@@ -11463,6 +11464,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 => {
+22 -9
View File
@@ -229,25 +229,38 @@ 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.
+60 -2
View File
@@ -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<ModZoom> {
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<ModZoom> {
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,
})
}
}
+4
View File
@@ -63,6 +63,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
@@ -434,6 +437,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);
+24 -1
View File
@@ -207,9 +207,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.
@@ -222,6 +226,10 @@ interface input {
held: func() -> option<held-item>;
/// The events since the last call, oldest first.
poll: func() -> list<event>;
/// 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`.
@@ -339,6 +347,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.
+2 -2
View File
@@ -137,9 +137,9 @@ impl Capability {
Capability::Command => "run commands as you, with your permissions",
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"
}
}
}
+67 -1
View File
@@ -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};
@@ -192,6 +192,8 @@ struct State {
shapes: Vec<Shape>,
/// Capability `render`'s corner panel.
corner: Option<CornerPanel>,
/// Capability `render`'s zoom, when the mod zooms.
zoom: Option<ModZoom>,
input: InputState,
/// Capability `storage`'s folder; made on first `set`.
data_dir: PathBuf,
@@ -334,6 +336,7 @@ impl Mods {
ui: UiState::default(),
shapes: Vec::new(),
corner: None,
zoom: None,
input: InputState::default(),
data_dir,
storage_budget: STORAGE_WRITE_BUDGET,
@@ -590,6 +593,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 {
@@ -598,6 +611,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<ModZoom> {
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<Item = &InputState> {
self.entries
.iter()
@@ -827,6 +869,10 @@ struct InputState {
claimed: Vec<String>,
keys: Vec<ModKey>,
events: std::collections::VecDeque<InputEvent>,
/// The mod's keys held now, by name.
down: Vec<String>,
/// It holds the mouse wheel.
wheel: bool,
}
/// Events kept for `poll`, items claimed and keys, per mod.
const INPUT_EVENTS: usize = 256;
@@ -892,12 +938,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.
@@ -966,6 +1019,19 @@ impl render::Host for State {
.sum::<f32>()
.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 }
+50
View File
@@ -543,6 +543,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<String> {
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]
+24 -2
View File
@@ -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<Option<String>, String> {
fn command(&mut self, name: &str, args: &str) -> Result<Option<String>, 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,24 @@ 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);