diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index ea5859c23..63acb45e3 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -21,7 +21,7 @@ horizon-shaders = { path = "../horizon-shaders" } horizon-friends = { path = "../horizon-friends" } # Horizon mods: sandboxed WebAssembly components, off unless installed and turned on (docs/mods.md). # Their runtime is the `mods` feature. -horizon-mods = { path = "../horizon-mods", default-features = false } +horizon-mods = { path = "../horizon-mods", default-features = false, features = ["index"] } wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl", "naga-ir"] } winit = "0.30.13" pollster = "0.4" diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 40e87214e..c8683bb92 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -81,6 +81,9 @@ pub struct Extras { pub zoom_smooth: bool, /// Divide mouse turning by the zoom. pub zoom_sensitivity: bool, + /// The FPS counter and keystrokes extras are official mods now + /// (`moved_extras`): their old settings stay here until the game has + /// installed the mod for a player who had one on. pub fps: bool, pub fps_corner: Corner, /// Also show the minimum and 1% low. @@ -89,6 +92,9 @@ pub struct Extras { pub keystrokes_corner: Corner, /// Clicks per second under the mouse buttons. pub keystrokes_cps: bool, + /// The official mods installed for the extras they replace, by mod id + /// (`movedToMods`): each is done once. + pub moved: Vec, pub minimap: bool, pub minimap_corner: Corner, /// Side in GUI pixels (`MINIMAP_SIZES`). @@ -132,6 +138,7 @@ impl Default for Extras { keystrokes: false, keystrokes_corner: Corner::TopLeft, keystrokes_cps: true, + moved: Vec::new(), minimap: false, minimap_corner: Corner::TopRight, minimap_size: 96, @@ -190,6 +197,14 @@ impl Extras { e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner) } "keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps), + "movedToMods" => { + e.moved = value + .split(',') + .map(str::trim) + .filter(|id| !id.is_empty()) + .map(str::to_owned) + .collect() + } "minimap" => e.minimap = flag(e.minimap), "minimapCorner" => e.minimap_corner = Corner::parse(value, e.minimap_corner), "minimapSize" => { @@ -219,7 +234,7 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n", + "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nmovedToMods:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n", bool_text(self.fullbright), bool_text(self.dynamic_lights), bool_text(self.zoom), @@ -233,6 +248,7 @@ impl Extras { bool_text(self.keystrokes), self.keystrokes_corner.name(), bool_text(self.keystrokes_cps), + self.moved.join(","), bool_text(self.minimap), self.minimap_corner.name(), self.minimap_size, @@ -452,12 +468,6 @@ pub enum Item { ZoomLevel, ZoomSmooth, ZoomSensitivity, - Fps, - FpsCorner, - FpsLows, - Keystrokes, - KeystrokesCorner, - KeystrokesCps, Minimap, MinimapCorner, MinimapSize, @@ -495,14 +505,6 @@ pub fn rows() -> Vec> { Ok(MinimapShape), Ok(MinimapZoom), Ok(MinimapRotate), - Err("FPS counter"), - Ok(Fps), - Ok(FpsCorner), - Ok(FpsLows), - Err("Keystrokes"), - Ok(Keystrokes), - Ok(KeystrokesCorner), - Ok(KeystrokesCps), Err("Inventory"), Ok(MouseTweaks), Ok(MouseTweaksWheel), @@ -537,8 +539,7 @@ impl Item { Item::ZoomLevel => "Starting zoom", Item::ZoomSmooth => "Smooth zoom", Item::ZoomSensitivity => "Slower turning", - Item::Fps => "FPS counter", - Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner", + Item::MinimapCorner => "Corner", Item::Minimap => "Minimap", Item::MinimapSize => "Size", Item::MinimapShape => "Shape", @@ -549,9 +550,6 @@ impl Item { Item::MouseTweaksWheel => "Scroll wheel moves items", Item::Sort => "Sort buttons", Item::SortKey => "Sort key", - Item::FpsLows => "Minimum and 1% low", - Item::Keystrokes => "Keystrokes", - Item::KeystrokesCps => "Clicks per second", Item::NoAi => "No AI", Item::AgentControl => "Agent Control", Item::DiscordPresence => "Discord Rich Presence", @@ -563,12 +561,10 @@ impl Item { Some(match self { ZoomKey | ZoomLevel | ZoomSmooth | ZoomSensitivity => Zoom, MinimapCorner | MinimapSize | MinimapShape | MinimapZoom | MinimapRotate => Minimap, - FpsCorner | FpsLows => Fps, - KeystrokesCorner | KeystrokesCps => Keystrokes, MouseTweaksWheel => MouseTweaks, SortKey => Sort, - Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort - | AutoReconnect | NoAi | AgentControl | DiscordPresence => { + Fullbright | DynamicLights | Zoom | Minimap | MouseTweaks | Sort | AutoReconnect + | NoAi | AgentControl | DiscordPresence => { return None; } }) @@ -585,10 +581,7 @@ impl Item { Item::ZoomLevel => "The zoom the key starts at.", Item::ZoomSmooth => "Eases in and out like the spyglass.", Item::ZoomSensitivity => "Turns slower the more you zoom in.", - Item::Fps => "Frames per second in a corner of the screen.", - Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => { - "Overlays in one corner stack." - } + Item::MinimapCorner => "Overlays in one corner stack.", Item::Minimap => "A map of the loaded terrain around you, in map colours.", Item::MinimapSize => "How big the map is on screen.", Item::MinimapShape => "Square or round.", @@ -597,7 +590,6 @@ impl Item { Item::AutoReconnect => { "Rejoins a server after a lost connection or a restart, never after a kick or ban." } - Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.", Item::MouseTweaks => { "Right-drag places one per slot, left-drag gathers the held item, Shift + left-drag moves every slot." } @@ -610,8 +602,6 @@ impl Item { Item::SortKey => { "Sorts the part under the cursor. Click, then press a key; Escape unbinds it." } - Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.", - Item::KeystrokesCps => "Clicks in the last second under each mouse button.", Item::NoAi => { "Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too." } @@ -627,7 +617,7 @@ impl Item { pub fn cost(self) -> Option { use crate::graphics_style::Cost; match self { - Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), + Item::Fullbright | Item::Zoom => Some(Cost::None), Item::Minimap | Item::DynamicLights => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, @@ -641,10 +631,6 @@ impl Item { Item::Zoom => e.zoom, Item::ZoomSmooth => e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity, - Item::Fps => e.fps, - Item::FpsLows => e.fps_lows, - Item::Keystrokes => e.keystrokes, - Item::KeystrokesCps => e.keystrokes_cps, Item::Minimap => e.minimap, Item::MinimapRotate => e.minimap_rotate, Item::AutoReconnect => e.auto_reconnect, @@ -663,8 +649,6 @@ impl Item { Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(), Item::SortKey => crate::keybinds::display_name(&e.sort_key).plain(), Item::ZoomLevel => format!("{}x", e.zoom_level), - Item::FpsCorner => e.fps_corner.label().into(), - Item::KeystrokesCorner => e.keystrokes_corner.label().into(), Item::MinimapCorner => e.minimap_corner.label().into(), Item::MinimapSize => MINIMAP_SIZES .iter() @@ -687,15 +671,7 @@ impl Item { Item::Zoom => e.zoom = !e.zoom, Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, - Item::Fps => e.fps = !e.fps, - Item::FpsLows => e.fps_lows = !e.fps_lows, - Item::Keystrokes => e.keystrokes = !e.keystrokes, - Item::KeystrokesCps => e.keystrokes_cps = !e.keystrokes_cps, Item::ZoomLevel => e.zoom_level = next(&ZOOM_LEVELS, e.zoom_level, back), - Item::FpsCorner => e.fps_corner = next(&Corner::ALL, e.fps_corner, back), - Item::KeystrokesCorner => { - e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back) - } Item::Minimap => e.minimap = !e.minimap, Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate, Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect, @@ -750,6 +726,7 @@ mod tests { e.fps_corner = Corner::BottomRight; e.keystrokes = true; e.keystrokes_cps = false; + e.moved = vec!["fps_overlay".into(), "keystrokes".into()]; e.minimap = true; e.minimap_size = 128; e.minimap_round = true; @@ -942,8 +919,8 @@ mod tests { Item::ZoomLevel.cycle(&mut e, true); Item::ZoomLevel.cycle(&mut e, true); assert_eq!(e.zoom_level, 3); - Item::FpsCorner.cycle(&mut e, true); - assert_eq!(e.fps_corner, Corner::BottomRight); + Item::MinimapCorner.cycle(&mut e, true); + assert_eq!(e.minimap_corner, Corner::TopLeft); Item::Zoom.cycle(&mut e, false); assert_eq!(Item::Zoom.switch(&e), Some(true)); assert_eq!(Item::ZoomKey.value(&e), "Z"); diff --git a/crates/horizon-client/src/extras_hud.rs b/crates/horizon-client/src/extras_hud.rs index f6fc1ba12..cc26e15d4 100644 --- a/crates/horizon-client/src/extras_hud.rs +++ b/crates/horizon-client/src/extras_hud.rs @@ -1,7 +1,7 @@ -//! The extras' HUD overlays (FPS counter, keystrokes): small boxes in the -//! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`). +//! HUD boxes in the corners: the minimap's place and mods' panels, small +//! boxes in GUI pixels stacked per corner (`docs/extras.md`). use crate::{ - extras::{Corner, FpsReading}, + extras::Corner, hud::{HudAtlas, HudBatch, Rect, rgba}, }; @@ -99,36 +99,6 @@ pub fn draw_minimap( } } -/// The FPS counter's text. -pub fn fps_text(r: FpsReading, lows: bool) -> String { - if lows { - format!("{} fps min {} 1% {}", r.fps, r.min, r.low) - } else { - format!("{} fps", r.fps) - } -} -pub fn draw_fps( - batch: &mut HudBatch, - atlas: &HudAtlas, - corners: &mut Corners, - corner: Corner, - reading: FpsReading, - lows: bool, -) { - let text = fps_text(reading, lows); - let w = HudBatch::text_width(atlas, &text) + 4.0; - let (x, y) = corners.place(corner, w, 12.0); - batch.fill(atlas, x, y, w, 12.0, BACKGROUND); - batch.text( - atlas, - &text, - x + 2.0, - y + 2.0, - rgba(255, 255, 255, 255), - true, - ); -} - /// A box of text lines (a mod's HUD panel): `(text, 0xRRGGBB)` each. pub fn draw_lines( batch: &mut HudBatch, @@ -155,95 +125,6 @@ pub fn draw_lines( } } -/// What the keystroke overlay shows. -pub struct Keystrokes { - /// Forward, left, back, right: held, and the bound key's name. - pub moves: [(bool, String); 4], - pub jump: bool, - pub attack: bool, - pub use_: bool, - /// Clicks per second of the left and right buttons, when shown. - pub cps: Option<(usize, usize)>, -} -const KEY: f32 = 22.0; -const GAP: f32 = 2.0; -/// The overlay's size. -pub fn keystrokes_size() -> (f32, f32) { - (3.0 * KEY + 2.0 * GAP, 3.0 * KEY + 3.0 * GAP + 10.0) -} -fn key_box(batch: &mut HudBatch, atlas: &HudAtlas, rect: [f32; 4], held: bool, lines: &[&str]) { - let [x, y, w, h] = rect; - let (fill, ink) = if held { - (rgba(255, 255, 255, 176), rgba(20, 20, 20, 255)) - } else { - (BACKGROUND, rgba(255, 255, 255, 255)) - }; - batch.fill(atlas, x, y, w, h, fill); - let total = lines.len() as f32 * 9.0 - 1.0; - for (i, line) in lines.iter().enumerate() { - let tw = HudBatch::text_width(atlas, line); - let tx = (x + (w - tw) / 2.0).round(); - let ty = (y + (h - total) / 2.0).round() + i as f32 * 9.0; - batch.text(atlas, line, tx, ty, ink, !held); - } -} -pub fn draw_keystrokes( - batch: &mut HudBatch, - atlas: &HudAtlas, - corners: &mut Corners, - corner: Corner, - k: &Keystrokes, -) { - let (w, h) = keystrokes_size(); - let (x, y) = corners.place(corner, w, h); - let step = KEY + GAP; - let [forward, left, back, right] = &k.moves; - key_box( - batch, - atlas, - [x + step, y, KEY, KEY], - forward.0, - &[&forward.1], - ); - for (i, key) in [left, back, right].into_iter().enumerate() { - key_box( - batch, - atlas, - [x + i as f32 * step, y + step, KEY, KEY], - key.0, - &[&key.1], - ); - } - let mw = (w - GAP) / 2.0; - let my = y + 2.0 * step; - for (i, (held, label, cps)) in [ - (k.attack, "LMB", k.cps.map(|c| c.0)), - (k.use_, "RMB", k.cps.map(|c| c.1)), - ] - .into_iter() - .enumerate() - { - let rate = cps.map(|n| format!("{n} CPS")); - let lines: Vec<&str> = std::iter::once(label).chain(rate.as_deref()).collect(); - key_box( - batch, - atlas, - [x + i as f32 * (mw + GAP), my, mw, KEY], - held, - &lines, - ); - } - // The space bar: a line in a short key. - let sy = my + step; - key_box(batch, atlas, [x, sy, w, 10.0], k.jump, &[]); - let ink = if k.jump { - rgba(20, 20, 20, 255) - } else { - rgba(255, 255, 255, 255) - }; - batch.fill(atlas, x + w / 2.0 - 12.0, sy + 4.0, 24.0, 2.0, ink); -} - #[cfg(test)] mod tests { use super::*; @@ -259,15 +140,4 @@ mod tests { assert_eq!(c.place(Corner::BottomRight, 50.0, 10.0), (348.0, 274.0)); assert_eq!(c.place(Corner::BottomLeft, 10.0, 10.0), (2.0, 288.0)); } - - #[test] - fn fps_text_with_and_without_lows() { - let r = FpsReading { - fps: 144, - min: 61, - low: 98, - }; - assert_eq!(fps_text(r, false), "144 fps"); - assert_eq!(fps_text(r, true), "144 fps min 61 1% 98"); - } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5b04d8716..fb5260fbd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -101,6 +101,7 @@ mod mod_render; mod mods; mod mount_menu; mod mounts; +mod moved_extras; mod moving_pistons; mod music; mod names; @@ -11482,6 +11483,7 @@ impl ApplicationHandler for Game<'_> { } self.extras_frame(elapsed); self.mods_frame(elapsed); + self.poll_moved_extras(); self.extras_retry()?; self.apply_mouse_look(); self.pad_look(elapsed.as_secs_f32()); @@ -12809,6 +12811,7 @@ fn start_game<'a>( // Benchmarks measure the game alone. if game.options.benchmark.is_none() { game.mods.dev = game.options.dev_mods.clone(); + game.start_moved_extras(); game.start_mods(); } game.start_agent_control()?; diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 4664f0c6f..0bcc72739 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -1,11 +1,11 @@ //! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel, -//! clicks for the keystroke overlay, frame times for the FPS counter, the -//! minimap's tiles and image, and their HUD. Each hook does nothing while its -//! extra is off. +//! the minimap's tiles and image, and their HUD; clicks and frame times for +//! mods (`input.clicks-per-second`, `render.frame-stats`). Each hook does +//! nothing while its extra is off and no mod runs. use super::{Dim, Game, Screen}; use horizon_client::{ extras::{Corner, Cps, FpsCounter, Zoom, fov_target, turn_scale}, - extras_hud::{self, Corners, Keystrokes}, + extras_hud::{self, Corners}, hud::{HudBatch, MINIMAP_SPRITE}, keybinds, minimap::{self, Layer, Minimap, View}, @@ -70,8 +70,8 @@ impl Game<'_> { _ => return, }; self.extras.mouse[i] = pressed; - // Mods read the clicks too (`input.clicks-per-second`). - if pressed && (self.settings.extras.keystrokes || self.mods.running()) { + // For mods (`input.clicks-per-second`). + if pressed && self.mods.running() { let now = self.extras_now(); self.extras.cps[i].click(now); } @@ -88,8 +88,8 @@ impl Game<'_> { self.extras.mouse = [false; 2]; } self.update_minimap(); - // Mods read the counter too (`render.frame-stats`). - if self.settings.extras.fps || self.mods.running() { + // For mods (`render.frame-stats`). + if self.mods.running() { let now = self.extras_now(); self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0); } else { @@ -249,16 +249,14 @@ impl Game<'_> { pub(super) fn zoom_turn_scale(&self) -> f64 { turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity) } - /// 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. + /// 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. pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) { let e = &self.settings.extras; let mod_panels = self.mods.has_panels(); - if !e.fps && !e.keystrokes && !e.minimap && !mod_panels { + if !e.minimap && !mod_panels { return; } - let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows); - let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps); let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); @@ -282,32 +280,6 @@ impl Game<'_> { }; extras_hud::draw_minimap(batch, atlas, &mut corners, &look); } - if fps_on && visible(fps_corner) { - let reading = self.extras.fps.reading(); - extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows); - } - if keys_on && visible(keys_corner) { - let now = self.extras_now(); - let cps = cps_on.then(|| { - let [l, r] = &mut self.extras.cps; - (l.per_second(now), r.per_second(now)) - }); - let held = |k| self.keys.contains(&k); - let label = |name| keybinds::display_name(self.settings.keys.get(name)).plain(); - let k = Keystrokes { - moves: [ - (held(KeyCode::KeyW), label("key.forward")), - (held(KeyCode::KeyA), label("key.left")), - (held(KeyCode::KeyS), label("key.back")), - (held(KeyCode::KeyD), label("key.right")), - ], - jump: held(KeyCode::Space), - attack: self.extras.mouse[0], - use_: self.extras.mouse[1], - cps, - }; - extras_hud::draw_keystrokes(batch, &self.gui.atlas, &mut corners, keys_corner, &k); - } if mod_panels { self.draw_mod_panels(batch, &mut corners); } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 9d6015ad7..eb35c491f 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]>, + /// Extras that are official mods now, being installed. + #[cfg(feature = "mods")] + pub(super) moved: super::moved_extras::MovedState, } /// The mappings `input.mapping` answers for, with the default key their diff --git a/crates/horizon-client/src/game/moved_extras.rs b/crates/horizon-client/src/game/moved_extras.rs new file mode 100644 index 000000000..faeeea541 --- /dev/null +++ b/crates/horizon-client/src/game/moved_extras.rs @@ -0,0 +1,115 @@ +//! Extras that are official mods now (`horizon_client::moved_extras`): on +//! the first start after the update, a player who had one on gets the mod +//! installed from Horizon's registry, turned on, with their settings, and +//! one line in the chat saying so. The download runs on its own thread; if +//! it fails (offline), the game tries again at the next start. + +#[cfg(not(feature = "mods"))] +impl super::Game<'_> { + pub(super) fn start_moved_extras(&mut self) {} + pub(super) fn poll_moved_extras(&mut self) {} +} + +#[cfg(feature = "mods")] +mod with_mods { + use super::super::Game; + use horizon_client::{ + moved_extras::{self, Moved}, + text::{self, Text}, + }; + use std::sync::mpsc::{Receiver, channel}; + + type Done = Vec<(&'static Moved, Result<(), String>)>; + + #[derive(Default)] + pub(in crate::game) struct MovedState { + /// The installs under way. + running: Option>, + /// Lines for the player, shown once a world is open. + notices: Vec, + } + + impl Game<'_> { + /// At start: remembers the moved extras that were off, and installs + /// the ones that were on, in the background. + pub(in crate::game) fn start_moved_extras(&mut self) { + let off = moved_extras::nothing_to_do(&self.settings.extras); + let pending = moved_extras::pending(&self.settings.extras); + if off.is_empty() && pending.is_empty() { + return; + } + if !off.is_empty() { + let e = &mut self.settings.extras; + e.moved.extend(off.iter().map(|m| m.id.to_owned())); + self.settings.save(&Self::options_path()); + } + if pending.is_empty() { + return; + } + let extras = self.settings.extras.clone(); + let dir = Self::options_path() + .parent() + .map(std::path::Path::to_path_buf) + .unwrap_or_default(); + let (tx, rx) = channel(); + self.mods.moved.running = Some(rx); + let spawned = std::thread::Builder::new() + .name("Moved extras".into()) + .spawn(move || { + let done = match moved_extras::fetch_index() { + Ok(index) => pending + .into_iter() + .map(|m| (m, moved_extras::install(&index, m, &extras, &dir))) + .collect(), + Err(e) => pending.into_iter().map(|m| (m, Err(e.clone()))).collect(), + }; + let _ = tx.send(done); + }); + if spawned.is_err() { + self.mods.moved.running = None; + } + } + /// Once a frame: the installs that finished turn their mods on; + /// their lines wait for a world. + pub(in crate::game) fn poll_moved_extras(&mut self) { + if let Some(rx) = &self.mods.moved.running + && let Ok(done) = rx.try_recv() + { + self.mods.moved.running = None; + let mut installed = false; + for (m, result) in done { + match result { + Ok(()) => { + self.settings.extras.moved.push(m.id.to_owned()); + self.settings.mods.enabled.insert(m.id.to_owned()); + self.mods.moved.notices.push(Text::literal(m.notice())); + installed = true; + } + Err(e) => { + log::warn!("Horizon: {} not installed, next start retries: {e}", m.id); + self.mods.moved.notices.push( + Text::literal(format!( + "{} moved to the mod browser; it couldn't be installed for you yet, Horizon tries again at the next start", + m.name + )) + .with_color(text::GRAY), + ); + } + } + } + if installed { + self.settings.save(&Self::options_path()); + self.start_mods(); + } + } + if !self.mods.moved.notices.is_empty() && self.player.is_some() && self.title.is_none() + { + for line in std::mem::take(&mut self.mods.moved.notices) { + self.system_message(line); + } + } + } + } +} +#[cfg(feature = "mods")] +pub(super) use with_mods::MovedState; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ae95e1bdb..745052060 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -123,6 +123,7 @@ mod model_library; pub mod models; pub mod motion; pub mod mouse; +pub mod moved_extras; pub mod multiplayer; pub mod music; pub mod nbt_path; diff --git a/crates/horizon-client/src/moved_extras.rs b/crates/horizon-client/src/moved_extras.rs new file mode 100644 index 000000000..659592d80 --- /dev/null +++ b/crates/horizon-client/src/moved_extras.rs @@ -0,0 +1,214 @@ +//! Extras that became official mods (docs/mods.md, "Horizon's official +//! mods"). For a player who had one on, the game installs the mod from +//! Horizon's registry once, checked as the launcher checks it, turns it on +//! and carries the extra's settings over into the mod's storage. A player +//! who had it off gets nothing: the mod is in the mod browser. +use crate::{extras::Extras, mod_list::ModList}; +use horizon_mods::index::{self, Index}; +use std::{ + fs, + io::Read, + path::{Path, PathBuf}, +}; + +/// Horizon's registry; `HORIZON_MOD_INDEX` points elsewhere (a local file +/// for trials, whose files may then be `file://`), as for the launcher. +pub const INDEX_URL: &str = "https://ludovic111.github.io/horizon-mods/index.json"; +const MAX_INDEX: u64 = 16 << 20; + +/// An extra that is an official mod now. +#[derive(Debug, PartialEq)] +pub struct Moved { + /// The mod's id in the registry. + pub id: &'static str, + /// The extra's name, for the line the player reads. + pub name: &'static str, +} + +pub const MOVED: [Moved; 2] = [ + Moved { + id: "fps_overlay", + name: "FPS counter", + }, + Moved { + id: "keystrokes", + name: "Keystrokes", + }, +]; + +impl Moved { + fn was_on(&self, e: &Extras) -> bool { + match self.id { + "fps_overlay" => e.fps, + _ => e.keystrokes, + } + } + /// The extra's settings as the mod keeps them (its storage keys). + pub fn settings(&self, e: &Extras) -> Vec<(&'static str, String)> { + let flag = |b: bool| if b { "true" } else { "false" }.to_owned(); + match self.id { + "fps_overlay" => vec![ + ("corner", e.fps_corner.name().into()), + ("lows", flag(e.fps_lows)), + ], + _ => vec![ + ("corner", e.keystrokes_corner.name().into()), + ("cps", flag(e.keystrokes_cps)), + ], + } + } + /// The line the player reads once it is installed. + pub fn notice(&self) -> String { + format!("{} moved to the mod browser: installed for you", self.name) + } +} + +/// The moved extras still to install: on, and not done yet. +pub fn pending(e: &Extras) -> Vec<&'static Moved> { + MOVED + .iter() + .filter(|m| m.was_on(e) && !e.moved.iter().any(|d| d == m.id)) + .collect() +} + +/// The moved extras that were off and not marked yet: nothing to install, +/// only to remember. +pub fn nothing_to_do(e: &Extras) -> Vec<&'static Moved> { + MOVED + .iter() + .filter(|m| !m.was_on(e) && !e.moved.iter().any(|d| d == m.id)) + .collect() +} + +fn location() -> String { + std::env::var("HORIZON_MOD_INDEX") + .ok() + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| INDEX_URL.to_owned()) +} + +/// `url`'s bytes, at most `max`: `https://` from the network; `file://` only +/// with a local index (a trial registry). +fn get(url: &str, local: bool, max: u64) -> Result, String> { + let mut out = Vec::new(); + if url.starts_with("https://") { + let response = ureq::AgentBuilder::new() + .timeout(std::time::Duration::from_secs(60)) + .build() + .get(url) + .call() + .map_err(|e| format!("{url}: {e}"))?; + response + .into_reader() + .take(max + 1) + .read_to_end(&mut out) + .map_err(|e| e.to_string())?; + } else { + let path = match url.strip_prefix("file://") { + Some(p) if local => p, + _ if local && !url.contains("://") => url, + _ => return Err(format!("{url}: not an https address")), + }; + out = fs::read(path).map_err(|e| format!("{path}: {e}"))?; + } + if out.len() as u64 > max { + return Err(format!("{url}: over {max} bytes")); + } + Ok(out) +} + +/// The registry's index, from the network (or `HORIZON_MOD_INDEX`). +pub fn fetch_index() -> Result { + let at = location(); + let local = !at.starts_with("https://"); + let text = String::from_utf8(get(&at, local, MAX_INDEX)?).map_err(|e| e.to_string())?; + if local { + Index::parse_local(&text) + } else { + Index::parse(&text) + } +} + +/// Installs `m` into the game folder `dir` (where `options.txt` is), for a +/// player whose extras were `e`: its newest version for this game that +/// wasn't taken down, checked against the index (size, SHA-256, signature, +/// manifest), as `horizon-mods/.hmod`, turned on, with the extra's +/// settings in its storage unless the mod has its own already. +pub fn install(index: &Index, m: &Moved, e: &Extras, dir: &Path) -> Result<(), String> { + let project = index + .project(m.id) + .ok_or_else(|| format!("{} isn't in Horizon's registry yet", m.id))?; + let version = project + .versions + .iter() + .find(|v| { + v.game == horizon_core::version::VERSION_ID + && index.revoked(&project.id, &v.file.sha256).is_none() + }) + .ok_or_else(|| format!("{} has no version for this game", m.id))?; + let mods = dir.join(crate::mod_list::DIR); + fs::create_dir_all(&mods).map_err(|e| format!("{}: {e}", mods.display()))?; + let target = mods.join(format!("{}.hmod", m.id)); + let current = index::sha256_file(&target).ok(); + if current.as_deref() != Some(version.file.sha256.as_str()) { + let local = !location().starts_with("https://"); + let bytes = get(&version.file.url, local, index::MAX_FILE)?; + let partial: PathBuf = mods.join(format!(".{}.hmod.download", m.id)); + fs::write(&partial, bytes).map_err(|e| format!("{}: {e}", partial.display()))?; + if let Err(e) = index::check_file(index, project, version, &partial) { + let _ = fs::remove_file(&partial); + return Err(format!("{}: {e}", m.id)); + } + fs::rename(&partial, &target).map_err(|e| format!("{}: {e}", target.display()))?; + } + let storage = mods.join(horizon_mods::manifest::STORAGE_DIR).join(m.id); + fs::create_dir_all(&storage).map_err(|e| format!("{}: {e}", storage.display()))?; + for (key, value) in m.settings(e) { + let path = storage.join(key); + if !path.exists() { + fs::write(&path, value).map_err(|e| format!("{}: {e}", path.display()))?; + } + } + let mut list = ModList::load(dir); + list.enabled.insert(m.id.to_owned()); + list.save(dir); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::extras::Corner; + + #[test] + fn only_extras_that_were_on_are_installed_and_each_once() { + let mut e = Extras::default(); + assert!(pending(&e).is_empty()); + assert_eq!(nothing_to_do(&e).len(), 2); + e.fps = true; + e.fps_corner = Corner::BottomRight; + e.fps_lows = true; + assert_eq!(pending(&e), [&MOVED[0]]); + assert_eq!( + MOVED[0].settings(&e), + [("corner", "bottom_right".into()), ("lows", "true".into())] + ); + assert_eq!( + MOVED[1].settings(&e), + [("corner", "top_left".into()), ("cps", "true".into())] + ); + e.moved.push("fps_overlay".into()); + assert!(pending(&e).is_empty()); + assert_eq!(nothing_to_do(&e), [&MOVED[1]]); + assert_eq!( + MOVED[0].notice(), + "FPS counter moved to the mod browser: installed for you" + ); + } + + #[test] + fn a_file_url_needs_a_local_index() { + assert!(get("file:///etc/hosts", false, 1 << 20).is_err()); + assert!(get("http://example.com/x", true, 1 << 20).is_err()); + } +} diff --git a/docs/extras.md b/docs/extras.md index 26ddbe161..598b29739 100644 --- a/docs/extras.md +++ b/docs/extras.md @@ -1,8 +1,7 @@ # Horizon extras -Optional conveniences built into the client: fullbright, dynamic lights, zoom, a minimap, an FPS counter, a -keystroke overlay, auto-reconnect, Mouse Tweaks-style inventory controls and -inventory sorting. **Every one is off by default**: a fresh +Optional conveniences built into the client: fullbright, dynamic lights, zoom, a minimap, auto-reconnect, +Mouse Tweaks-style inventory controls and inventory sorting. **Every one is off by default**: a fresh install looks and behaves exactly like vanilla 26.3, and turning an extra off again restores vanilla's behaviour completely. @@ -11,9 +10,9 @@ again restores vanilla's behaviour completely. | Part | Code | |---|---| | Settings, parsing and saving | `crates/horizon-client/src/extras.rs` | -| Zoom curve, FPS and click counters | `extras.rs` (pure logic, unit tested) | +| Zoom curve; FPS and click counters (for mods) | `extras.rs` (pure logic, unit tested) | | Dynamic lights: item glow, nearest sources | `crates/horizon-client/src/dynamic_light.rs` (unit tested), `game/dynamic_lights.rs`, `terrain.wgsl` and `entity.wgsl` (`dynamic_block_light`) | -| HUD drawing (FPS, keystrokes, minimap frame) | `crates/horizon-client/src/extras_hud.rs` | +| HUD drawing (minimap frame, corner stacking) | `crates/horizon-client/src/extras_hud.rs` | | Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` | | Reconnect policy and backoff | `crates/horizon-client/src/reconnect.rs` | | Game glue (input hooks, per-frame update) | `crates/horizon-client/src/game/extras.rs` | @@ -83,15 +82,15 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int - With zoom off (or the key up) the FOV target and mouse are vanilla's, bit for bit; the FOV harness covers this. -### FPS counter (`fps`, default off) -- A small "N fps" line in a corner (default top left), optionally followed by - the minimum and the 1% low over the last 5 seconds. -- Separate from the Advanced graphics "Overlay" (the frame-time graph). +### Moved to the mod browser -### Keystrokes (`keystrokes`, default off) -- W A S D, Space, LMB and RMB keys that light up while held, with clicks per - second under the mouse buttons (clicks in the last second). The letters follow - the bound keys. +The **FPS counter** and **Keystrokes** are official mods now (`mods/official/`, [mods.md](mods.md#horizons-official-mods)), +with the same look and options. On the first start after the update, a player who had one on gets the mod installed +from Horizon's registry and turned on, with their corner and options carried over, and reads one line in the chat +("FPS counter moved to the mod browser: installed for you"). The install is checked like the launcher's (size, +SHA-256, signature, manifest); if it fails (offline), the next start tries again. `horizon-extras.txt` keeps the old +keys and lists what was done in `movedToMods`. Code: `crates/horizon-client/src/moved_extras.rs`, +`game/moved_extras.rs`. ### Minimap (`minimap`, default off) - A corner map (top right by default), square or round, small/medium/large, @@ -162,11 +161,11 @@ and the container screen tests are unchanged). the world, like vanilla's HUD. Extras in the top left corner give way to the debug screen (F3), which shows the FPS anyway. - Corners stack: extras placed in the same corner stack downward (top corners) - or upward (bottom corners) in the order minimap, FPS, keystrokes. The top + or upward (bottom corners) in the order minimap, then mods' panels. The top right corner starts below the status effect icons. ## Perf budget Off: a flag check per frame per extra (no allocations, no world access). -On: FPS and keystrokes are a few quads; the minimap stays under 0.3 ms of CPU +On: the minimap stays under 0.3 ms of CPU per frame (tile budget) plus a 64 KiB texture upload when its image changes.