Merge feat/official-zoom-mod into feat/moved-zoom

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-26 05:55:10 +01:00
18 changed files with 762 additions and 55 deletions
Generated
+7
View File
@@ -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"
+1 -1
View File
@@ -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]
+6 -3
View File
@@ -10452,6 +10452,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(());
}
@@ -11110,6 +11113,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
@@ -11280,6 +11284,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 => {
@@ -11362,9 +11367,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),
_ => {}
}
}
+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 minimap and mods' corner panels, 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,
})
}
}
+146 -10
View File
@@ -27,8 +27,9 @@ 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},
};
#[derive(Default)]
@@ -66,6 +67,9 @@ pub(super) struct ModsState {
/// Extras that are official mods now, being installed.
#[cfg(feature = "mods")]
pub(super) moved: super::moved_extras::MovedState,
/// 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
@@ -101,6 +105,8 @@ struct ModScreen {
under: Screen,
/// One scroll per `list` widget, in widget order.
scrolls: Vec<ui::Scroll>,
/// A key row waiting for the key to bind: the mod key's name.
binding: Option<String>,
}
impl ModsState {
/// The chat's command tree: vanilla's, plus the running mods' commands.
@@ -240,7 +246,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 +272,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 +440,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));
@@ -437,6 +450,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);
@@ -564,7 +578,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
@@ -578,11 +592,78 @@ impl Game<'_> {
Some((s.title.as_str(), s.widgets.as_slice()))
}
}
/// 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(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 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 {
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 row 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)> {
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,
@@ -606,7 +687,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;
}
@@ -616,6 +698,7 @@ impl Game<'_> {
settings,
under: self.screen,
scrolls: Vec::new(),
binding: None,
});
self.screen = Screen::Mod;
if self.player.is_some() {
@@ -677,7 +760,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 {
@@ -797,7 +900,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) {
@@ -813,7 +929,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;
@@ -857,7 +988,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 };
@@ -877,3 +1010,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;
+46 -6
View File
@@ -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.<id>: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<String>,
/// The keys the player chose for mods' keys, mod id → key name → key
/// (`key.<id>.<name>:key.keyboard.x` lines).
pub keys: BTreeMap<String, BTreeMap<String, String>>,
/// What the Mods page shows, filled by the game from the mods it found.
pub installed: Vec<Installed>,
}
@@ -45,20 +52,41 @@ impl ModList {
.filter_map(|(k, _)| k.trim().strip_prefix("mod."))
.map(str::to_owned)
.collect();
let mut keys: BTreeMap<String, BTreeMap<String, String>> = 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 {
+27 -2
View File
@@ -207,21 +207,31 @@ 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.
claim-items: func(ids: list<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.
/// 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<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 +349,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"
}
}
}
+133 -5
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};
@@ -152,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()
})
}
}
@@ -192,6 +194,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 +338,7 @@ impl Mods {
ui: UiState::default(),
shapes: Vec::new(),
corner: None,
zoom: None,
input: InputState::default(),
data_dir,
storage_budget: STORAGE_WRITE_BUDGET,
@@ -561,6 +566,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) {
@@ -590,6 +637,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 +655,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 +913,13 @@ 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,
/// 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;
@@ -847,6 +940,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();
@@ -866,6 +970,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(());
@@ -892,12 +1000,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 +1081,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 }
+87
View File
@@ -543,6 +543,93 @@ 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 the_players_key_choice_wins() {
let chat = |mods: &mut Mods| -> Vec<String> {
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"));
// 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"));
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");
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);
+15 -4
View File
@@ -14,8 +14,8 @@ The contract between Horizon and its mods: the WIT package `horizon:mods@0.1.0`,
| `command` | [`command`](#command) | run commands as you, with your permissions |
| `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`
@@ -262,8 +262,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`
@@ -277,9 +278,10 @@ A mapping as the player has bound it.
| Function | Signature | What it does |
| --- | --- | --- |
| `claim-items` | `func(ids: list<string>)` | 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: 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<held-item>` | The main hand's stack, as of this tick; none when it is empty. |
| `poll` | `func() -> list<event>` | 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<mapping-state>` | 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<u32, u32>` | Clicks of the attack and use buttons in the last second. |
@@ -380,6 +382,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<shape>)` | 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. |
@@ -389,6 +399,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`
+16 -6
View File
@@ -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
@@ -88,8 +89,8 @@ Deprecations and breaking changes are in bold. The release notes of the game rel
| --- | --- | --- |
| Mod API: `log`, `game`, `chat`, `hud`, `storage`, `command`, `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 +105,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.
+4 -3
View File
@@ -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 |
@@ -89,8 +89,8 @@ folder, loads no runtime and plays exactly like vanilla 26.3.
| `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"]` |
| `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`. 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.<mod>.<name>: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 |
|---|---|
@@ -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
+16
View File
@@ -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
+9
View File
@@ -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"]
+141
View File
@@ -0,0 +1,141 @@
//! 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
//! 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::{
Mod, Registration,
input::{self, Event},
render::{self, Zoom as ZoomView},
storage,
ui::{self, ButtonWidget, Widget},
};
/// 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];
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 buttons, under the key's row.
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<f32>,
}
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::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<String> {
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", "key.keyboard.z")?;
// The extra's defaults: 4x, smooth, slower turning.
let level = stored("level")
.and_then(|v| v.trim().parse::<u8>().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);