diff --git a/.github/workflows/parity-main.yml b/.github/workflows/parity-main.yml index 13be3c36d..c47005ab0 100644 --- a/.github/workflows/parity-main.yml +++ b/.github/workflows/parity-main.yml @@ -23,10 +23,10 @@ env: jobs: parity-main: - # The Mac mini's release runner (label added 2026-10-26), not the two `horizon-game` runners: behind PR parity jobs - # this run waited 2 h while every merge replaced the pending one, and releases wait for it. Releases need it green - # first, so the two never compete. Not the desktop: a job slowed down because the maintainer came back could time - # out, and a failure here bisects and comments on merges. + # A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs + # this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited + # behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down + # because the maintainer came back could time out, and a failure here bisects and comments on merges. runs-on: [self-hosted, macOS, horizon-parity-main] timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures steps: diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml index b48be1d05..1fc31d8cb 100644 --- a/.github/workflows/parity.yml +++ b/.github/workflows/parity.yml @@ -52,7 +52,14 @@ jobs: - name: The prepared output is the one the preparer's OUTPUT_VERSION says env: BASE_SHA: ${{ inputs.base }} - run: python3 tools/prepare_output.py check --cache --base "$BASE_SHA" + run: | + # The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither + # the tool nor the number, so there is nothing to check. + if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then + echo "This head's preparer has no OUTPUT_VERSION: nothing to check" + exit 0 + fi + python3 tools/prepare_output.py check --cache --base "$BASE_SHA" - name: The version constants are the pinned jar's run: python3 tools/gen_version_consts.py --check - name: The harnesses this change can affect diff --git a/Cargo.lock b/Cargo.lock index 73c40a57a..9f4678859 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2083,6 +2083,13 @@ dependencies = [ "libc", ] +[[package]] +name = "minimap" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "minisign-verify" version = "0.3.0" @@ -5253,6 +5260,13 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zoom" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "zopfli" version = "0.8.4" diff --git a/Cargo.toml b/Cargo.toml index cc88441a4..4d463654b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "mods/official/fps-overlay", "mods/official/keystrokes", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/cargo-horizon-mod/src/main.rs b/crates/cargo-horizon-mod/src/main.rs index a4585f680..b82c6d07f 100644 --- a/crates/cargo-horizon-mod/src/main.rs +++ b/crates/cargo-horizon-mod/src/main.rs @@ -6,12 +6,15 @@ //! `assets/` and `data/`; a folder without `Cargo.toml` is content only. //! - `run [--game ] [-- ]`: build, then play with //! the mod; run `build` again and the game reloads it. +//! - `test [--debug] [--hmod ] []`: build, then run the mod's +//! `tests/*.toml` scripts in the sandbox, with no game. //! - `check [--json]`: what the registry checks of a submission //! (`.hmod`, `.hpack`, resource pack `.zip`), with a trial run for a mod. //! - `registry build|review|check|list`: the registry repository's CI. use horizon_mods::{ Capability, Content, Manifest, Package, manifest::{MANIFEST, component_imports, componentize}, + testing::{Script, TestGame}, }; mod check; mod registry; @@ -36,9 +39,10 @@ fn main() -> ExitCode { println!("Built {}", p.display()); }), Some("run") => run(&args[1..]), + Some("test") => test(&args[1..]), Some("check") => check(&args[1..]), Some("registry") => registry::main(&args[1..]), - _ => Err("usage: cargo horizon-mod new [--template code|content] | build [--debug] | run [--game ] [-- ] | check [--kind ] [--key --signature ] [--json] | registry build|review|check|list".into()), + _ => Err("usage: cargo horizon-mod new [--template code|content] | build [--debug] | run [--game ] [-- ] | test [--debug] [--hmod ] [] | check [--kind ] [--key --signature ] [--json] | registry build|review|check|list".into()), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -97,6 +101,10 @@ fn new(args: &[String]) -> Result<(), String> { (MANIFEST, include_str!("../template/horizon-mod.toml")), ("src/lib.rs", include_str!("../template/src/lib.rs")), (".gitignore", include_str!("../template/gitignore")), + ( + "tests/hello.toml", + include_str!("../template/tests/hello.toml"), + ), ]; // A block copying a vanilla one, with its model, name, loot, recipe and tag. let content = [ @@ -270,6 +278,63 @@ fn check(args: &[String]) -> Result<(), String> { Ok(()) } +/// `test`: every `tests/*.toml` script (those whose name holds ``) +/// against the built mod, or the `.hmod` given with `--hmod`. +fn test(args: &[String]) -> Result<(), String> { + let hmod = match flag(args, "--hmod") { + Some(p) => PathBuf::from(p), + None => build(!args.iter().any(|a| a == "--debug"))?, + }; + let filter = args + .iter() + .enumerate() + .find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--hmod")) + .map(|(_, a)| a.as_str()); + let mut scripts: Vec = std::fs::read_dir("tests") + .map_err(|e| { + format!( + "tests/: {e} (a mod's tests are tests/.toml: docs/mods.md, \"Testing a mod\")" + ) + })? + .filter_map(|e| Some(e.ok()?.path())) + .filter(|p| p.extension().is_some_and(|e| e == "toml")) + .filter(|p| filter.is_none_or(|f| p.to_string_lossy().contains(f))) + .collect(); + scripts.sort(); + if scripts.is_empty() { + return Err("no tests/*.toml to run".into()); + } + println!( + "running {} scripts against {}", + scripts.len(), + hmod.display() + ); + let mut failed = 0; + for path in &scripts { + let result = std::fs::read_to_string(path) + .map_err(|e| e.to_string()) + .and_then(|text| Script::parse(&text)) + .and_then(|script| { + let mut game = TestGame::load(&hmod)?; + script.run(&mut game)?; + Ok(script.steps.len()) + }); + match result { + Ok(steps) => println!("test {} ... ok ({steps} steps)", path.display()), + Err(e) => { + failed += 1; + println!("test {} ... FAILED\n {e}", path.display()); + } + } + } + let passed = scripts.len() - failed; + if failed > 0 { + return Err(format!("{failed} failed, {passed} passed")); + } + println!("test result: ok. {passed} passed"); + Ok(()) +} + fn run(args: &[String]) -> Result<(), String> { let path = build(true)?; let game = flag(args, "--game") @@ -312,6 +377,8 @@ mod tests { ); let cargo = std::fs::read_to_string(path.join("Cargo.toml")).unwrap(); assert!(cargo.contains("name = \"my-mod\"") && cargo.contains(SDK_GIT)); + let script = std::fs::read_to_string(path.join("tests/hello.toml")).unwrap(); + assert_eq!(Script::parse(&script).unwrap().steps.len(), 3); assert!( new(&[path.display().to_string()]).is_err(), "never overwrites" diff --git a/crates/cargo-horizon-mod/template/tests/hello.toml b/crates/cargo-horizon-mod/template/tests/hello.toml new file mode 100644 index 000000000..17afd7e65 --- /dev/null +++ b/crates/cargo-horizon-mod/template/tests/hello.toml @@ -0,0 +1,14 @@ +# `cargo horizon-mod test` runs every tests/*.toml against the built mod, with no game: +# steps happen in order, and `expect` checks what the mod showed during the step. +# Every key: docs/mods.md, "Testing a mod". + +[[step]] +expect.commands = ["hello"] + +[[step]] +command = "hello world" +expect.chat = ["Hello world! (1 so far)"] + +[[step]] +command = "hello again" +expect.chat = ["Hello again! (2 so far)"] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index a585ce19e..d7c6d812b 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -23,7 +23,7 @@ horizon-shader-api = { path = "../horizon-shader-api" } 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/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index cf7be69a6..f722e2f9a 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -143,6 +143,7 @@ const PAGES: Ty = Ty::Enum(&[ "font", "packs", "mods", + "shader-packs", "graphics", "graphics-advanced", "extras", diff --git a/crates/horizon-client/src/debug_overlay.rs b/crates/horizon-client/src/debug_overlay.rs index 3448ea411..7140905a8 100644 --- a/crates/horizon-client/src/debug_overlay.rs +++ b/crates/horizon-client/src/debug_overlay.rs @@ -84,6 +84,33 @@ impl Displayer { } } +/// Horizon's own lines: the shader pack's GPU time, then its costliest passes (`passes`: each +/// pass's median milliseconds, in the order they run). +pub fn shader_pass_lines(passes: &[(String, f32)]) -> Vec { + const SHOWN: usize = 8; + if passes.is_empty() { + return Vec::new(); + } + let total: f32 = passes.iter().map(|p| p.1).sum(); + let mut lines = vec![format!( + "Shader pack GPU: {total:.2} ms in {} passes", + passes.len() + )]; + let mut costliest: Vec<&(String, f32)> = passes.iter().collect(); + costliest.sort_by(|a, b| b.1.total_cmp(&a.1)); + lines.extend( + costliest + .iter() + .take(SHOWN) + .map(|(name, ms)| format!("{name}: {ms:.2} ms")), + ); + if costliest.len() > SHOWN { + let rest: f32 = costliest[SHOWN..].iter().map(|p| p.1).sum(); + lines.push(format!("{} more: {rest:.2} ms", costliest.len() - SHOWN)); + } + lines +} + /// `Mth.wrapDegrees`. fn wrap_degrees(angle: f32) -> f32 { let wrapped = angle % 360.0; @@ -337,4 +364,15 @@ mod tests { (1.0, [640, 360]) ); } + + #[test] + fn shader_pass_lines_list_the_costliest_passes_first() { + assert!(shader_pass_lines(&[]).is_empty()); + let passes: Vec<(String, f32)> = (0..10).map(|i| (format!("p{i}"), i as f32)).collect(); + let lines = shader_pass_lines(&passes); + assert_eq!(lines[0], "Shader pack GPU: 45.00 ms in 10 passes"); + assert_eq!(lines[1], "p9: 9.00 ms"); + assert_eq!(lines[8], "p2: 2.00 ms"); + assert_eq!(lines[9], "2 more: 1.00 ms"); + } } diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 40e87214e..d2f0b4e9d 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -1,4 +1,4 @@ -//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their +//! Horizon's optional extras (minimap, lighting, inventory tools): their //! settings, kept in `horizon-extras.txt` next to `options.txt` so that file //! stays exactly vanilla's, and the logic behind them. Every extra is off by //! default; see `docs/extras.md`. Horizon's own switches outside the Extras page @@ -6,17 +6,8 @@ use std::{collections::VecDeque, fs, path::Path}; pub const FILE: &str = "horizon-extras.txt"; -/// The name the options screen uses while the zoom key waits for a key. -pub const ZOOM_KEY: &str = "horizon.zoom"; -/// The same for the sort key. +/// The name the options screen uses while the sort key waits for a key. pub const SORT_KEY: &str = "horizon.sort"; -/// Zoom levels the default cycles through, and the wheel's limits. -pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10]; -pub const ZOOM_MIN: f32 = 1.25; -/// `Camera.tickFov` keeps the field-of-view modifier at 0.1 or more. -pub const ZOOM_MAX: f32 = 10.0; -/// Each wheel step multiplies the zoom by this. -const ZOOM_STEP: f32 = 1.25; /// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel. pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")]; @@ -81,6 +72,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 +83,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 +129,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, @@ -177,7 +175,7 @@ impl Extras { "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), "zoomLevel" => { if let Ok(v) = value.parse::() { - e.zoom_level = v.clamp(2, ZOOM_MAX as u8); + e.zoom_level = v.clamp(2, 10); } } "zoomSmooth" => e.zoom_smooth = flag(e.zoom_smooth), @@ -190,6 +188,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 +225,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 +239,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, @@ -254,11 +261,10 @@ impl Extras { bool_text(self.discord_presence), ) } - /// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for + /// Binds the extra key `name` (`SORT_KEY`); false for /// another name (a vanilla mapping). pub fn set_key(&mut self, name: &str, value: String) -> bool { match name { - ZOOM_KEY => self.zoom_key = value, SORT_KEY => self.sort_key = value, _ => return false, } @@ -275,87 +281,12 @@ impl Extras { } } -/// The zoom key's state: held or not, and the zoom the wheel has set. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Zoom { - held: bool, - factor: f32, -} -impl Default for Zoom { - fn default() -> Self { - Self { - held: false, - factor: 1.0, - } - } -} -impl Zoom { - /// The key went down: start at the default level. - pub fn press(&mut self, level: u8) { - self.held = true; - self.factor = f32::from(level).clamp(ZOOM_MIN, ZOOM_MAX); - } - pub fn release(&mut self) { - self.held = false; - } - /// A press or release of the zoom key. Only a press while `playing` (no - /// screen or text field open) zooms; anywhere else the key belongs to - /// the screen, and the zoom lets go. - pub fn key(&mut self, pressed: bool, repeat: bool, playing: bool, level: u8) { - if !pressed || !playing { - self.release(); - } else if !repeat { - self.press(level); - } - } - pub fn held(&self) -> bool { - self.held - } - /// Wheel steps while held (positive zooms in); false when not zooming. - pub fn scroll(&mut self, steps: f32) -> bool { - if !self.held { - return false; - } - self.factor = (self.factor * ZOOM_STEP.powf(steps)).clamp(ZOOM_MIN, ZOOM_MAX); - true - } - /// The zoom in effect: 1 when the key is up or the spyglass is in use - /// (scoping keeps vanilla's spyglass view). - pub fn factor(&self, scoping: bool) -> f32 { - if self.held && !scoping { - self.factor - } else { - 1.0 - } - } -} -/// Vanilla key mappings bound to the zoom key. The key still reaches them -/// (a key bound twice triggers both, as vanilla's do), so the Extras page -/// says so. -pub fn zoom_key_conflicts(e: &Extras, keys: &crate::keybinds::KeyBinds) -> Vec<&'static str> { - if e.zoom_key == "key.keyboard.unknown" { - return Vec::new(); - } - crate::keybinds::MAPPINGS - .iter() - .map(|m| m.0) - .filter(|name| keys.get(name) == e.zoom_key) - .collect() -} /// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's -/// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is. +/// (`getFieldOfViewModifier`) divided by a mod's zoom (`render.set-zoom`). A +/// zoom of 1 leaves it as is. pub fn fov_target(vanilla: f32, zoom: f32) -> f32 { if zoom == 1.0 { vanilla } else { vanilla / zoom } } -/// The mouse turning scale while zoomed. -pub fn turn_scale(zoom: f32, lower_sensitivity: bool) -> f64 { - if lower_sensitivity && zoom > 1.0 { - 1.0 / f64::from(zoom) - } else { - 1.0 - } -} - /// Frame times over the last few seconds: frames per second, the minimum /// and the 1% low, recomputed twice a second. pub struct FpsCounter { @@ -447,23 +378,6 @@ impl Cps { pub enum Item { Fullbright, DynamicLights, - Zoom, - ZoomKey, - ZoomLevel, - ZoomSmooth, - ZoomSensitivity, - Fps, - FpsCorner, - FpsLows, - Keystrokes, - KeystrokesCorner, - KeystrokesCps, - Minimap, - MinimapCorner, - MinimapSize, - MinimapShape, - MinimapZoom, - MinimapRotate, AutoReconnect, MouseTweaks, MouseTweaksWheel, @@ -482,27 +396,6 @@ pub fn rows() -> Vec> { Err("Lighting"), Ok(Fullbright), Ok(DynamicLights), - Err("Zoom"), - Ok(Zoom), - Ok(ZoomKey), - Ok(ZoomLevel), - Ok(ZoomSmooth), - Ok(ZoomSensitivity), - Err("Minimap"), - Ok(Minimap), - Ok(MinimapCorner), - Ok(MinimapSize), - 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), @@ -512,46 +405,16 @@ pub fn rows() -> Vec> { Ok(AutoReconnect), ] } -/// "1 block", "2 blocks", "½ block". -fn block_count(n: f32) -> String { - if n < 1.0 { - "½ block".into() - } else if n == 1.0 { - "1 block".into() - } else { - format!("{n} blocks") - } -} -fn next(all: &[T], current: T, back: bool) -> T { - let i = all.iter().position(|v| *v == current).unwrap_or(0); - let n = all.len(); - all[if back { (i + n - 1) % n } else { (i + 1) % n }] -} impl Item { pub fn caption(self) -> &'static str { match self { Item::Fullbright => "Fullbright", Item::DynamicLights => "Dynamic lights", - Item::Zoom => "Zoom", - Item::ZoomKey => "Zoom key", - Item::ZoomLevel => "Starting zoom", - Item::ZoomSmooth => "Smooth zoom", - Item::ZoomSensitivity => "Slower turning", - Item::Fps => "FPS counter", - Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner", - Item::Minimap => "Minimap", - Item::MinimapSize => "Size", - Item::MinimapShape => "Shape", - Item::MinimapZoom => "Zoom", - Item::MinimapRotate => "Turn with the player", Item::AutoReconnect => "Auto-reconnect", Item::MouseTweaks => "Mouse Tweaks controls", 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", @@ -561,14 +424,10 @@ impl Item { pub fn parent(self) -> Option { use 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 | MouseTweaks | Sort | AutoReconnect | NoAi + | AgentControl | DiscordPresence => { return None; } }) @@ -580,24 +439,9 @@ impl Item { Item::DynamicLights => { "Torches and other light sources held, dropped or on fire light the blocks around them." } - Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", - Item::ZoomKey => "Click, then press a key. Escape unbinds it.", - 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::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.", - Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.", - Item::MinimapRotate => "Forward is up; off keeps north up.", 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 +454,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,8 +469,8 @@ 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::Minimap | Item::DynamicLights => Some(Cost::Low), + Item::Fullbright => Some(Cost::None), + Item::DynamicLights => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, } @@ -638,15 +480,6 @@ impl Item { Some(match self { Item::Fullbright => e.fullbright, Item::DynamicLights => e.dynamic_lights, - 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, Item::MouseTweaks => e.mouse_tweaks, Item::MouseTweaksWheel => e.mouse_tweaks_wheel, @@ -660,65 +493,32 @@ impl Item { /// The value of the other items, as their button shows it. pub fn value(self, e: &Extras) -> String { match self { - 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() - .find(|s| s.0 == e.minimap_size) - .map_or("Medium", |s| s.1) - .into(), - Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(), - Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)), other => match other.switch(e) { Some(true) => "On".into(), _ => "Off".into(), }, } } - /// A click (`back` for the right button). The zoom key binds instead. - pub fn cycle(self, e: &mut Extras, back: bool) { + /// A click (`_back` for the right button: every item left is a switch, + /// so both flip it). The sort key binds instead. + pub fn cycle(self, e: &mut Extras, _back: bool) { match self { Item::Fullbright => e.fullbright = !e.fullbright, Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights, - 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, Item::MouseTweaks => e.mouse_tweaks = !e.mouse_tweaks, Item::MouseTweaksWheel => e.mouse_tweaks_wheel = !e.mouse_tweaks_wheel, Item::Sort => e.sort = !e.sort, - Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back), - Item::MinimapSize => { - let sizes: Vec = MINIMAP_SIZES.iter().map(|s| s.0).collect(); - e.minimap_size = next(&sizes, e.minimap_size, back); - } - Item::MinimapShape => e.minimap_round = !e.minimap_round, - Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back), Item::NoAi => e.no_ai = !e.no_ai, Item::AgentControl => e.agent_control = !e.agent_control, Item::DiscordPresence => e.discord_presence = !e.discord_presence, - Item::ZoomKey | Item::SortKey => {} + Item::SortKey => {} } } /// The key name the options screen waits on for a key item. pub fn key_name(self) -> Option<&'static str> { match self { - Item::ZoomKey => Some(ZOOM_KEY), Item::SortKey => Some(SORT_KEY), _ => None, } @@ -750,6 +550,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; @@ -775,43 +576,7 @@ mod tests { } #[test] - fn default_zoom_key_is_free_in_vanilla() { - let key = Extras::default().zoom_key; - assert!(crate::keybinds::key_code(&key).is_some()); - assert!( - crate::keybinds::MAPPINGS.iter().all(|m| m.1 != key), - "{key} is a vanilla binding" - ); - } - - #[test] - fn zoom_is_vanilla_unless_held_and_not_scoping() { - let mut z = Zoom::default(); - assert_eq!(z.factor(false), 1.0); - assert_eq!(fov_target(1.1, z.factor(false)), 1.1); - assert!(!z.scroll(1.0), "the wheel is the hotbar's when not zooming"); - z.press(4); - assert_eq!(z.factor(false), 4.0); - assert_eq!(z.factor(true), 1.0, "the spyglass wins"); - assert!((fov_target(1.0, 4.0) - 0.25).abs() < 1e-6); - assert!(z.scroll(1.0)); - assert!((z.factor(false) - 5.0).abs() < 1e-5); - for _ in 0..40 { - z.scroll(1.0); - } - assert_eq!(z.factor(false), ZOOM_MAX); - for _ in 0..80 { - z.scroll(-1.0); - } - assert_eq!(z.factor(false), ZOOM_MIN); - z.release(); - assert_eq!(z.factor(false), 1.0); - z.press(2); - assert_eq!(z.factor(false), 2.0, "each press starts at the default"); - } - - #[test] - fn zoom_target_eases_like_the_spyglass() { + fn a_mods_zoom_eases_like_the_spyglass() { // Camera.tickFov halves the distance to the target each tick. let mut camera = crate::camera::Camera::default(); camera.tick(None, 1.0); @@ -835,55 +600,6 @@ mod tests { assert!((floor - 7.0).abs() < 1e-3, "{floor}"); } - #[test] - fn the_zoom_key_only_zooms_while_playing() { - let mut z = Zoom::default(); - // In chat, a sign, a text field or any screen: no zoom. - z.key(true, false, false, 4); - assert!(!z.held()); - z.key(true, false, true, 4); - assert!(z.held()); - // A screen opening while held lets go (its key presses are the screen's). - z.key(true, true, false, 4); - assert!(!z.held()); - // Key repeats do not restart a zoom the wheel changed. - z.key(true, false, true, 4); - z.scroll(1.0); - z.key(true, true, true, 4); - assert!((z.factor(false) - 5.0).abs() < 1e-5); - z.key(false, false, true, 4); - assert!(!z.held()); - } - - #[test] - fn zoom_key_conflicts_name_the_vanilla_mappings() { - let mut e = Extras::default(); - let mut keys = crate::keybinds::KeyBinds::default(); - assert!(zoom_key_conflicts(&e, &keys).is_empty()); - e.zoom_key = "key.keyboard.c".into(); - assert_eq!( - zoom_key_conflicts(&e, &keys), - [ - "key.saveToolbarActivator", - "key.debug.crash", - "key.debug.copyLocation" - ] - ); - keys.set("key.drop", "key.keyboard.z"); - e.zoom_key = "key.keyboard.z".into(); - assert_eq!(zoom_key_conflicts(&e, &keys), ["key.drop"]); - e.zoom_key = "key.keyboard.unknown".into(); - keys.set("key.smoothCamera", "key.keyboard.unknown"); - assert!(zoom_key_conflicts(&e, &keys).is_empty()); - } - - #[test] - fn sensitivity_scales_with_zoom() { - assert_eq!(turn_scale(1.0, true), 1.0); - assert_eq!(turn_scale(4.0, false), 1.0); - assert_eq!(turn_scale(4.0, true), 0.25); - } - #[test] fn fps_counter_reports_rate_minimum_and_low() { let mut c = FpsCounter::default(); @@ -937,20 +653,9 @@ mod tests { #[test] fn items_cycle_through_their_values() { let mut e = Extras::default(); - Item::ZoomLevel.cycle(&mut e, false); - assert_eq!(e.zoom_level, 6); - 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::Zoom.cycle(&mut e, false); - assert_eq!(Item::Zoom.switch(&e), Some(true)); - assert_eq!(Item::ZoomKey.value(&e), "Z"); - Item::MinimapZoom.cycle(&mut e, true); - assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel"); - Item::MinimapSize.cycle(&mut e, false); - assert_eq!(Item::MinimapSize.value(&e), "Large"); + Item::Sort.cycle(&mut e, true); + assert_eq!(Item::Sort.value(&e), "On"); + // The minimap's old keys still parse, for the move to its mod. assert_eq!( Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom, 1.0 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 f7dffb734..8591c721f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -103,6 +103,7 @@ mod mod_render; mod mods; mod mount_menu; mod mounts; +mod moved_extras; mod moving_pistons; mod music; mod names; @@ -130,6 +131,7 @@ mod pumpkin; mod raids; mod recipe_book; mod remote; +mod remote_chunks; mod remote_mob_data; mod remote_mob_use; mod remote_objects; @@ -557,6 +559,8 @@ struct GameLevel<'w> { /// Where the chunk tickets let blocks tick. tickets: horizon_client::ticket_levels::Levels, random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections, + /// Players with each chest open (a trapped chest's signal). + lid_openers: &'w HashMap<(i32, i32, i32), i32>, } struct PlayerCollision { y: f64, @@ -692,6 +696,10 @@ impl LevelAccess for GameLevel<'_> { _state: BlockStateId, _direction: Direction, ) -> i32 { + // TrappedChestBlock.getSignal: the players with it open, at most 15. + if let Some(count) = self.lid_openers.get(&(pos.x, pos.y, pos.z)) { + return (*count).clamp(0, 15); + } jukebox::jukebox_signals(self.world, self.items, pos).map_or(0, |(signal, _)| signal) } fn biome_name(&self, pos: BlockPos) -> Option<&str> { @@ -1504,7 +1512,7 @@ struct Game<'a> { pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, /// Recent frame times for the performance overlay. frame_graph: horizon_client::perf_overlay::FrameGraph, - /// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`. + /// Horizon's extras (minimap, auto-reconnect; mods' counters): `game/extras.rs`. extras: extras::ExtrasState, /// Horizon mods (`game/mods.rs`), none running unless turned on. mods: mods::ModsState, @@ -2202,7 +2210,7 @@ impl Game<'_> { self.player_drop(thrown); } /// `Player.drop`: the statistics and a thrown item entity in front of the player. - fn player_drop(&mut self, thrown: ItemStack) { + pub(super) fn player_drop(&mut self, thrown: ItemStack) { let Some(eye) = self.eye_position() else { return; }; @@ -2473,6 +2481,7 @@ impl Game<'_> { spill: &mut self.spill, tickets: self.tickets.levels(), random_tick_sections: &mut self.random_tick_sections, + lid_openers: &self.lid_openers, }; let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); @@ -6511,7 +6520,11 @@ impl Game<'_> { use horizon_client::menu::Input; let button = i32::from(right); if self.remote.is_some() { - self.remote_throw(right, input); + if self.screen == Screen::Creative { + self.remote_creative_drop(right); + } else { + self.remote_throw(right, input); + } return; } let before = self.carried.clone(); @@ -10495,7 +10508,10 @@ impl Game<'_> { menu_blur: self.menu_blur(), }; let result = match self.renderer.as_mut() { - Some(renderer) => horizon_client::spans::time("renderer", || renderer.render(&frame)), + Some(renderer) => { + renderer.set_pass_timing(self.debug); + horizon_client::spans::time("renderer", || renderer.render(&frame)) + } None => Err("renderer".into()), }; // Restore storage even when rendering fails (for example, a lost surface). @@ -11295,7 +11311,6 @@ impl ApplicationHandler for Game<'_> { && self.sleeping.is_none() && self.player.is_some() && !self.mod_wheel(d) - && !self.extras_scroll(d) && let Some((wheel, (_, vertical_steps))) = self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) @@ -11706,7 +11721,6 @@ impl ApplicationHandler for Game<'_> { let PhysicalKey::Code(key) = event.physical_key else { return Ok(()); }; - self.extras_key(key, event.state == ElementState::Pressed, event.repeat); self.mod_key(key, event.state == ElementState::Pressed, event.repeat); // key.smoothCamera toggles the cinematic camera. if self.screen == Screen::Playing @@ -11799,6 +11813,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()); @@ -13149,6 +13164,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/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 55f9c42ba..56f571bee 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -13,7 +13,10 @@ use horizon_client::{ save::number, skins, }; -use horizon_core::geometry::{Aabb, Vec3}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + position::BlockPos, +}; use horizon_world::nbt::Tag; /// The handle of the local player among a bell's gathered entities. @@ -86,6 +89,16 @@ impl Game<'_> { self.lid_openers_changed(other, open); } } + _ if self + .res + .facts() + .get(self.world.block(pos[0], pos[1], pos[2])) + .name + .as_ref() + == "minecraft:barrel" => + { + self.barrel_openers_changed(key, open); + } Some(Ticker::Shulker { .. }) => { let shulker = self.be_anims.shulkers.entry(pos).or_default(); let (count, _) = if open { @@ -104,15 +117,48 @@ impl Game<'_> { /// `ChestBlockEntity.signalOpenCount`: block event 1 with the count, here /// and for the guests. fn lid_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { - let count = self.lid_openers.entry(key).or_default(); - *count = (*count + if open { 1 } else { -1 }).max(0); - let count = *count; - if count == 0 { - self.lid_openers.remove(&key); - } + let (before, count) = self.count_opener(key, open); let pos = [key.0, key.1, key.2]; self.block_entity_event(pos, 1, count); self.lan_block_event(pos, 1, count); + // TrappedChestBlockEntity.signalOpenCount: its signal is the count + // (`TrappedChestBlock.getSignal`), so the blocks around it and + // below it hear of a change. + let state = self.world.block(pos[0], pos[1], pos[2]); + if before != count && self.res.facts().get(state).name.as_ref() == "minecraft:trapped_chest" + { + let p = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| { + let block = b.block(state); + b.update_neighbors_at(level, ticks, p, block); + b.update_neighbors_at(level, ticks, p.offset(0, -1, 0), block); + }); + } + } + /// `BarrelBlockEntity.openersCounter`: the first opener opens the barrel + /// (`open=true`), the last one to leave closes it (`updateBlockState`). + fn barrel_openers_changed(&mut self, key: (i32, i32, i32), open: bool) { + let (before, count) = self.count_opener(key, open); + if (before == 0) != (count == 0) { + self.set_bool_prop( + key, + "open", + count > 0, + horizon_world::level::flags::UPDATE_ALL, + ); + } + } + /// One opener more (`open`) or less at `key`: the count before and after + /// (`ContainerOpenersCounter.incrementOpeners` / `decrementOpeners`). + fn count_opener(&mut self, key: (i32, i32, i32), open: bool) -> (i32, i32) { + let count = self.lid_openers.entry(key).or_default(); + let before = *count; + *count = (before + if open { 1 } else { -1 }).max(0); + let after = *count; + if after == 0 { + self.lid_openers.remove(&key); + } + (before, after) } /// `BellBlockEntity.updateEntities`: the living entities whose bounding /// box meets the bell's block box inflated by 48. diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f418b0b83..7a632e308 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -295,13 +295,9 @@ impl Game<'_> { self.debug_key(key, KeyAction::Release); } } - // The zoom extra sees the key as the keyboard hook does. + // Mods' keys (capability `input`) see the key as the keyboard + // hook does. let action = arg(2)?; - self.extras_key(physical, action != "up", action == "repeat"); - if action == "tap" { - self.extras_key(physical, false, false); - } - // So do mods' keys (capability `input`). self.mod_key(physical, action != "up", action == "repeat"); if action == "tap" { self.mod_key(physical, false, false); @@ -379,15 +375,19 @@ impl Game<'_> { match arg(2)? { "down" => { self.extras_mouse(button, true); + self.mod_mouse_key(button, true); self.play_mouse(button, true)? } "up" => { self.extras_mouse(button, false); + self.mod_mouse_key(button, false); self.play_mouse(button, false)? } "click" => { self.extras_mouse(button, true); + self.mod_mouse_key(button, true); self.extras_mouse(button, false); + self.mod_mouse_key(button, false); self.play_mouse(button, true)?; self.play_mouse(button, false)?; } @@ -612,6 +612,7 @@ impl Game<'_> { "font" => Page::Font, "packs" => Page::Packs, "mods" => Page::Mods, + "shader-packs" => Page::ShaderPacks, "graphics" => Page::Graphics, "graphics-advanced" => Page::GraphicsAdvanced, "extras" => Page::Extras, @@ -625,6 +626,10 @@ impl Game<'_> { } self.open_options(self.title.is_some()); self.ui.options.show(page); + if page == Page::ShaderPacks { + self.settings.shader_packs = + horizon_client::shader_pack_list::scan(&Self::shader_packs_dir()); + } ok() } "chat-log" => { diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 61e2b2f05..16e7fc6e7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -415,6 +415,13 @@ impl Game<'_> { ], ); } + // Horizon's own: the shader pack's GPU time per pass (an empty group would move others). + let pass_lines = self.renderer.as_ref().map_or_else(Vec::new, |r| { + debug_overlay::shader_pass_lines(&r.shader_pass_times()) + }); + if !pass_lines.is_empty() { + d.group("shader pack", pass_lines); + } // tps: DebugEntryTps for local and remote connections. if self.player.is_some() { let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64); diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index a04196b69..4d21f5288 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -1,24 +1,22 @@ -//! 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. +//! Horizon's extras in the game (`docs/extras.md`); a mod's minimap +//! (`render.set-minimap`: its tiles, image and HUD) and zoom (`render.set-zoom`) on the camera; 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::{Corner, Cps, FpsCounter, fov_target}, + extras_hud::{self, Corners}, hud::{HudBatch, MINIMAP_SPRITE}, - keybinds, minimap::{self, Layer, Minimap, View}, multiplayer, reconnect::{Retry, Tracker}, title::Mode, }; use std::time::Duration; -use winit::{event::MouseButton, keyboard::KeyCode}; +use winit::event::MouseButton; #[derive(Default)] pub(super) struct ExtrasState { - zoom: Zoom, fps: FpsCounter, /// Left and right mouse buttons: held, and their clicks. mouse: [bool; 2], @@ -36,42 +34,16 @@ impl Game<'_> { fn extras_now(&self) -> f64 { self.started.elapsed().as_secs_f64() } - fn zoom_key(&self) -> Option { - let e = &self.settings.extras; - e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten() - } - /// A key press or release. The zoom key zooms only while playing with - /// no text open; the key itself always goes on to the screen and the key - /// binds, as a vanilla key mapping's would. - pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) { - if self.zoom_key() != Some(key) { - return; - } - let playing = self.screen == Screen::Playing - && self.title.is_none() - && self.sign_edit.is_none() - && self.book.is_none(); - let level = self.settings.extras.zoom_level; - self.extras.zoom.key(pressed, repeat, playing, level); - } - /// Wheel steps while playing; true when zooming took them from the hotbar. - pub(super) fn extras_scroll(&mut self, steps: f32) -> bool { - self.settings.extras.zoom && self.extras.zoom.scroll(steps) - } - /// Mouse buttons while playing, for zoom and the keystroke overlay. + /// Mouse buttons while playing, for mods' clicks. pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) { - let e = &self.settings.extras; - if e.zoom && e.zoom_key == keybinds::mouse_name(button) { - self.extras.zoom.key(pressed, false, true, e.zoom_level); - } let i = match button { MouseButton::Left => 0, MouseButton::Right => 1, _ => 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); } @@ -81,15 +53,12 @@ impl Game<'_> { // Under agent control the window may lack focus without pausing. let focused = self.focused || self.control.is_some(); let playing = self.screen == Screen::Playing && self.title.is_none() && focused; - if !playing || !self.settings.extras.zoom { - self.extras.zoom.release(); - } if !playing { 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 { @@ -159,25 +128,29 @@ impl Game<'_> { } Ok(()) } - /// The minimap's view of the player, if it shows. - fn minimap_view(&self) -> Option { - let e = &self.settings.extras; + /// The minimap a mod shows (`render.set-minimap`): its corner, its side + /// in GUI pixels and its view of the player. + fn minimap_shown(&self) -> Option<(Corner, f32, View)> { let p = self.player.as_ref()?; - let shown = e.minimap && self.title.is_none() && !self.ui.hide_gui; - shown.then_some(View { + if self.title.is_some() || self.ui.hide_gui { + return None; + } + let m = self.mod_minimap()?; + let view = View { x: p.position.x, z: p.position.z, yaw: self.yaw, - rotate: e.minimap_rotate, - blocks_per_pixel: e.minimap_zoom, - round: e.minimap_round, - }) + rotate: m.rotate, + blocks_per_pixel: m.blocks_per_pixel, + round: m.round, + }; + Some((m.corner, m.size, view)) } /// Refresh the minimap's tiles within the frame budget, recompose its /// image when the view or a tile changed, and queue the upload. fn update_minimap(&mut self) { - let Some(view) = self.minimap_view() else { - if !self.settings.extras.minimap || self.player.is_none() { + let Some((_, _, view)) = self.minimap_shown() else { + if self.mod_minimap().is_none() || self.player.is_none() { self.extras.minimap.clear(); self.extras.minimap_dim = None; } @@ -225,24 +198,12 @@ impl Game<'_> { rgba: self.extras.minimap.image.clone(), }); } - /// The zoom in effect (1 unless the key is held). - 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). + /// A mod's zoom in effect (`render.set-zoom`): (factor, smooth, turning + /// scale); none is 1. 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, - } + self.mod_zoom().map_or((1.0, true, 1.0), |z| { + (z.factor, z.smooth, f64::from(z.turn)) + }) } /// The field-of-view modifier target, divided by a smooth zoom. pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 { @@ -262,21 +223,18 @@ impl Game<'_> { pub(super) fn zoom_turn_scale(&self) -> f64 { 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. + /// 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 { + let map = self.minimap_shown(); + if map.is_none() && !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()); let atlas = &self.gui.atlas; - if let Some(view) = self.minimap_view() + if let Some((map_corner, map_size, view)) = map && visible(map_corner) && !self.extras.minimap.image.is_empty() && let Some(image) = atlas.sprites.get(MINIMAP_SPRITE).copied() @@ -295,32 +253,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/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 29dfc91d2..76839ffd1 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -38,6 +38,9 @@ pub(super) struct GuestPlay { use_delay: u32, /// The shield's ItemCooldowns entry: an axe disabled it for this many ticks. pub(super) shield_cooldown: u32, + /// `ServerGamePacketListenerImpl.dropSpamThrottler` (`TickThrottler(20, 1480)`): 20 for each + /// item a creative player drops from the creative screen, one less each tick. + creative_drops: u32, /// The guest's `Player.getCooldowns()` (`Game::cooldowns` for its turn). pub(super) cooldowns: horizon_client::cooldowns::Cooldowns, attack_ticks: u32, @@ -1086,6 +1089,35 @@ impl Game<'_> { } S::MoveVehicle(p) => self.guest_move_vehicle(host, conn, &p), S::PaddleBoat(p) => self.guest_paddle_boat(host, conn, [p.left, p.right]), + // handleSetCreativeModeSlot's drop: a slot below 0 is a stack thrown out of the + // creative screen (`handleCreativeModeItemDrop`), dropped from the player's hand. + S::SetCreativeModeSlot(p) if p.slot < 0 => { + if !host.hub.guests[gi].creative() { + return; + } + let Some(stack) = self.item_from_network(host, &p.item) else { + return; + }; + if stack.count + > self + .res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack) + { + return; + } + let play = host.play.entry(conn).or_default(); + if play.creative_drops >= 1480 { + eprintln!( + "Player {} was dropping items too fast in creative mode, ignoring.", + host.hub.guests[gi].name + ); + return; + } + play.creative_drops += 20; + self.as_guest(host, conn, |g| g.player_drop(stack)); + } S::SetCreativeModeSlot(p) => { let g = &mut host.hub.guests[gi]; if !g.creative() || !(0..46).contains(&p.slot) { @@ -1805,6 +1837,7 @@ impl Game<'_> { // Player.tick's ItemCooldowns.tick, once a tick for each player // (the shield an axe disabled, a thrown pearl). play.shield_cooldown = play.shield_cooldown.saturating_sub(1); + play.creative_drops = play.creative_drops.saturating_sub(1); // ServerItemCooldowns.onCooldownEnded: a finished entry is told to // the guest (a duration of 0 removes it). for group in play.cooldowns.tick() { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index b76bafd64..1539ce641 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -33,7 +33,7 @@ fn recipe_matches(condition: &Value, id: &str) -> bool { impl Game<'_> { /// `Level.setBlock` of one boolean property of the block at `pos`. - fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) { + pub(crate) fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) { let registry = self.pack.assets.registry; let old = self.world.block(pos.0, pos.1, pos.2); let Some(mut state) = registry.state(old).cloned() else { diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 199669957..10faf6a81 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -28,6 +28,9 @@ impl Game<'_> { pub(super) fn mod_zoom(&self) -> Option { None } + pub(super) fn mod_minimap(&self) -> Option { + None + } } /// A mod's zoom (`render.set-zoom`), clamped by the runtime. @@ -38,6 +41,16 @@ pub(super) struct ModZoom { pub(super) turn: f32, } +/// A mod's minimap (`render.set-minimap`), clamped by the runtime. +#[derive(Clone, Copy)] +pub(super) struct ModMinimap { + pub(super) corner: horizon_client::extras::Corner, + pub(super) size: f32, + pub(super) blocks_per_pixel: f32, + pub(super) rotate: bool, + pub(super) round: bool, +} + #[cfg(feature = "mods")] impl Game<'_> { /// The main hand's stack as `input` shows it; none when it is empty. @@ -147,4 +160,22 @@ impl Game<'_> { turn: z.turn, }) } + /// The minimap the first mod showing one asks for. + pub(super) fn mod_minimap(&self) -> Option { + use horizon_client::extras::Corner; + use horizon_mods::RenderCorner; + let m = self.mods.mods.minimap()?; + Some(ModMinimap { + corner: match m.corner { + RenderCorner::TopLeft => Corner::TopLeft, + RenderCorner::TopRight => Corner::TopRight, + RenderCorner::BottomLeft => Corner::BottomLeft, + RenderCorner::BottomRight => Corner::BottomRight, + }, + size: m.size, + blocks_per_pixel: m.blocks_per_pixel, + rotate: m.rotate, + round: m.round, + }) + } } diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 2335891d5..bbd0261b9 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -64,6 +64,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, /// Playing at the last frame, for `mod_input_frame`. #[cfg(feature = "mods")] pub(super) playing: bool, 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..bd277033e --- /dev/null +++ b/crates/horizon-client/src/game/moved_extras.rs @@ -0,0 +1,122 @@ +//! 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()); + // The install wrote the key to horizon-mods.txt; + // the settings save below must keep it. + let keys = self.settings.mods.keys.entry(m.id.to_owned()).or_default(); + for (name, key) in m.keys(&self.settings.extras) { + keys.entry(name.to_owned()).or_insert(key); + } + self.settings.mods.keys.retain(|_, k| !k.is_empty()); + 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/game/native_shaders.rs b/crates/horizon-client/src/game/native_shaders.rs index 62aaafc42..e72892b0e 100644 --- a/crates/horizon-client/src/game/native_shaders.rs +++ b/crates/horizon-client/src/game/native_shaders.rs @@ -1,7 +1,6 @@ -//! Horizon's own shader packs in the game (docs/shaders.md), for development until the Shader -//! Packs page exists: `HORIZON_SHADER_PACK=` naming one in `shaderpacks/` (a folder with -//! `horizon-shaders.toml`, or a `.hshader`) runs it once it passes `horizon_shader_api::check`. -//! The pack is looked at twice a second: a saved file is checked and the pack rebuilt, and a +//! Horizon's own shader packs in the game (docs/shaders.md): the pick in `shaderpacks/` (a +//! folder with `horizon-shaders.toml`, or a `.hshader`; `game/shader_packs.rs`) runs once it +//! passes `horizon_shader_api::check`. The pack is looked at twice a second: a saved file is checked and the pack rebuilt, and a //! pack that fails is refused with its problems in the chat while the last good one keeps //! drawing. @@ -21,11 +20,22 @@ const RED: u32 = 0xFF5555; #[derive(Default)] pub(super) struct NativeShaders { + /// The pack's name in `shaderpacks/`, of either kind (`game/shader_packs.rs`); empty: none. + pub picked: String, /// The pack's files when it was last read (`fingerprint`). stamp: Option, looked: Option, } +impl NativeShaders { + pub fn picking(name: &str) -> Self { + Self { + picked: name.to_owned(), + ..Self::default() + } + } +} + impl Game<'_> { /// Builds the pack at `path` when its files changed since it was last read. pub(super) fn tick_native_shader_pack(&mut self, path: &Path) { diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index a30cf822a..353ad216c 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -270,6 +270,18 @@ impl Game<'_> { self.portals.player.set_inside(pos, PLAYER_DELAY); self.portals.client_inside = true; } + /// The same on a server's client: `Entity.canUsePortal` (alive, not a + /// passenger), then only the client's `setAsInsidePortal`, which drives + /// the confusion effect (`client_portal_effect`). + pub(super) fn client_inside_nether_portal(&mut self) { + let alive = self + .player + .as_ref() + .is_some_and(|p| !p.health.dead_or_dying()); + if alive && self.riding.is_none() { + self.portals.client_inside = true; + } + } /// `ServerPlayer.handlePortal` (not while changing dimension: there is no /// player then). Players wait `players_nether_portal_default_delay` /// ticks, or the creative delay with invulnerable abilities. diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 0e385e25c..243eced5c 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -57,14 +57,7 @@ impl Game<'_> { .map(str::trim) .filter(|v| !v.is_empty()) .ok_or("options-set KEY VALUE: missing the value")?; - let mut file = self.settings.to_file(); - file.set_text(key, value)?; - let mut settings = horizon_client::settings::Settings::from_file(file); - // Horizon's own files are not in options.txt. - std::mem::swap(&mut settings.horizon, &mut self.settings.horizon); - std::mem::swap(&mut settings.controller, &mut self.settings.controller); - std::mem::swap(&mut settings.extras, &mut self.settings.extras); - self.settings = settings; + self.settings = self.settings.with_option(key, value)?; // As the options screen applies a change. self.handle_option_events(vec![Event::Changed])?; match *key { @@ -85,6 +78,10 @@ impl Game<'_> { .unwrap_or_default() .join("options.txt") } + /// `shaderpacks/` beside `options.txt`. + pub(super) fn shader_packs_dir() -> std::path::PathBuf { + Self::options_path().with_file_name(horizon_client::shader_pack_list::DIR) + } pub(super) fn gui_size(&self) -> (f32, f32) { let size = self .renderer @@ -237,6 +234,17 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::ListShaderPacks => { + self.settings.shader_packs = + horizon_client::shader_pack_list::scan(&Self::shader_packs_dir()); + } + // Saved; the next frame's `shader_pack_inputs` loads the pick. + Event::ShaderPack => self.settings.save(&Self::options_path()), + Event::OpenShaderPackFolder => { + let dir = Self::shader_packs_dir(); + let _ = std::fs::create_dir_all(&dir); + super::packs::open_folder(&dir); + } Event::ModSettings(i) => self.open_mod_screen(i, true), Event::Credits => self.open_win_screen(false, super::win::Finish::Options), } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3a2dd1d69..07ab0c80d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -6,11 +6,12 @@ //! clicks). The player still moves with the local physics, as the vanilla //! client predicts its own movement; the server stays authoritative for //! everything else. +use super::remote_chunks::{ChunkDecoder, ChunkFormat, Next}; use super::{Dim, Game, Mining, Screen}; use horizon_client::first_person::{Hand, SwingAnimation}; use horizon_client::{ Result, - chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, + chunk::{Chunk, SECTIONS}, containers::{BlockEntity, Furnace, FurnaceKind}, entities::{Experience, ExperienceOrb, ItemEntity}, hud::{HudBatch, rgba}, @@ -25,11 +26,7 @@ use horizon_client::{ tab_list::SPECTATOR, world::World, }; -use horizon_core::{ - geometry::Vec3, - paletted::{PalettedContainer, Strategy}, - random::RandomSource, -}; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ entity_data::{ITEM_ENTITY_ITEM, Value}, item::{Hashed, Stack}, @@ -64,9 +61,6 @@ fn menu_title(tag: &Tag) -> horizon_client::text::Text { remote_text(tag).resolve_legacy() } -/// A section's sky and block light layers from the wire. -type LightLayers = (Option>, Option>); - /// Streaming needs a generator; a server world never generates. struct NoTerrain; impl ChunkGenerator for NoTerrain { @@ -104,6 +98,14 @@ fn place_interpolated(m: &mut Mob, at: PosRot) { m.head_pitch = (at.pitch % 360.0).clamp(-90.0, 90.0); } +/// What the network thread delivered, in order: an event, or a chunk packet +/// handed to the decoder (with the format it decodes with), whose column +/// comes back from `ChunkDecoder::next`. +enum Received { + Event(Event), + Chunk(Arc), +} + pub(super) struct Remote { pub session: Session, pub brand: String, @@ -114,8 +116,11 @@ pub(super) struct Remote { status: String, pub(super) entity_id: i32, dimension: DimensionType, - biome_map: Vec, - biome_bits: u8, + /// What chunk packets decode with (the dimension's height and sky, the + /// biome registry); replaced whenever one of them changes. + pub(super) chunk_format: Arc, + /// Decodes chunk packets as they arrive, off the frame. + decoder: ChunkDecoder, view_distance: i32, sequence: i32, position_sender: horizon_client::player_sync::PositionSender, @@ -200,7 +205,7 @@ pub(super) struct Remote { chunk_center: (i32, i32), /// Received events a frame left for the next one, in order, and when /// the oldest of them first waited (`poll_remote`). - backlog: VecDeque, + backlog: VecDeque, backlog_since: Option, /// `ClientboundTransferPacket`'s target: when the connection ends the /// game connects here, the stored cookies carried over (`TransferState`). @@ -210,11 +215,12 @@ pub(super) struct Remote { /// The time a frame spends on chunk packets before it leaves the rest of /// the received events for the next frame. A batch of 25 to 60 columns /// (0.1 ms each on an M4 Pro) all in one frame was a 3 to 8 ms frame every -/// time the player crossed a chunk border at 32 chunks. +/// time the player crossed a chunk border at 32 chunks; they decode on the +/// chunk decoder's thread now, and the frame only inserts them. const CHUNK_PACKETS_PER_FRAME: Duration = Duration::from_millis(1); /// Events that have waited this long are all handled in the next frame, -/// whatever their cost: the packets after a slow machine's chunks never -/// wait more than a tick. +/// whatever inserting their columns costs, up to a column still decoding: +/// the packets after a slow machine's chunks don't wait on its frames. const BACKLOG_LIMIT: Duration = Duration::from_millis(50); /// The open menu name of a server's horse inventory, then its chest's /// columns (the packet names no `MenuType`). @@ -420,8 +426,12 @@ impl Game<'_> { status: "Connecting to the server...".into(), entity_id: 0, dimension: DimensionType::vanilla("minecraft:overworld"), - biome_map: Vec::new(), - biome_bits: 7, + chunk_format: Arc::new(ChunkFormat::new( + &DimensionType::vanilla("minecraft:overworld"), + Vec::new(), + 7, + )), + decoder: ChunkDecoder::new(), view_distance: self.settings.render_distance, sequence: 0, position_sender: Default::default(), @@ -741,25 +751,63 @@ impl Game<'_> { /// client's packet processor), in order. Chunk packets get /// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from /// the next chunk packet on wait for the next frame, unless they have - /// already waited `BACKLOG_LIMIT`. + /// already waited `BACKLOG_LIMIT`. A chunk packet still decoding holds + /// back what follows it. pub(super) fn poll_remote(&mut self) -> Result<()> { let Some(r) = self.remote.as_mut() else { return Ok(()); }; let mut events = std::mem::take(&mut r.backlog); - events.extend(r.session.poll()); + // Chunk packets start decoding now; the frame that reaches one in + // order inserts its column. + for event in r.session.poll() { + events.push_back(match event { + Event::Packet(p) if matches!(*p, C::LevelChunkWithLight(_)) => { + match r.decoder.submit(r.chunk_format.clone(), p) { + None => Received::Chunk(r.chunk_format.clone()), + Some(p) => Received::Event(Event::Packet(p)), + } + } + event => Received::Event(event), + }); + } let overdue = r .backlog_since .is_some_and(|since| since.elapsed() >= BACKLOG_LIMIT); let mut chunks = Duration::ZERO; - while let Some(event) = events.pop_front() { - let chunk = - matches!(&event, Event::Packet(p) if matches!(**p, C::LevelChunkWithLight(_))); + while let Some(item) = events.pop_front() { + let chunk = matches!(item, Received::Chunk(_)); if chunk && !overdue && chunks >= CHUNK_PACKETS_PER_FRAME { - events.push_front(event); + events.push_front(item); break; } let started = chunk.then(Instant::now); + let event = match item { + Received::Event(event) => event, + Received::Chunk(format) => { + // A column still decoding waits for the next frame, with + // what came after it, overdue or not. + let Some(next) = self.remote.as_ref().map(|r| r.decoder.next()) else { + break; + }; + let (packet, column) = match next { + Next::Ready(decoded) => decoded, + Next::Decoding => { + events.push_front(Received::Chunk(format)); + break; + } + Next::Lost => { + log::warn!("Horizon: the chunk decoder stopped; a column is missing"); + continue; + } + }; + if let C::LevelChunkWithLight(p) = *packet { + self.remote_chunk(&p, Some((&format, column))); + } + chunks += started.map_or(Duration::ZERO, |t| t.elapsed()); + continue; + } + }; match event { Event::Status(s) => { if let Some(r) = self.remote.as_mut() { @@ -915,8 +963,8 @@ impl Game<'_> { }) .unwrap_or_default(); if let Some(r) = self.remote.as_mut() { - r.biome_bits = ceil_log2(biomes.len()); - r.biome_map = biomes; + let bits = ceil_log2(biomes.len()); + r.chunk_format = Arc::new(ChunkFormat::new(&r.dimension, biomes, bits)); r.registries = registries; } } @@ -927,6 +975,7 @@ impl Game<'_> { }; let dimension = r.registries.dimension(spawn.dimension_type); let same = r.dimension.name == dimension.name && keep_world; + r.chunk_format = Arc::new(r.chunk_format.with_dimension(&dimension)); r.dimension = dimension; r.game_mode = spawn.game_type; r.loaded_sent = false; @@ -989,145 +1038,10 @@ impl Game<'_> { self.apply_settings(); } - /// LevelChunkSection data into the client's fixed -64..320 column. - fn remote_chunk(&self, p: &play::LevelChunkWithLight) -> std::result::Result { - let r = self.remote.as_ref().ok_or("no connection")?; - let sections = p - .chunk - .sections(r.dimension.sections(), 16, r.biome_bits) - .map_err(|e| e.to_string())?; - let mut chunk = Chunk::empty(p.x, p.z); - let offset = (r.dimension.min_y - MIN_Y).div_euclid(16); - // Biome table index per quart cell of the dimension's own sections. - let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len()); - for (i, s) in sections.iter().enumerate() { - let target = offset + i as i32; - let mut cells = [0u32; 64]; - for (j, cell) in cells.iter_mut().enumerate() { - *cell = u32::from( - r.biome_map - .get(s.biomes.get(j) as usize) - .copied() - .unwrap_or(0), - ); - } - biome_cells.push(cells); - if !(0..SECTIONS as i32).contains(&target) { - continue; - } - // A global section is as wide as the server's registry: 16 bits - // from a vanilla server, wider from a Horizon host with the same - // content mods. Read it at that width, then widen it to ours. - let ours = block_strategy(); - let strategy = if ours.wire_has_palette(s.states.bits) { - ours - } else { - Strategy::blocks(s.states.bits) - }; - let palette = s.states.palette.iter().map(|&p| p as u32).collect(); - let words = s.states.data.iter().map(|&w| w as u64).collect(); - let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) - .map_err(|e| e.to_string())?; - if strategy.global_bits != ours.global_bits { - let mut values = [0u32; 4096]; - blocks.unpack(&mut values); - // Ids past our registry (a host with mods we lack) read as air. - let limit = 1u64 << ours.global_bits; - for v in &mut values { - if u64::from(*v) >= limit { - *v = 0; - } - } - blocks = PalettedContainer::from_values(ours, &values); - } - let mut section = Section { - blocks, - biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells), - light: Light::Uniform(0xF0), - }; - section.compact(); - chunk.sections[target as usize] = Arc::new(section); - } - // Sections outside the dimension's range take its nearest biomes - // (the column's top or bottom cell layer repeated). - if !biome_cells.is_empty() { - let last = biome_cells.len() - 1; - for si in 0..SECTIONS as i32 { - let i = si - offset; - if (0..sections.len() as i32).contains(&i) { - continue; - } - let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) }; - let mut cells = [0u32; 64]; - for (j, cell) in cells.iter_mut().enumerate() { - *cell = biome_cells[edge][layer * 16 + j % 16]; - } - Arc::make_mut(&mut chunk.sections[si as usize]).biomes = - PalettedContainer::from_values(BIOME_STRATEGY, &cells); - } - } - // ClientPacketListener.applyLightData: the column keeps the light - // the server sent; nothing is relit. - let (layers, above) = self.wire_light(&p.light); - let sky = r.dimension.has_skylight; - horizon_client::light::light_from_layers(&mut chunk, &layers, above, sky); - Ok(chunk) - } - /// `ClientPacketListener.readSectionList`: the sky and block layers of a - /// light packet, by section of the client's column, and the sky light - /// above the column's top section (from the light section just above - /// it, else open sky). - fn wire_light( - &self, - light: &horizon_protocol::chunk::LightData, - ) -> (Vec, [u8; 256]) { - let mut layers: Vec = vec![(None, None); SECTIONS]; - let Some(r) = self.remote.as_ref() else { - return (layers, [0; 256]); - }; - let sky = r.dimension.has_skylight; - let mut above = [if sky { 15 } else { 0 }; 256]; - // Light section b is the dimension's section b - 1. - let first = (r.dimension.min_y - MIN_Y).div_euclid(16) - 1; - for (b, layer) in light - .layers(r.dimension.sections() + 2) - .into_iter() - .enumerate() - { - let si = first + b as i32; - if (0..SECTIONS as i32).contains(&si) { - layers[si as usize] = layer; - } else if si == SECTIONS as i32 - && sky - && let Some(l) = &layer.0 - { - for (i, a) in above.iter_mut().enumerate() { - *a = (l[i >> 1] >> ((i & 1) * 4)) & 15; - } - } - } - (layers, above) - } - /// `handleLightUpdatePacket`: the sections it names take its light. - fn remote_light_update(&mut self, p: &play::LightUpdate) { - let Some(sky) = self.remote.as_ref().map(|r| r.dimension.has_skylight) else { - return; - }; - if !self.world.chunks.contains_key(&(p.x, p.z)) { - return; - } - let (layers, _) = self.wire_light(&p.light); - let Some(chunk) = self.world.chunks.get_mut(&(p.x, p.z)) else { - return; - }; - let changed = - horizon_client::light::update_light_layers(Arc::make_mut(chunk), &layers, sky); - Streaming::light_updated(&mut self.world, p.x, p.z, &changed); - } /// `ClientChunkCache.Storage.inRange`: within the storage around the /// view centre, `calculateStorageRange` (the server's radius, at least /// two, plus three) chunks each way. - fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool { + pub(super) fn remote_chunk_in_range(&self, x: i32, z: i32) -> bool { self.remote.as_ref().is_none_or(|r| { let range = r.view_distance.max(2) + 3; (x - r.chunk_center.0).abs() <= range && (z - r.chunk_center.1).abs() <= range @@ -1135,29 +1049,33 @@ impl Game<'_> { } /// The columns a moved or resized storage no longer holds. fn drop_remote_chunks_out_of_range(&mut self) { - let gone: Vec<(i32, i32)> = self + let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> = self .world .chunks .keys() .copied() .filter(|&(x, z)| !self.remote_chunk_in_range(x, z)) .collect(); - for (x, z) in gone { + if gone.is_empty() { + return; + } + for &(x, z) in &gone { self.streaming.forget(&mut self.world, x, z); - self.world - .block_entities - .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); if let Some(renderer) = self.renderer.as_mut() { for sy in 0..SECTIONS as i32 { renderer.remove((x, sy, z)); } } } + // One pass for all of them. + self.world + .block_entities + .retain(|k, _| !gone.contains(&(k.0 >> 4, k.2 >> 4))); } /// `handleBlockEntityData`: the block entity at `pos`, when it is of the /// packet's type, loads the tag (`loadWithComponents`); an empty tag /// changes nothing. - fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) { + pub(super) fn remote_block_entity_data(&mut self, pos: [i32; 3], kind: i32, tag: &Tag) { let key = (pos[0], pos[1], pos[2]); let Some(name) = self .remote @@ -1248,7 +1166,7 @@ impl Game<'_> { } } /// Keep the renderable block entities (chests, furnaces) in step with blocks. - fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { + pub(super) fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { let name = self.res.facts().get(state).name.clone(); match BlockEntity::for_block(&name) { Some(entity) => { @@ -1704,36 +1622,7 @@ impl Game<'_> { }) .clamp(-90.0, 90.0); } - // ClientChunkCache.replaceWithPacketData: a column outside the - // storage around the view centre is ignored. - C::LevelChunkWithLight(p) if !self.remote_chunk_in_range(p.x, p.z) => { - log::warn!( - "Ignoring chunk since it's not in the view range: {}, {}", - p.x, - p.z - ); - } - C::LevelChunkWithLight(p) => match self.remote_chunk(&p) { - Ok(chunk) => { - let (x, z) = (p.x, p.z); - self.streaming.insert_remote(&mut self.world, chunk); - self.world - .block_entities - .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); - for info in &p.chunk.block_entities { - let pos = ( - x * 16 + i32::from(info.packed_xz as u8 >> 4), - i32::from(info.y), - z * 16 + i32::from(info.packed_xz as u8 & 15), - ); - let state = self.world.block(pos.0, pos.1, pos.2); - self.sync_block_entity(pos, state); - // LevelChunk.replaceWithPacketData: the block entity loads its update tag. - self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag); - } - } - Err(e) => log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z), - }, + C::LevelChunkWithLight(p) => self.remote_chunk(&p, None), C::LightUpdate(p) => self.remote_light_update(&p), C::ForgetLevelChunk(p) => { let [x, z] = p.pos; @@ -3343,6 +3232,12 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.swim", Some(feet), volume, pitch); } + // NetherPortalBlock.entityInside on the client's own level: + // the portal overlay and its trigger sound (the server moves + // the player). + horizon_client::motion::MotionEvent::InsidePortal { .. } => { + self.client_inside_nether_portal(); + } _ => {} } } @@ -4828,6 +4723,34 @@ impl Game<'_> { carried, })); } + /// `CreativeModeInventoryScreen.slotClicked` outside the window: the server knows nothing of + /// a stack picked from the creative screen, so the carried stack (an item tab's right click: + /// one of it) is dropped through `handleCreativeModeItemDrop`, a SetCreativeModeSlot to slot + /// -1, and the hand swings as `Player.drop` predicts. + pub(super) fn remote_creative_drop(&mut self, right: bool) { + let one = right && !self.creative_inventory_open(); + let Some(carried) = self.carried.as_mut() else { + return; + }; + let thrown = if one && carried.count > 1 { + carried.count -= 1; + ItemStack { + count: 1, + ..carried.clone() + } + } else { + self.carried.take().expect("carried") + }; + if !self.creative { + return; + } + self.swing_arm(); + let item = self.to_network(&Some(thrown)); + self.send(S::SetCreativeModeSlot(play::SetCreativeModeSlot { + slot: -1, + item, + })); + } pub(super) fn remote_close_container(&mut self) { let id = self .remote diff --git a/crates/horizon-client/src/game/remote_chunks.rs b/crates/horizon-client/src/game/remote_chunks.rs new file mode 100644 index 000000000..47f474619 --- /dev/null +++ b/crates/horizon-client/src/game/remote_chunks.rs @@ -0,0 +1,355 @@ +//! A server's chunk columns (`ClientboundLevelChunkWithLightPacket`): the +//! sections and light of each packet become a client column on a decoder +//! thread as soon as the packet arrives, so the frame that handles it in +//! order only inserts the result (`ClientPacketListener.handleLevelChunkWithLight`). +use super::Game; +use horizon_client::{ + chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, + streaming::Streaming, +}; +use horizon_core::paletted::{PalettedContainer, Strategy}; +use horizon_protocol::{ + chunk::{LightData, SectionLight}, + packets::play::{self, Clientbound as C}, + registry::DimensionType, +}; +use std::sync::{ + Arc, + mpsc::{self, TryRecvError}, +}; + +/// What turning a chunk packet into a client column depends on: the +/// dimension's height and sky, and the server's biome registry mapped to +/// ours. The connection replaces it when either changes, so a column decoded +/// with an older one is decoded again. +#[derive(Default)] +pub(super) struct ChunkFormat { + min_y: i32, + sections: usize, + has_skylight: bool, + biome_map: Vec, + biome_bits: u8, +} + +impl ChunkFormat { + pub(super) fn new(dimension: &DimensionType, biome_map: Vec, biome_bits: u8) -> Self { + Self { + min_y: dimension.min_y, + sections: dimension.sections(), + has_skylight: dimension.has_skylight, + biome_map, + biome_bits, + } + } + pub(super) fn with_dimension(&self, dimension: &DimensionType) -> Self { + Self::new(dimension, self.biome_map.clone(), self.biome_bits) + } + + /// LevelChunkSection data into the client's fixed -64..320 column. + fn column(&self, p: &play::LevelChunkWithLight) -> Result { + let sections = p + .chunk + .sections(self.sections, 16, self.biome_bits) + .map_err(|e| e.to_string())?; + let mut chunk = Chunk::empty(p.x, p.z); + let offset = (self.min_y - MIN_Y).div_euclid(16); + // Biome table index per quart cell of the dimension's own sections. + let mut biome_cells: Vec<[u32; 64]> = Vec::with_capacity(sections.len()); + for (i, s) in sections.iter().enumerate() { + let target = offset + i as i32; + let mut cells = [0u32; 64]; + for (j, cell) in cells.iter_mut().enumerate() { + *cell = u32::from( + self.biome_map + .get(s.biomes.get(j) as usize) + .copied() + .unwrap_or(0), + ); + } + biome_cells.push(cells); + if !(0..SECTIONS as i32).contains(&target) { + continue; + } + // A global section is as wide as the server's registry: 16 bits + // from a vanilla server, wider from a Horizon host with the same + // content mods. Read it at that width, then widen it to ours. + let ours = block_strategy(); + let strategy = if ours.wire_has_palette(s.states.bits) { + ours + } else { + Strategy::blocks(s.states.bits) + }; + let palette = s.states.palette.iter().map(|&p| p as u32).collect(); + let words = s.states.data.iter().map(|&w| w as u64).collect(); + let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) + .map_err(|e| e.to_string())?; + if strategy.global_bits != ours.global_bits { + let mut values = [0u32; 4096]; + blocks.unpack(&mut values); + // Ids past our registry (a host with mods we lack) read as air. + let limit = 1u64 << ours.global_bits; + for v in &mut values { + if u64::from(*v) >= limit { + *v = 0; + } + } + blocks = PalettedContainer::from_values(ours, &values); + } + let mut section = Section { + blocks, + biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells), + light: Light::Uniform(0xF0), + }; + section.compact(); + chunk.sections[target as usize] = Arc::new(section); + } + // Sections outside the dimension's range take its nearest biomes + // (the column's top or bottom cell layer repeated). + if !biome_cells.is_empty() { + let last = biome_cells.len() - 1; + for si in 0..SECTIONS as i32 { + let i = si - offset; + if (0..sections.len() as i32).contains(&i) { + continue; + } + let (edge, layer) = if i < 0 { (0, 0) } else { (last, 3) }; + let mut cells = [0u32; 64]; + for (j, cell) in cells.iter_mut().enumerate() { + *cell = biome_cells[edge][layer * 16 + j % 16]; + } + Arc::make_mut(&mut chunk.sections[si as usize]).biomes = + PalettedContainer::from_values(BIOME_STRATEGY, &cells); + } + } + // ClientPacketListener.applyLightData: the column keeps the light + // the server sent; nothing is relit. + let (layers, above) = self.light(&p.light); + horizon_client::light::light_from_layers(&mut chunk, &layers, above, self.has_skylight); + Ok(chunk) + } + + /// `ClientPacketListener.readSectionList`: the sky and block layers of a + /// light packet, by section of the client's column, and the sky light + /// above the column's top section (from the light section just above + /// it, else open sky). + pub(super) fn light(&self, light: &LightData) -> (Vec, [u8; 256]) { + let mut layers: Vec = vec![(None, None); SECTIONS]; + let sky = self.has_skylight; + let mut above = [if sky { 15 } else { 0 }; 256]; + // Light section b is the dimension's section b - 1. + let first = (self.min_y - MIN_Y).div_euclid(16) - 1; + for (b, layer) in light.layers(self.sections + 2).into_iter().enumerate() { + let si = first + b as i32; + if (0..SECTIONS as i32).contains(&si) { + layers[si as usize] = layer; + } else if si == SECTIONS as i32 + && sky + && let Some(l) = &layer.0 + { + for (i, a) in above.iter_mut().enumerate() { + *a = (l[i >> 1] >> ((i & 1) * 4)) & 15; + } + } + } + (layers, above) + } +} + +type Decoded = (Box, Result); + +/// One thread that decodes chunk packets in the order they arrived; its +/// results come back in that order, one per `submit`. +pub(super) struct ChunkDecoder { + jobs: mpsc::Sender<(Arc, Box)>, + done: mpsc::Receiver, +} + +impl ChunkDecoder { + pub(super) fn new() -> Self { + let (jobs, todo) = mpsc::channel::<(Arc, Box)>(); + let (finished, done) = mpsc::channel(); + // The thread ends with the connection, when `jobs` is dropped. + let spawned = std::thread::Builder::new() + .name("Chunk decoder".into()) + .spawn(move || { + // A frame waits for its columns, as it would for the render + // thread's own work. + horizon_threads::favour_current(); + for (format, packet) in todo { + let column = match &*packet { + C::LevelChunkWithLight(p) => format.column(p), + _ => Err("not a chunk packet".into()), + }; + if finished.send((packet, column)).is_err() { + break; + } + } + }); + if let Err(e) = spawned { + log::warn!("Horizon: no chunk decoder thread ({e}); chunks decode in the frame"); + } + Self { jobs, done } + } + + /// Start decoding a chunk packet with the format it arrived under. + /// Without a decoder thread the packet comes back undecoded. + pub(super) fn submit(&self, format: Arc, packet: Box) -> Option> { + self.jobs.send((format, packet)).err().map(|e| (e.0).1) + } + + /// The oldest submitted packet and its column, unless it is still + /// decoding: a frame never waits for the decoder. + pub(super) fn next(&self) -> Next { + match self.done.try_recv() { + Ok(decoded) => Next::Ready(decoded), + Err(TryRecvError::Empty) => Next::Decoding, + // The decoder thread panicked: its columns are gone. + Err(TryRecvError::Disconnected) => Next::Lost, + } + } +} + +pub(super) enum Next { + Ready(Decoded), + Decoding, + Lost, +} + +impl Game<'_> { + /// `handleLevelChunkWithLight`: the column replaces any loaded one, and + /// its block entities load their update tags. `decoded` is the column the + /// decoder made with `format`; another format since means decode again. + pub(super) fn remote_chunk( + &mut self, + p: &play::LevelChunkWithLight, + decoded: Option<(&Arc, Result)>, + ) { + // ClientChunkCache.replaceWithPacketData: a column outside the + // storage around the view centre is ignored. + if !self.remote_chunk_in_range(p.x, p.z) { + log::warn!( + "Ignoring chunk since it's not in the view range: {}, {}", + p.x, + p.z + ); + return; + } + let Some(format) = self.remote.as_ref().map(|r| r.chunk_format.clone()) else { + return; + }; + let column = match decoded { + Some((used, column)) if Arc::ptr_eq(used, &format) => column, + _ => format.column(p), + }; + let chunk = match column { + Ok(chunk) => chunk, + Err(e) => { + log::warn!("Horizon: chunk {} {}: {e}", p.x, p.z); + return; + } + }; + let (x, z) = (p.x, p.z); + self.streaming.insert_remote(&mut self.world, chunk); + self.world + .block_entities + .retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z)); + for info in &p.chunk.block_entities { + let pos = ( + x * 16 + i32::from(info.packed_xz as u8 >> 4), + i32::from(info.y), + z * 16 + i32::from(info.packed_xz as u8 & 15), + ); + let state = self.world.block(pos.0, pos.1, pos.2); + self.sync_block_entity(pos, state); + // LevelChunk.replaceWithPacketData: the block entity loads its update tag. + self.remote_block_entity_data([pos.0, pos.1, pos.2], info.kind, &info.tag); + } + } + + /// `handleLightUpdatePacket`: the sections it names take its light. + pub(super) fn remote_light_update(&mut self, p: &play::LightUpdate) { + let Some(format) = self.remote.as_ref().map(|r| r.chunk_format.clone()) else { + return; + }; + if !self.world.chunks.contains_key(&(p.x, p.z)) { + return; + } + let (layers, _) = format.light(&p.light); + let Some(chunk) = self.world.chunks.get_mut(&(p.x, p.z)) else { + return; + }; + let changed = horizon_client::light::update_light_layers( + Arc::make_mut(chunk), + &layers, + format.has_skylight, + ); + Streaming::light_updated(&mut self.world, p.x, p.z, &changed); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_protocol::chunk::{ChunkData, Paletted, Section as Wire, Strategy as Wiring}; + + /// A column of `state` with biome 1 everywhere, unlit. + fn packet(x: i32, state: i32) -> Box { + let section = Wire { + non_empty: 4096, + fluids: 0, + states: Paletted::from_values(&[state; 4096], Wiring::Blocks, 16), + biomes: Paletted::from_values(&[1; 64], Wiring::Biomes, 2), + }; + let none = LightData { + sky_mask: Vec::new(), + block_mask: Vec::new(), + empty_sky_mask: Vec::new(), + empty_block_mask: Vec::new(), + sky: Vec::new(), + block: Vec::new(), + }; + Box::new(C::LevelChunkWithLight(play::LevelChunkWithLight { + x, + z: -3, + chunk: ChunkData { + heightmaps: Vec::new(), + buffer: ChunkData::from_sections(&vec![section; 24]), + block_entities: Vec::new(), + }, + light: none, + })) + } + + /// Columns come back one per packet, in the order the packets went in, + /// as the frame would have decoded them itself. + #[test] + fn the_decoder_returns_columns_in_order() { + let overworld = DimensionType::vanilla("minecraft:overworld"); + let format = Arc::new(ChunkFormat::new(&overworld, vec![0, 7, 9], 2)); + let decoder = ChunkDecoder::new(); + for x in 0..20 { + assert!(decoder.submit(format.clone(), packet(x, 1 + x)).is_none()); + } + for x in 0..20 { + let (packet, column) = loop { + match decoder.next() { + Next::Ready(decoded) => break decoded, + Next::Decoding => std::thread::yield_now(), + Next::Lost => panic!("the decoder stopped"), + } + }; + let C::LevelChunkWithLight(p) = *packet else { + panic!("not a chunk packet"); + }; + let (column, direct) = (column.unwrap(), format.column(&p).unwrap()); + assert_eq!((column.x, column.z), (x, -3)); + for (cx, y, cz) in [(0, -64, 0), (5, 70, 9), (15, 319, 15)] { + assert_eq!(column.get(cx, y, cz), 1 + x as u32); + assert_eq!(column.get(cx, y, cz), direct.get(cx, y, cz)); + // Wire biome 1 is our biome 7. + assert_eq!(column.biome(cx, y, cz), 7); + } + } + assert!(matches!(decoder.next(), Next::Decoding)); + } +} diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index ed8ad61b7..4146283d3 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -1,7 +1,8 @@ -//! Shader packs, for development until the Shader Packs page exists: `HORIZON_SHADER_PACK=` -//! runs `shaderpacks/` (a folder or a zip beside `options.txt`) over the world; Horizon's -//! own packs go to `game/native_shaders.rs`. The -//! programs of the current dimension's folder are loaded when the dimension changes (spec 1.2). +//! Shader packs: the one picked on Options > Horizon Settings > Shader Packs, or +//! `HORIZON_SHADER_PACK=` (development; it wins over the pick), runs `shaderpacks/` +//! (a folder or a zip beside `options.txt`) over the world; Horizon's own packs go to +//! `game/native_shaders.rs`. The programs of the current dimension's folder are loaded when the +//! dimension changes (spec 1.2). use horizon_client::camera::CameraFluid; use horizon_client::gfx::pack_uniforms::PackInputs; @@ -34,25 +35,34 @@ impl Game<'_> { /// Loads the pack for the current dimension when it changed, and returns this frame's /// inputs to the pack's uniforms. pub(super) fn shader_pack_inputs(&mut self, camera: glam::DVec3, partial: f32) -> PackInputs { - let Some(name) = std::env::var_os("HORIZON_SHADER_PACK") else { + static DEV_PACK: std::sync::OnceLock> = std::sync::OnceLock::new(); + let dev = DEV_PACK.get_or_init(|| std::env::var("HORIZON_SHADER_PACK").ok()); + let picked = dev.as_deref().unwrap_or(&self.settings.horizon.shader_pack); + if self.native_shaders.picked != picked { + // Another pack, or none: drop what ran. + self.native_shaders = super::native_shaders::NativeShaders::picking(picked); + self.pack_ids = None; + if let Some(renderer) = &mut self.renderer { + renderer.drop_shader_packs(); + } + } + if picked.is_empty() { return PackInputs::default(); - }; + } + let name = picked.to_owned(); let dimension = match self.dim { Dim::Overworld => 0, Dim::Nether => -1, Dim::End => 1, }; - let path = std::env::current_dir() - .unwrap_or_default() - .join("shaderpacks") - .join(&name); + let path = Self::shader_packs_dir().join(&name); if horizon_shader_api::package::is_pack(&path) { // One of Horizon's own packs (game/native_shaders.rs). self.tick_native_shader_pack(&path); } else if let Some(renderer) = &mut self.renderer && renderer.shader_pack_dimension() != Some(dimension) { - let name = name.to_string_lossy(); + let name = name.as_str(); let started = std::time::Instant::now(); match Pack::open(&path) { Ok(pack) => { diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index f7be6241f..ed5971324 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -366,6 +366,16 @@ impl Loading { let _ = std::fs::create_dir_all(&dir); packs::open_folder(&dir); } + Event::ListShaderPacks => { + self.settings.shader_packs = + horizon_client::shader_pack_list::scan(&Game::shader_packs_dir()); + } + Event::ShaderPack => self.save_menu_settings(), + Event::OpenShaderPackFolder => { + let dir = Game::shader_packs_dir(); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } Event::Credits => { if let Some(gui) = &self.gui { let name = self.options.as_ref().map_or_else( diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5db82b19a..78f73bc8b 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -67,7 +67,9 @@ mod end_sky; mod flat; pub mod lightning; mod lod; +mod native_pack; mod native_post; +mod native_sky; mod occlusion; mod pack_atlas; pub mod pack_draw; @@ -501,7 +503,9 @@ pub struct Renderer { /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, /// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s. - native_post: Option, + native: Option, + /// Time the shader pack's passes on the GPU (F3, or `HORIZON_SHADER_PACK_TIMING`). + pass_timing: bool, /// The entity vertices Horizon draws itself while a shader pack draws the others. pack_entity_rest: Vec, /// Set 1 of the cloud pipeline, for a shader pack's `gbuffers_clouds`. @@ -2412,7 +2416,8 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, pack_post: None, - native_post: None, + native: None, + pass_timing: pack_timing::PassTiming::logging(), pack_entity_rest: Vec::new(), cloud_bindings, pack_weather: None, @@ -2921,35 +2926,40 @@ impl Renderer { }); self.pack_post = Some((dimension, post)); if self.pack_post.as_ref().is_some_and(|p| p.1.is_some()) { - self.native_post = None; + self.native = None; } report } - /// Runs the post passes of one of Horizon's own shader packs over the world from now on - /// (`None`: no pack), with its options' values; replaces a `shaders/` pack. Returns the - /// passes' labels; on an error the passes that ran keep running. + /// Drops the running shader pack, of either kind. + pub fn drop_shader_packs(&mut self) { + self.pack_post = None; + self.native = None; + self.pack_atlas = None; + } + /// Runs the sky and post stages of one of Horizon's own shader packs from now on (`None`: + /// no pack), with its options' values; replaces a `shaders/` pack. Returns the stages' + /// labels; on an error the pack that ran keeps running. pub fn set_native_shader_pack( &mut self, pack: Option<(horizon_shader_api::Report, Vec<(String, f64)>)>, ) -> std::result::Result, String> { - let stages = pack.map(|(report, constants)| { - let post: Vec<_> = report - .stages - .into_iter() - .filter(|s| s.kind == horizon_shader_api::StageKind::Post) - .collect(); - (post, constants) - }); - let Some((post, constants)) = stages.filter(|(post, _)| !post.is_empty()) else { - self.native_post = None; + let Some((report, constants)) = pack else { + self.native = None; return Ok(Vec::new()); }; let format = self.config.format.remove_srgb_suffix(); - let post = native_post::NativePost::new(&self.device, post, &constants, format)?; - let labels = post.labels().into_iter().map(str::to_owned).collect(); - self.pack_post = None; - self.pack_atlas = None; - self.native_post = Some(post); + let (pack, labels) = native_pack::NativePack::new( + &self.device, + &self.terrain_layout, + report, + &constants, + format, + )?; + self.native = pack.draws().then_some(pack); + if self.native.is_some() { + self.pack_post = None; + self.pack_atlas = None; + } Ok(labels) } /// What a shader pack's gbuffers programs read from Horizon's geometry: the sky's, and @@ -2992,6 +3002,34 @@ impl Renderer { .terrain_inputs(self.pack_terrain_flat), ) } + /// Times the shader pack's passes on the GPU while `on` (the F3 overlay is open), or always + /// with `HORIZON_SHADER_PACK_TIMING`. + pub fn set_pass_timing(&mut self, on: bool) { + self.pass_timing = on || pack_timing::PassTiming::logging(); + } + /// The running shader pack's timer, of either kind. + fn pass_timer<'a>( + pack: &'a mut Option<(i32, Option)>, + native: &'a mut Option, + ) -> Option<&'a mut Option> { + match (pack, native) { + (Some((_, Some(post))), _) => Some(&mut post.timing), + (_, Some(native)) => Some(&mut native.timing), + _ => None, + } + } + /// Each pass of the running shader pack with its median GPU time in milliseconds, while + /// they are timed (`set_pass_timing`). + pub fn shader_pass_times(&self) -> Vec<(String, f32)> { + let timer = match (&self.pack_post, &self.native) { + (Some((_, Some(post))), _) => post.timing.as_ref(), + (_, Some(native)) => native.timing.as_ref(), + _ => None, + }; + timer + .map(pack_timing::PassTiming::medians) + .unwrap_or_default() + } /// The dimension the shader pack was last set for. pub fn shader_pack_dimension(&self) -> Option { self.pack_post.as_ref().map(|p| p.0) @@ -4015,7 +4053,15 @@ impl Renderer { // The world's targets: the screen, or the scaled target of `post`. let pack_post = !frame.title && self.pack_post.as_ref().is_some_and(|p| p.1.is_some()); // One of Horizon's own packs reads the same world target. - let native_post = !frame.title && self.native_post.is_some(); + let native_post = !frame.title && self.native.as_ref().is_some_and(|n| n.post.is_some()); + if let Some(timer) = Self::pass_timer(&mut self.pack_post, &mut self.native) + && timer.is_some() != self.pass_timing + { + *timer = self + .pass_timing + .then(|| pack_timing::PassTiming::new(&self.device, &self.queue)) + .flatten(); + } let pack_reads_world = pack_post || native_post; // The pack's program reads the vertices this frame's draws bind. let pack_draws_terrain = pack_terrain && flat_frame == self.pack_terrain_flat; @@ -4070,24 +4116,79 @@ impl Renderer { cull.bind_depth(&self.device, world_depth); } let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); + let clear = if frame.title || (frame.end_sky && !frame.underwater) { + wgpu::Color::BLACK + } else { + wgpu::Color { + r: f64::from(fog_color[0]), + g: f64::from(fog_color[1]), + b: f64::from(fog_color[2]), + a: 1.0, + } + }; + let sky_visible = sky_open(frame); + // One of Horizon's own packs: this frame's inputs; in a timed frame its sky draws in a + // pass of its own, so that it has a time of its own. + let mut native_sky_pass = false; + if !frame.title + && let Some(native) = &mut self.native + { + let size = self + .world_post + .size() + .filter(|_| scaled.is_some()) + .unwrap_or([self.config.width, self.config.height]); + native.frame.write(&self.queue, frame, size); + if let Some(t) = &mut native.timing { + t.begin(&self.device, &self.queue); + native_sky_pass = + native.sky.is_some() && t.recording() && sky_visible && frame.skybox; + } + } + if native_sky_pass + && let Some(native) = &mut self.native + && let Some(sky) = &native.sky + { + if let Some(t) = &mut native.timing { + let format = self.config.format.remove_srgb_suffix(); + t.mark(&self.device, &mut encoder, (world_view, format)); + } + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(&sky.label), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: world_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(clear), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: world_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + timestamp_writes: native.timing.as_mut().and_then(|t| t.writes(&sky.label)), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + sky.draw(&mut pass, &native.frame); + } { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, resolve_target: None, depth_slice: None, ops: wgpu::Operations { - load: wgpu::LoadOp::Clear( - if frame.title || (frame.end_sky && !frame.underwater) { - wgpu::Color::BLACK - } else { - wgpu::Color { - r: f64::from(fog_color[0]), - g: f64::from(fog_color[1]), - b: f64::from(fog_color[2]), - a: 1.0, - } - }, - ), + load: if native_sky_pass { + wgpu::LoadOp::Load + } else { + wgpu::LoadOp::Clear(clear) + }, store: wgpu::StoreOp::Store, }, })]; @@ -4110,11 +4211,19 @@ impl Renderer { ..Default::default() }); pass.set_bind_group(0, &self.group, &[]); - let sky_visible = sky_open(frame); if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { - if !frame.title && frame.skybox && !pack_draws_sky { - pass.set_pipeline(&self.sky); - pass.draw(0..3, 0..1); + if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass { + match self + .native + .as_ref() + .and_then(|n| Some((n.sky.as_ref()?, &n.frame))) + { + Some((sky, native)) => sky.draw(&mut pass, native), + None => { + pass.set_pipeline(&self.sky); + pass.draw(0..3, 0..1); + } + } } if frame.title { self.panorama.draw(&mut pass); @@ -4466,17 +4575,17 @@ impl Renderer { self.pack_post = Some((dimension, Some(post))); } else if let Some((color, depth)) = &scaled && native_post - && let Some(post) = &mut self.native_post + && let Some(native) = &mut self.native + && let Some(post) = &mut native.post { let size = self.world_post.size().unwrap_or([1, 1]); post.run( &self.device, - &self.queue, &mut encoder, (color, depth), &view_target, - frame, size, + native.timing.as_mut(), ); } else if scaled.is_some() { self.world_post.finish(&mut encoder, &view_target); @@ -4649,6 +4758,9 @@ impl Renderer { timer.submitted(&self.queue); timer.collect(&self.device, &mut self.gpu_times); } + if let Some(Some(timer)) = Self::pass_timer(&mut self.pack_post, &mut self.native) { + timer.submitted(&self.queue); + } if let Some((path, buffer)) = readback { self.screenshot_result = Some( self.write_screenshot(&path, &buffer) diff --git a/crates/horizon-client/src/gfx/native_pack.rs b/crates/horizon-client/src/gfx/native_pack.rs new file mode 100644 index 000000000..3f9206e11 --- /dev/null +++ b/crates/horizon-client/src/gfx/native_pack.rs @@ -0,0 +1,60 @@ +//! One of Horizon's own shader packs while it runs (docs/shaders.md): the frame its stages +//! read, its sky and post stages, and the timer of their passes. + +use horizon_shader_api::{Report, StageKind}; + +use super::native_post::{NativeFrame, NativePost}; +use super::native_sky::NativeSky; +use super::pack_timing::PassTiming; + +pub struct NativePack { + pub frame: NativeFrame, + pub sky: Option, + pub post: Option, + /// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`). + pub timing: Option, +} + +impl NativePack { + /// The pack of the checked stages `report` with the option values `constants`, drawing + /// onto targets of `format`; `globals` is the terrain's group 0, which the sky reads. + /// Also returns its stages' labels, in the order they draw. Errors name the stage wgpu + /// refused. + pub fn new( + device: &wgpu::Device, + globals: &wgpu::BindGroupLayout, + report: Report, + constants: &[(String, f64)], + format: wgpu::TextureFormat, + ) -> Result<(Self, Vec), String> { + let frame = NativeFrame::new(device); + let (post, others): (Vec<_>, Vec<_>) = report + .stages + .into_iter() + .partition(|s| s.kind == StageKind::Post); + let sky = others + .iter() + .find(|s| s.kind == StageKind::Sky) + .map(|stage| NativeSky::new(device, globals, &frame, stage, constants, format)) + .transpose()?; + let post = (!post.is_empty()) + .then(|| NativePost::new(device, post, constants, format, &frame)) + .transpose()?; + let mut labels: Vec = sky.iter().map(|s| s.label.clone()).collect(); + if let Some(post) = &post { + labels.extend(post.labels().into_iter().map(str::to_owned)); + } + let pack = Self { + frame, + sky, + post, + timing: None, + }; + Ok((pack, labels)) + } + + /// Whether the pack draws anything the game runs today. + pub fn draws(&self) -> bool { + self.sky.is_some() || self.post.is_some() + } +} diff --git a/crates/horizon-client/src/gfx/native_post.rs b/crates/horizon-client/src/gfx/native_post.rs index c4af862d7..89515f5db 100644 --- a/crates/horizon-client/src/gfx/native_post.rs +++ b/crates/horizon-client/src/gfx/native_post.rs @@ -3,7 +3,8 @@ //! the pack's options as pipeline constants. A pass reads bind group 3: the frame, the world's //! colour and depth, the previous pass's output and two samplers. Passes before the last write //! half-float targets of the world's size, so values over 1 carry to the next; the last draws -//! onto the screen. +//! onto the screen. Every stage of a pack reads the same `frame`, written once a frame +//! (`NativeFrame`). use glam::{Mat4, Vec3}; use horizon_shader_api::{Frame as FrameInputs, check::CheckedStage, stages::GROUP}; @@ -25,10 +26,89 @@ pub struct NativePost { targets: Option<([u32; 2], [wgpu::TextureView; 2])>, /// One bind group per pass, for these world views. groups: Option<(WorldViews, Vec)>, + /// The screen's colour format, the world target's too. + format: wgpu::TextureFormat, +} + +/// The `frame` every stage of a pack reads (group 3, binding 0), written once a frame. +pub struct NativeFrame { + pub(super) buffer: wgpu::Buffer, + /// Group 3 of the stages that read only the frame (the sky). + pub layout: wgpu::BindGroupLayout, + pub group: wgpu::BindGroup, start: std::time::Instant, frames: u32, } +/// The uniform `frame` at binding 0, read by `visibility`. +fn frame_entry(visibility: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: wgpu::BufferSize::new(size_of::() as u64), + }, + count: None, + } +} + +impl NativeFrame { + pub fn new(device: &wgpu::Device) -> Self { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Native shader pack frame"), + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Native shader pack frame"), + entries: &[frame_entry(wgpu::ShaderStages::VERTEX_FRAGMENT)], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Native shader pack frame"), + layout: &layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: buffer.as_entire_binding(), + }], + }); + Self { + buffer, + layout, + group, + start: std::time::Instant::now(), + frames: 0, + } + } + + /// Writes this frame's inputs, for a world of `size`. + pub fn write(&mut self, queue: &wgpu::Queue, frame: &Frame, size: [u32; 2]) { + let seconds = self.start.elapsed().as_secs_f32() % 3600.0; + let inputs = frame_inputs(frame, size, seconds, self.frames); + self.frames = self.frames.wrapping_add(1); + queue.write_buffer(&self.buffer, 0, bytemuck::bytes_of(&inputs)); + } +} + +/// The option values of `constants` that `module` declares as overrides (wgpu refuses others). +pub fn present_constants<'a>( + module: &naga::Module, + constants: &'a [(String, f64)], +) -> Vec<(&'a str, f64)> { + constants + .iter() + .filter(|(id, _)| { + module + .overrides + .iter() + .any(|(_, o)| o.name.as_ref() == Some(id)) + }) + .map(|(id, v)| (id.as_str(), *v)) + .collect() +} + fn texture_entry(binding: u32, sample_type: wgpu::TextureSampleType) -> wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry { binding, @@ -59,21 +139,13 @@ impl NativePost { stages: Vec, constants: &[(String, f64)], format: wgpu::TextureFormat, + frame: &NativeFrame, ) -> Result { let float = wgpu::TextureSampleType::Float { filterable: true }; let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Native shader pack post"), entries: &[ - wgpu::BindGroupLayoutEntry { - binding: 0, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Uniform, - has_dynamic_offset: false, - min_binding_size: wgpu::BufferSize::new(size_of::() as u64), - }, - count: None, - }, + frame_entry(wgpu::ShaderStages::FRAGMENT), texture_entry(1, float), texture_entry(2, wgpu::TextureSampleType::Depth), texture_entry(3, float), @@ -91,17 +163,7 @@ impl NativePost { let count = stages.len(); let mut passes = Vec::with_capacity(count); for (i, stage) in stages.into_iter().enumerate() { - let present: Vec<(&str, f64)> = constants - .iter() - .filter(|(id, _)| { - stage - .module - .overrides - .iter() - .any(|(_, o)| o.name.as_ref() == Some(id)) - }) - .map(|(id, v)| (id.as_str(), *v)) - .collect(); + let present = present_constants(&stage.module, constants); let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(&stage.label), @@ -141,12 +203,6 @@ impl NativePost { } passes.push((stage.label, pipeline)); } - let frame = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Native shader pack frame"), - size: size_of::() as u64, - usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); let sampler = |label, filter| { device.create_sampler(&wgpu::SamplerDescriptor { label: Some(label), @@ -158,13 +214,12 @@ impl NativePost { Ok(Self { passes, layout, - frame, + frame: frame.buffer.clone(), linear: sampler("Native shader pack linear", wgpu::FilterMode::Linear), nearest: sampler("Native shader pack nearest", wgpu::FilterMode::Nearest), targets: None, groups: None, - start: std::time::Instant::now(), - frames: 0, + format, }) } @@ -258,35 +313,20 @@ impl NativePost { } /// Runs the passes over the world target `world` (colour, depth) of `size`, the last onto - /// `screen`. + /// `screen`, timed by `timing` when it times this frame. pub fn run( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, world: (&wgpu::TextureView, &wgpu::TextureView), screen: &wgpu::TextureView, - frame: &Frame, - size: [u32; 2], - ) { - let seconds = self.start.elapsed().as_secs_f32() % 3600.0; - let inputs = frame_inputs(frame, size, seconds, self.frames); - self.frames = self.frames.wrapping_add(1); - self.draw(device, queue, encoder, world, screen, &inputs, size); - } - - fn draw( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - encoder: &mut wgpu::CommandEncoder, - world: (&wgpu::TextureView, &wgpu::TextureView), - screen: &wgpu::TextureView, - inputs: &FrameInputs, size: [u32; 2], + mut timing: Option<&mut super::pack_timing::PassTiming>, ) { self.prepare(device, world, size); - queue.write_buffer(&self.frame, 0, bytemuck::bytes_of(inputs)); + if let Some(t) = timing.as_deref_mut() { + t.mark(device, encoder, (world.0, self.format)); + } let Some((_, groups)) = &self.groups else { return; }; @@ -307,6 +347,7 @@ impl NativePost { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some(label), color_attachments: &attachments, + timestamp_writes: timing.as_deref_mut().and_then(|t| t.writes(label)), ..Default::default() }); pass.set_pipeline(pipeline); @@ -426,8 +467,20 @@ mod tests { .into(); let report = check(&Pack::from_files(files).unwrap()).unwrap(); let format = wgpu::TextureFormat::Rgba8Unorm; - let mut post = - NativePost::new(&device, report.stages, &[("gain".into(), 1.0)], format).unwrap(); + let frame = NativeFrame::new(&device); + queue.write_buffer( + &frame.buffer, + 0, + bytemuck::bytes_of(&FrameInputs::default()), + ); + let mut post = NativePost::new( + &device, + report.stages, + &[("gain".into(), 1.0)], + format, + &frame, + ) + .unwrap(); assert_eq!(post.labels(), ["a.wgsl", "b.wgsl"]); let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING; @@ -467,15 +520,7 @@ mod tests { ..Default::default() }); let view = screen.create_view(&Default::default()); - post.draw( - &device, - &queue, - &mut encoder, - (&color, &depth), - &view, - &FrameInputs::default(), - [4, 4], - ); + post.run(&device, &mut encoder, (&color, &depth), &view, [4, 4], None); let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4), diff --git a/crates/horizon-client/src/gfx/native_sky.rs b/crates/horizon-client/src/gfx/native_sky.rs new file mode 100644 index 000000000..9a354ed4e --- /dev/null +++ b/crates/horizon-client/src/gfx/native_sky.rs @@ -0,0 +1,426 @@ +//! The sky stage of Horizon's own shader packs (docs/shaders.md): the pack's `sky` function, +//! called for each pixel of the sky disc with vanilla's colour along its view ray. The +//! pipeline's shader is the pack's stage (`CheckedStage::source`) followed by a copy of the +//! renderer's sky (terrain.wgsl's `Globals`, `linear_fog` and sky section) whose names all +//! take a `horizon_sky_` prefix, so none can meet a pack's (the check refuses `horizon_` +//! names). It reads the renderer's globals (group 0) and the pack's frame (group 3), and +//! draws where vanilla's sky draws; the sun, moon, stars and the dark disc are drawn over it. + +use horizon_shader_api::{check::CheckedStage, stages::GROUP}; + +use super::native_post::{NativeFrame, present_constants}; + +const PREFIX: &str = "horizon_sky_"; +const TERRAIN: &str = include_str!("../terrain.wgsl"); + +/// The fragment entry that calls the pack: vanilla's colour in, an opaque colour out. +const PACK_ENTRY: &str = " +@fragment fn horizon_sky_fs_pack(in: horizon_sky_SkyOut) -> @location(0) vec4 { + let d = horizon_sky_view_ray(in.ndc); + return vec4(sky(SkyInput(d, vec4(horizon_sky_sky_along_ray(d), 1.0))).rgb, 1.0); +} +"; + +pub struct NativeSky { + pipeline: wgpu::RenderPipeline, + pub label: String, +} + +/// The text of `source` from the line starting with `start` up to (not including) the one +/// starting with `end`. +fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str { + let from = source + .find(&format!("\n{start}")) + .expect("terrain.wgsl has the section") + + 1; + let to = from + + source[from..] + .find(&format!("\n{end}")) + .expect("terrain.wgsl ends the section") + + 1; + &source[from..to] +} + +/// terrain.wgsl's sky with every name it declares (and `globals`) prefixed. +fn vanilla_sky() -> String { + let text = [ + section(TERRAIN, "struct Globals {", "@group(0) @binding(0)"), + section(TERRAIN, "fn linear_fog(", "fn apply_fog("), + section(TERRAIN, "struct SkyOut {", "// rendertype_lines"), + ] + .concat(); + let mut names = vec!["globals"]; + for line in text.lines() { + let line = line + .trim_start_matches("@vertex ") + .trim_start_matches("@fragment "); + for keyword in ["fn ", "struct ", "const "] { + if let Some(rest) = line.strip_prefix(keyword) { + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + names.push(&rest[..end]); + } + } + } + let mut out = String::with_capacity(text.len() * 2); + let mut word = String::new(); + let flush = |word: &mut String, out: &mut String| { + if names.contains(&word.as_str()) { + out.push_str(PREFIX); + } + out.push_str(word); + word.clear(); + }; + for c in text.chars() { + if c.is_ascii_alphanumeric() || c == '_' { + word.push(c); + } else { + flush(&mut word, &mut out); + out.push(c); + } + } + flush(&mut word, &mut out); + out + &format!("@group(0) @binding(0) var {PREFIX}globals: {PREFIX}Globals;\n") +} + +/// The sky shader for the pack's sky stage `source`. +fn shader_source(source: &str) -> String { + format!( + "{source}\n// Horizon's sky (terrain.wgsl)\n{}{PACK_ENTRY}", + vanilla_sky() + ) +} + +/// A sky pipeline over `module` whose fragment entry is `fragment`. +fn pipeline( + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + module: &wgpu::ShaderModule, + fragment: &str, + constants: &[(&str, f64)], + format: wgpu::TextureFormat, +) -> wgpu::RenderPipeline { + let options = wgpu::PipelineCompilationOptions { + constants, + ..Default::default() + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Native shader pack sky"), + layout: Some(layout), + vertex: wgpu::VertexState { + module, + entry_point: Some("horizon_sky_vs_sky"), + compilation_options: options.clone(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module, + entry_point: Some(fragment), + compilation_options: options, + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) +} + +/// The sky's naga module and the layout of its pipelines: `globals` at group 0, the frame +/// at group 3. +fn build( + device: &wgpu::Device, + globals: &wgpu::BindGroupLayout, + frame: &NativeFrame, + stage: &CheckedStage, +) -> Result<(naga::Module, wgpu::PipelineLayout), String> { + let text = shader_source(&stage.source); + let module = naga::front::wgsl::parse_str(&text) + .map_err(|e| format!("{}: {}", stage.file, e.emit_to_string(&text)))?; + let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] = Default::default(); + groups[0] = Some(globals); + groups[GROUP as usize] = Some(&frame.layout); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Native shader pack sky"), + bind_group_layouts: &groups, + ..Default::default() + }); + Ok((module, layout)) +} + +impl NativeSky { + /// The pipeline of the pack's sky `stage` with the option values `constants`, drawing + /// onto the world's target of `format`; `globals` is the terrain's group 0. + pub fn new( + device: &wgpu::Device, + globals: &wgpu::BindGroupLayout, + frame: &NativeFrame, + stage: &CheckedStage, + constants: &[(String, f64)], + format: wgpu::TextureFormat, + ) -> Result { + let (module, layout) = build(device, globals, frame, stage)?; + let present = present_constants(&module, constants); + let scope = device.push_error_scope(wgpu::ErrorFilter::Validation); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some(&stage.label), + source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)), + }); + let pipeline = pipeline( + device, + &layout, + &module, + "horizon_sky_fs_pack", + &present, + format, + ); + if let Some(e) = pollster::block_on(scope.pop()) { + return Err(format!("{}: {e}", stage.file)); + } + Ok(Self { + pipeline, + label: stage.label.clone(), + }) + } + + /// Draws the sky in a pass whose group 0 is the terrain's. + pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, frame: &NativeFrame) { + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(GROUP, &frame.group, &[]); + pass.draw(0..3, 0..1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_shader_api::{Frame as FrameInputs, MANIFEST, Pack, StageKind, check}; + + fn stage(sky: &str) -> CheckedStage { + let mut manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\ + [sky]\nfile = \"sky.wgsl\"\n" + .to_owned(); + if sky.contains("gain") { + manifest += "[[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\n\ + default = 1.0\nmin = 0.0\nmax = 2.0\n"; + } + let manifest = manifest.as_str(); + let files = [(MANIFEST, manifest), ("sky.wgsl", sky)] + .map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec())) + .into(); + let mut report = check(&Pack::from_files(files).unwrap()).unwrap(); + assert_eq!(report.stages[0].kind, StageKind::Sky); + report.stages.remove(0) + } + + #[test] + fn the_renderer_s_sky_takes_a_prefix_and_validates_with_a_pack() { + let sky = vanilla_sky(); + for name in [ + "Globals", + "SkyOut", + "view_ray", + "PI", + "sky_along_ray", + "linear_fog", + "fs_sky", + ] { + assert!(sky.contains(&format!("{PREFIX}{name}")), "{name}"); + } + // A pack may use the renderer's names for its own things. + let own = "override gain: f32;\nconst PI: f32 = 3.0;\nfn view_ray() -> f32 { return PI; }\n\ + fn sky(input: SkyInput) -> vec4 { return input.color * gain * view_ray(); }\n"; + let text = shader_source(&stage(own).source); + let module = naga::front::wgsl::parse_str(&text).unwrap_or_else(|e| { + panic!("{}", e.emit_to_string(&text)); + }); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::default(), + ) + .validate(&module) + .unwrap(); + } + + /// Vanilla's sky and two packs over the same globals: one that returns its input draws + /// vanilla's pixels, one that inverts them draws the inverse (and stays opaque). + #[test] + fn a_pack_gets_vanilla_s_colour_and_draws_opaque() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { + return; + }; + let (device, queue) = + pollster::block_on(adapter.request_device(&Default::default())).unwrap(); + let format = wgpu::TextureFormat::Rgba8Unorm; + let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: None, + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + let mut globals: super::super::Globals = bytemuck::Zeroable::zeroed(); + globals.inverse_view = glam::Mat4::IDENTITY.to_cols_array_2d(); + globals.misc = [0.0, 0.0, 1.0, 1.0]; + globals.fog_color = [0.2, 0.4, 0.6, 1.0]; + globals.sky_color = [0.5, 0.7, 1.0, 1.0]; + globals.fog_ends = [64.0, 0.0, 0.0, 0.0]; + let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&globals_buffer, 0, bytemuck::bytes_of(&globals)); + let globals_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &globals_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: globals_buffer.as_entire_binding(), + }], + }); + let frame = NativeFrame::new(&device); + queue.write_buffer( + &frame.buffer, + 0, + bytemuck::bytes_of(&FrameInputs::default()), + ); + + let gain = [("gain".to_owned(), 1.0)]; + let draw = |stage: &CheckedStage, vanilla: bool| -> Vec { + let sky = + NativeSky::new(&device, &globals_layout, &frame, stage, &gain, format).unwrap(); + let pipeline = if vanilla { + let (module, layout) = build(&device, &globals_layout, &frame, stage).unwrap(); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)), + }); + pipeline(&device, &layout, &module, "horizon_sky_fs_sky", &[], format) + } else { + sky.pipeline.clone() + }; + let texture = |format, usage| { + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { + width: 4, + height: 4, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats: &[], + }) + }; + let color = texture( + format, + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, + ); + let depth = texture( + wgpu::TextureFormat::Depth32Float, + wgpu::TextureUsages::RENDER_ATTACHMENT, + ); + let (color_view, depth_view) = ( + color.create_view(&Default::default()), + depth.create_view(&Default::default()), + ); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &color_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), + ..Default::default() + }); + pass.set_bind_group(0, &globals_group, &[]); + pass.set_pipeline(&pipeline); + pass.set_bind_group(GROUP, &frame.group, &[]); + pass.draw(0..3, 0..1); + } + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT * 4), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + encoder.copy_texture_to_buffer( + color.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT), + rows_per_image: Some(4), + }, + }, + color.size(), + ); + queue.submit([encoder.finish()]); + buffer + .slice(..) + .map_async(wgpu::MapMode::Read, |r| r.unwrap()); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let bytes = buffer.slice(..).get_mapped_range().unwrap().to_vec(); + (0..4) + .flat_map(|row| { + let start = row * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; + bytes[start..start + 16].to_vec() + }) + .collect() + }; + let same = stage("fn sky(input: SkyInput) -> vec4 { return input.color; }\n"); + let vanilla = draw(&same, true); + assert_eq!(draw(&same, false), vanilla); + // The top row looks up into the sky disc, the bottom one down into the fog. + assert_ne!(vanilla[..4], vanilla[vanilla.len() - 4..]); + let inverse = stage( + "override gain: f32;\nfn sky(input: SkyInput) -> vec4 { return vec4(vec3(gain) - input.color.rgb, 0.25); }\n", + ); + let inverted = draw(&inverse, false); + for (got, want) in inverted.chunks(4).zip(vanilla.chunks(4)) { + assert_eq!(got[3], 255); + for i in 0..3 { + assert!(got[i].abs_diff(255 - want[i]) <= 1, "{got:?} {want:?}"); + } + } + } +} diff --git a/crates/horizon-client/src/gfx/pack_post.rs b/crates/horizon-client/src/gfx/pack_post.rs index 19f0d7349..b9320277a 100644 --- a/crates/horizon-client/src/gfx/pack_post.rs +++ b/crates/horizon-client/src/gfx/pack_post.rs @@ -297,8 +297,8 @@ pub struct PackPost { /// with the page buffer it was made for. block_ids: Option<(wgpu::BindGroupLayout, wgpu::Buffer)>, page_groups: HashMap, - /// `HORIZON_SHADER_PACK_TIMING`: GPU time of each pass, in the log. - timing: Option, + /// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`). + pub timing: Option, /// `shaders.properties`' custom uniforms, after the frame's in `uniforms.values`. custom: horizon_shaders::Custom, atlas: Option, @@ -1430,7 +1430,7 @@ impl PackPost { draws, block_ids, page_groups: HashMap::new(), - timing: super::pack_timing::PassTiming::new(device, queue), + timing: None, custom, atlas: world.atlas.as_ref().map(|a| a.0.clone()), lightmap: world.lightmap, diff --git a/crates/horizon-client/src/gfx/pack_timing.rs b/crates/horizon-client/src/gfx/pack_timing.rs index acfdb698f..2a8dcf4a5 100644 --- a/crates/horizon-client/src/gfx/pack_timing.rs +++ b/crates/horizon-client/src/gfx/pack_timing.rs @@ -1,31 +1,53 @@ -//! Developers' aid: `HORIZON_SHADER_PACK_TIMING=1` times every pass of a shader pack on the -//! GPU, one frame in `EVERY`, and logs each pass's median every `REPORT` timed frames. The -//! frame after a timed one waits for the GPU before reading the timestamps (Metal resolves -//! them without waiting for the passes that write them), so timing slows the game. +//! GPU time of each pass of a shader pack, of either kind: shown in the F3 overlay while it is +//! open, and logged every `REPORT` timed frames with `HORIZON_SHADER_PACK_TIMING=1`. One frame +//! at a time is timed, and the CPU never waits for it: its timestamps are resolved in a later +//! frame, once the GPU has finished it (Metal resolves them without waiting for the passes that +//! write them), then read back when mapped. The next frame after that is timed again. + +use std::collections::VecDeque; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; -const EVERY: u32 = 30; const REPORT: usize = 30; /// Passes timed per frame at most (two timestamps each). const CAPACITY: u32 = 64; +/// Timed frames each pass's median is taken over. +const WINDOW: usize = 15; -pub(super) struct PassTiming { +enum Stage { + /// The next frame is timed. + Idle, + /// The frame being recorded is timed. + Recording, + /// Submitted; the flag is set once the GPU has finished it. + Running(Arc), + /// Resolved and copied; the flag is set once the copy is mapped. + Reading(Arc, u64), +} + +pub struct PassTiming { queries: wgpu::QuerySet, resolve: wgpu::Buffer, read: wgpu::Buffer, period_ns: f32, - frame: u32, - /// The passes timed in the frame being recorded or waiting to be read, in order. + stage: Stage, + /// The passes of the timed frame, in order. names: Vec, - timed: bool, - samples: Vec<(String, Vec)>, + /// Each pass's last `WINDOW` times, in milliseconds. + samples: Vec<(String, VecDeque)>, + /// Log the medians every `REPORT` timed frames. + log: bool, + /// `mark`'s pipeline, for the target format it was made for. + marker: Option<(wgpu::TextureFormat, wgpu::RenderPipeline)>, reports: usize, } impl PassTiming { + /// `None` when the device can't time passes. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option { - if std::env::var_os("HORIZON_SHADER_PACK_TIMING").is_none() - || !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) - { + if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { return None; } let size = u64::from(CAPACITY) * 2 * 8; @@ -52,51 +74,138 @@ impl PassTiming { wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, ), period_ns: queue.get_timestamp_period(), - frame: 0, + stage: Stage::Idle, names: Vec::new(), - timed: false, samples: Vec::new(), + log: Self::logging(), + marker: None, reports: 0, }) } - /// At the start of a frame: reads the last timed frame's passes, and decides whether this - /// one is timed. + /// Whether `HORIZON_SHADER_PACK_TIMING` asks for timing without the F3 overlay. + pub fn logging() -> bool { + static LOG: std::sync::OnceLock = std::sync::OnceLock::new(); + *LOG.get_or_init(|| std::env::var_os("HORIZON_SHADER_PACK_TIMING").is_some()) + } + + /// At the start of a frame's passes: moves the last timed frame along, and decides whether + /// this one is timed. pub fn begin(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { - if self.timed && !self.names.is_empty() { - self.collect(device, queue); + match &self.stage { + // A timed frame that was never submitted: time this one instead. + Stage::Recording => self.stage = Stage::Idle, + Stage::Running(done) if done.load(Ordering::Acquire) => { + let bytes = self.names.len() as u64 * 16; + let mut encoder = device.create_command_encoder(&Default::default()); + encoder.resolve_query_set( + &self.queries, + 0..self.names.len() as u32 * 2, + &self.resolve, + 0, + ); + encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes); + queue.submit([encoder.finish()]); + let mapped = Arc::new(AtomicBool::new(false)); + let flag = mapped.clone(); + self.read + .slice(..bytes) + .map_async(wgpu::MapMode::Read, move |r| { + flag.store(r.is_ok(), Ordering::Release) + }); + self.stage = Stage::Reading(mapped, bytes); + } + Stage::Reading(mapped, bytes) if mapped.load(Ordering::Acquire) => { + let bytes = *bytes; + self.collect(bytes); + self.stage = Stage::Idle; + } + _ => {} } - self.names.clear(); - self.frame += 1; - self.timed = self.frame.is_multiple_of(EVERY); + if matches!(self.stage, Stage::Idle) { + self.names.clear(); + self.stage = Stage::Recording; + } + } + + /// Whether the frame being recorded is timed. + pub fn recording(&self) -> bool { + matches!(self.stage, Stage::Recording) } /// Timestamp writes for the pass `name`, in a timed frame. pub fn writes(&mut self, name: &str) -> Option> { + let i = self.push(name)?; + Some(stamps(&self.queries, i)) + } + + /// The index of the timed frame's next pass, `name`. + fn push(&mut self, name: &str) -> Option { let i = self.names.len() as u32; - if !self.timed || i >= CAPACITY { + if !matches!(self.stage, Stage::Recording) || i >= CAPACITY { return None; } self.names.push(name.to_owned()); - Some(wgpu::RenderPassTimestampWrites { - query_set: &self.queries, - beginning_of_pass_write_index: Some(2 * i), - end_of_pass_write_index: Some(2 * i + 1), - }) + Some(i) } - fn collect(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { - // The timed frame first, then the resolve, so every timestamp is written. - _ = device.poll(wgpu::PollType::wait_indefinitely()); - let count = self.names.len() as u32 * 2; - let bytes = u64::from(count) * 8; - let mut encoder = device.create_command_encoder(&Default::default()); - encoder.resolve_query_set(&self.queries, 0..count, &self.resolve, 0); - encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.read, 0, bytes); - queue.submit([encoder.finish()]); + /// A pass that ends once everything drawn into `target` before it has, in a timed frame: + /// the next pass counts from there, not from when the GPU queued it behind them. + pub fn mark( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + (target, format): super::timing::Target, + ) { + if self.marker.as_ref().is_none_or(|(f, _)| *f != format) { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Shader pack timing mark"), + source: wgpu::ShaderSource::Wgsl(super::timing::MARKER.into()), + }); + let pipeline = super::timing::end_pipeline(device, &module, format); + self.marker = Some((format, pipeline)); + } + // An unnamed pass: its end counts, it is never listed. + let Some(i) = self.push("") else { + return; + }; + let (_, pipeline) = self.marker.as_ref().expect("made above"); + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Shader pack timing mark"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: target, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })], + timestamp_writes: Some(stamps(&self.queries, i)), + ..Default::default() + }); + pass.set_pipeline(pipeline); + pass.set_scissor_rect(0, 0, 1, 1); + pass.draw(0..3, 0..1); + } + + /// After the frame is submitted. + pub fn submitted(&mut self, queue: &wgpu::Queue) { + if !matches!(self.stage, Stage::Recording) { + return; + } + if self.names.is_empty() { + self.stage = Stage::Idle; + return; + } + let done = Arc::new(AtomicBool::new(false)); + let flag = done.clone(); + queue.on_submitted_work_done(move || flag.store(true, Ordering::Release)); + self.stage = Stage::Running(done); + } + + fn collect(&mut self, bytes: u64) { let slice = self.read.slice(..bytes); - slice.map_async(wgpu::MapMode::Read, |_| {}); - _ = device.poll(wgpu::PollType::wait_indefinitely()); let Ok(data) = slice.get_mapped_range() else { return; }; @@ -108,41 +217,91 @@ impl PassTiming { .collect(); drop(data); self.read.unmap(); - // Passes overlap on tiled GPUs (a pass begins before the one before it ends): a pass - // costs the time from the later of its beginning and the previous pass's end. - let mut previous_end = 0; - for (name, pair) in self.names.iter().zip(stamps.as_chunks::<2>().0) { - if pair[0] == 0 || pair[1] < pair[0] { + let times = pass_times(&stamps, self.period_ns); + for (name, ms) in self.names.iter().zip(times) { + let Some(ms) = ms.filter(|_| !name.is_empty()) else { continue; + }; + let i = match self.samples.iter().position(|s| s.0 == *name) { + Some(i) => i, + None => { + self.samples.push((name.clone(), VecDeque::new())); + self.samples.len() - 1 + } + }; + let window = &mut self.samples[i].1; + if window.len() == WINDOW { + window.pop_front(); } - let from = pair[0].max(previous_end).min(pair[1]); - previous_end = pair[1]; - let ms = (pair[1] - from) as f32 * self.period_ns / 1e6; - match self.samples.iter_mut().find(|s| s.0 == *name) { - Some(s) => s.1.push(ms), - None => self.samples.push((name.clone(), vec![ms])), - } + window.push_back(ms); } self.reports += 1; - if self.reports.is_multiple_of(REPORT) { - self.report(); + if self.log && self.reports.is_multiple_of(REPORT) { + let medians = self.medians(); + let total: f32 = medians.iter().map(|m| m.1).sum(); + let parts: Vec = medians + .iter() + .map(|(n, ms)| format!("{n} {ms:.3}")) + .collect(); + log::info!( + "shader pack GPU time per pass (median ms of the last {WINDOW} timed frames): {} = {total:.3}", + parts.join(", ") + ); } } - fn report(&mut self) { - let mut total = 0.0; - let mut parts = Vec::new(); - // A pass that did not run in this window (no entities, the sky out of sight) is left out. - for (name, v) in self.samples.iter_mut().filter(|s| !s.1.is_empty()) { - v.sort_by(f32::total_cmp); - let median = v[v.len() / 2]; - total += median; - parts.push(format!("{name} {median:.3}")); - v.clear(); - } - log::info!( - "shader pack GPU time per pass (median ms of {REPORT} frames): {} = {total:.3}", - parts.join(", ") - ); + /// Each pass's median time in milliseconds over its last timed frames, in the order the + /// passes first ran. + pub fn medians(&self) -> Vec<(String, f32)> { + self.samples + .iter() + .filter(|s| !s.1.is_empty()) + .map(|(name, v)| { + let mut v: Vec = v.iter().copied().collect(); + v.sort_by(f32::total_cmp); + (name.clone(), v[v.len() / 2]) + }) + .collect() + } +} + +/// Pass `i`'s beginning and end timestamps. +fn stamps(queries: &wgpu::QuerySet, i: u32) -> wgpu::RenderPassTimestampWrites<'_> { + wgpu::RenderPassTimestampWrites { + query_set: queries, + beginning_of_pass_write_index: Some(2 * i), + end_of_pass_write_index: Some(2 * i + 1), + } +} + +/// Each pass's time in milliseconds from its (beginning, end) timestamps, `None` for a pass +/// the GPU left unstamped. Passes overlap on tiled GPUs (a pass begins before the one before it +/// ends): a pass costs the time from the later of its beginning and the previous pass's end. +fn pass_times(stamps: &[u64], period_ns: f32) -> Vec> { + let mut previous_end = 0; + stamps + .as_chunks::<2>() + .0 + .iter() + .map(|&[begin, end]| { + if begin == 0 || end < begin { + return None; + } + let from = begin.max(previous_end).min(end); + previous_end = end; + Some((end - from) as f32 * period_ns / 1e6) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::pass_times; + + #[test] + fn overlapping_passes_cost_from_the_previous_end() { + // Pass 2 begins before pass 1 ends; pass 3 was never stamped. + let stamps = [1_000_000, 3_000_000, 2_000_000, 5_000_000, 0, 0]; + assert_eq!(pass_times(&stamps, 1.0), [Some(2.0), Some(2.0), None]); } } diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index 5fc566fe7..7d2b17b3b 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -60,7 +60,7 @@ struct Markers { /// The start's one thread; the end's triangle over the whole target (the /// pass's scissor keeps one pixel), shading nothing it writes. -const MARKER: &str = +pub(super) const MARKER: &str = "@vertex fn cover(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { return vec4(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0); } @@ -254,7 +254,7 @@ impl GpuTimer { } /// The end marker's pipeline for a `format` target, every write masked. -fn end_pipeline( +pub(super) fn end_pipeline( device: &wgpu::Device, module: &wgpu::ShaderModule, format: wgpu::TextureFormat, diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index d3318aab2..b51a586ab 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -261,6 +261,10 @@ pub struct Graphics { pub battery: bool, /// The graphics API (Windows only; see `GraphicsApi`). pub api: GraphicsApi, + /// The shader pack picked in `shaderpacks/` (`shader_pack_list`); empty: none. Its key is + /// not `shaderPack`, which versions before the clean-room rewrite saved and which stays + /// ignored. + pub shader_pack: String, } impl Default for Graphics { fn default() -> Self { @@ -284,6 +288,7 @@ impl Default for Graphics { fxaa: false, battery: false, api: GraphicsApi::Auto, + shader_pack: String::new(), } } } @@ -334,6 +339,7 @@ impl Graphics { "fxaa" => g.fxaa = flag(g.fxaa), "batteryMode" => g.battery = flag(g.battery), "graphicsApi" => g.api = GraphicsApi::from_name(value).unwrap_or_default(), + "pickedShaderPack" => g.shader_pack = value.to_owned(), "overlay" => { g.overlay = match value { "fps" => Overlay::Fps, @@ -348,7 +354,7 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\ngraphicsApi:{}\n", + "preset:{}\nlodDistance:{}\nfarDetail:{}\ncaveCulling:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nbatteryMode:{}\ngraphicsApi:{}\npickedShaderPack:{}\n", self.preset.name(), self.lod_distance, self.far_detail.name(), @@ -375,6 +381,7 @@ impl Graphics { bool_text(self.fxaa), bool_text(self.battery), self.api.name(), + self.shader_pack, ) } pub fn save(&self, dir: &Path) { @@ -471,6 +478,7 @@ mod tests { fxaa: true, battery: true, api: GraphicsApi::Dx12, + shader_pack: "Golden Hour".into(), }; assert_eq!(Graphics::parse(&g.serialize()), g); assert_eq!(Graphics::parse(""), Graphics::default()); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7ab6d3f61..6bf40d1f0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -127,6 +127,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; @@ -167,6 +168,7 @@ pub mod sculk; pub use horizon_server_files as server; pub mod server_packs; pub mod settings; +pub mod shader_pack_list; pub mod shadows; pub mod signs; pub mod skins; diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index f16e0e18d..394821ace 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -64,6 +64,31 @@ impl MobWorld<'_> { let b = bounds.deflate(Vec3::new(0.001, 0.001, 0.001)); let (lo, hi) = (b.min_position(), b.max_position()); let mut out = Fluids::default(); + // The eye column below, in the box but for a box thinner than the + // deflation. + let (ex, ez) = ( + ((lo.x + hi.x) / 2.0).floor() as i32, + ((lo.z + hi.z) / 2.0).floor() as i32, + ); + // Most boxes are in sections without a fluid: no cell to read. + let cells = ( + [ + (lo.x.floor() as i32).min(ex), + lo.y.floor() as i32, + (lo.z.floor() as i32).min(ez), + ], + [ + (hi.x.ceil() as i32 - 1).max(ex), + hi.y.ceil() as i32 - 1, + (hi.z.ceil() as i32 - 1).max(ez), + ], + ); + if !self + .world + .may_hold(cells.0, cells.1, |s| self.facts.get(s).fluid != Fluid::None) + { + return out; + } for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { @@ -92,10 +117,6 @@ impl MobWorld<'_> { // EntityFluidInteraction.update: the eyes are in a fluid block of // the box in the entity's column, between its bottom and its height // for the camera. - let (ex, ez) = ( - ((lo.x + hi.x) / 2.0).floor() as i32, - ((lo.z + hi.z) / 2.0).floor() as i32, - ); for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { let (fluid, h) = self.fluid_height(ex, y, ez); if fluid != Fluid::Water || f64::from(y) + h < lo.y || eye_y < f64::from(y) { @@ -155,14 +176,28 @@ impl MobWorld<'_> { let c = f64::from(c); c < area.max(axis) && c + 1.0 > area.min(axis) }; + // Where no section of the cursor holds a block reaching out of its + // cell, only the cells meeting `area` can hold the support. + let (rx, ry, rz) = (range(Axis::X), range(Axis::Y), range(Axis::Z)); + let outer = self.world.may_hold( + [*rx.start(), *ry.start(), *rz.start()], + [*rx.end(), *ry.end(), *rz.end()], + |s| self.collision.reaches_out(s), + ); let mut best: Option<(f64, [i32; 3])> = None; - for x in range(Axis::X) { - for z in range(Axis::Z) { + for x in rx { + for z in rz.clone() { + let column = meets(Axis::X, x) && meets(Axis::Z, z); + if !outer && !column { + continue; + } let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { continue; }; - let column = meets(Axis::X, x) && meets(Axis::Z, z); - for y in range(Axis::Y) { + for y in ry.clone() { + if !outer && !meets(Axis::Y, y) { + continue; + } let state = chunk.block(x & 15, y, z & 15); let Ok(block) = self.collision.collision_block(state) else { continue; diff --git a/crates/horizon-client/src/moved_extras.rs b/crates/horizon-client/src/moved_extras.rs new file mode 100644 index 000000000..22fb37e52 --- /dev/null +++ b/crates/horizon-client/src/moved_extras.rs @@ -0,0 +1,286 @@ +//! 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; 4] = [ + Moved { + id: "fps_overlay", + name: "FPS counter", + }, + Moved { + id: "keystrokes", + name: "Keystrokes", + }, + Moved { + id: "zoom", + name: "Zoom", + }, + Moved { + id: "minimap", + name: "Minimap", + }, +]; + +impl Moved { + fn was_on(&self, e: &Extras) -> bool { + match self.id { + "fps_overlay" => e.fps, + "keystrokes" => e.keystrokes, + "zoom" => e.zoom, + _ => e.minimap, + } + } + /// 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)), + ], + "keystrokes" => vec![ + ("corner", e.keystrokes_corner.name().into()), + ("cps", flag(e.keystrokes_cps)), + ], + "zoom" => vec![ + ("level", e.zoom_level.to_string()), + ("smooth", flag(e.zoom_smooth)), + ("sensitivity", flag(e.zoom_sensitivity)), + ], + _ => vec![ + ("corner", e.minimap_corner.name().into()), + ("size", e.minimap_size.to_string()), + ( + "shape", + if e.minimap_round { "round" } else { "square" }.into(), + ), + ("zoom", e.minimap_zoom.to_string()), + ("rotate", flag(e.minimap_rotate)), + ], + } + } + /// The extra's key as the mod's key (`horizon-mods.txt`), when the + /// player had changed it from the mod's default. + pub fn keys(&self, e: &Extras) -> Vec<(&'static str, String)> { + match self.id { + "zoom" if e.zoom_key != "key.keyboard.z" => vec![("zoom", e.zoom_key.clone())], + _ => Vec::new(), + } + } + /// 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()); + // A key the player already chose for the mod stays. + let keys = list.keys.entry(m.id.to_owned()).or_default(); + for (name, key) in m.keys(e) { + keys.entry(name.to_owned()).or_insert(key); + } + list.keys.retain(|_, k| !k.is_empty()); + 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(), 4); + 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], &MOVED[2], &MOVED[3]]); + // Zoom: its settings, and its key only when the player changed it. + e.zoom = true; + e.zoom_level = 8; + e.zoom_smooth = false; + assert_eq!(pending(&e), [&MOVED[2]]); + assert_eq!( + MOVED[2].settings(&e), + [ + ("level", "8".into()), + ("smooth", "false".into()), + ("sensitivity", "true".into()) + ] + ); + assert!(MOVED[2].keys(&e).is_empty()); + e.zoom_key = "key.mouse.4".into(); + assert_eq!(MOVED[2].keys(&e), [("zoom", "key.mouse.4".into())]); + // The minimap: its five settings, in the extra's values. + e.minimap = true; + e.minimap_corner = Corner::BottomLeft; + e.minimap_size = 128; + e.minimap_round = true; + e.minimap_zoom = 0.5; + assert_eq!(pending(&e), [&MOVED[2], &MOVED[3]]); + assert_eq!( + MOVED[3].settings(&e), + [ + ("corner", "bottom_left".into()), + ("size", "128".into()), + ("shape", "round".into()), + ("zoom", "0.5".into()), + ("rotate", "false".into()) + ] + ); + 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/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 9f91254bd..61fda9878 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -863,6 +863,8 @@ pub enum Page { Font, Packs, Mods, + /// Horizon's shader packs, either kind (`shader_pack_list`). + ShaderPacks, /// Horizon's graphics settings (`graphics_ui`). Graphics, GraphicsAdvanced, @@ -893,6 +895,9 @@ enum Act { ResetPadKey(&'static str), ResetPadKeys, ToggleMod(usize), + /// Pick `s.shader_packs[i]`, or turn it off when it is the pick. + PickShaderPack(usize), + OpenShaderPackFolder, /// The installed mod's own settings page (capability `ui`), shown as a /// screen: `Event::ModSettings` has the game open it. ModSettings(usize), @@ -947,6 +952,11 @@ pub enum Event { Packs(Vec), OpenPackFolder, OpenModFolder, + /// The Shader Packs page opened: list `shaderpacks/` into `shader_packs`. + ListShaderPacks, + /// A shader pack was picked or turned off: save and apply it. + ShaderPack, + OpenShaderPackFolder, /// Open the mod's own settings page (capability `ui`): the installed /// mod's index in `mods.installed`. ModSettings(usize), @@ -1092,6 +1102,9 @@ fn horizon_page_tooltip(page: Page) -> Option<&'static str> { "Optional additions, all off by default: the game stays vanilla until you turn one on." } Page::Agent => "Let your own AI agent play: horizon-ctl and MCP clients on this computer.", + Page::ShaderPacks => { + "Shader packs from the shaderpacks folder: Horizon's own and those in the shaders/ format. One runs at a time." + } Page::Mods => { "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on." } @@ -1183,6 +1196,7 @@ impl OptionsUi { Page::Font => "options.font.title", Page::Packs => "resourcePack.title", Page::Mods => "Mods", + Page::ShaderPacks => "Shader Packs", Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle", Page::Controller => "Controller Settings", Page::PadBinds => "Controller Binds", @@ -1299,23 +1313,30 @@ impl OptionsUi { Some(open("Advanced Graphics...", Page::GraphicsAdvanced)), ), Row::Buttons( - open("Controller Settings...", Page::Controller), - Some(self.extra_button(s, crate::extras::Item::DiscordPresence)), + open("Shader Packs...", Page::ShaderPacks), + Some(open("Controller Settings...", Page::Controller)), ), Row::Buttons( open("Extras...", Page::Extras), Some(open("Mods...", Page::Mods)), ), // No AI hides the AI Agent page and everything AI. - if s.extras.no_ai { - Row::Buttons(self.extra_button(s, crate::extras::Item::NoAi), None) - } else { - Row::Buttons( - open("AI Agent...", Page::Agent), - Some(self.extra_button(s, crate::extras::Item::NoAi)), - ) - }, + Row::Buttons( + self.extra_button(s, crate::extras::Item::DiscordPresence), + Some(if s.extras.no_ai { + self.extra_button(s, crate::extras::Item::NoAi) + } else { + open("AI Agent...", Page::Agent) + }), + ), ] + .into_iter() + .chain( + (!s.extras.no_ai).then(|| { + Row::Buttons(self.extra_button(s, crate::extras::Item::NoAi), None) + }), + ) + .collect() } Page::Agent => { let mut rows = vec![Row::Buttons( @@ -1532,6 +1553,26 @@ impl OptionsUi { }) .collect() } + Page::ShaderPacks => { + if s.shader_packs.is_empty() { + return vec![Row::Header( + "No shader packs: put them in the shaderpacks folder", + )]; + } + s.shader_packs + .iter() + .enumerate() + .map(|(i, pack)| { + let kind = match pack.kind { + crate::shader_pack_list::Kind::Horizon => " (Horizon)", + crate::shader_pack_list::Kind::Classic => "", + }; + let label = Text::literal(format!("{}{kind}: ", pack.title)) + .append(on_off(s.horizon.shader_pack == pack.file)); + Row::Buttons(button(0.0, 0.0, 310.0, label, Act::PickShaderPack(i)), None) + }) + .collect() + } _ => { let _ = s; Vec::new() @@ -2017,13 +2058,18 @@ impl OptionsUi { } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - if page == Page::Mods { + let folder = match page { + Page::Mods => Some(("Open Mod Folder", Act::OpenModFolder)), + Page::ShaderPacks => Some(("Open Pack Folder", Act::OpenShaderPackFolder)), + _ => None, + }; + if let Some((label, act)) = folder { out.push(button( cx - 154.0, h - 27.0, 150.0, - Text::literal("Open Mod Folder"), - Act::OpenModFolder, + Text::literal(label), + act, )); out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); } else { @@ -2475,7 +2521,12 @@ impl OptionsUi { } => { events.push(Event::ButtonClick); match act { - Act::Push(p) => self.push(p), + Act::Push(p) => { + if p == Page::ShaderPacks { + events.push(Event::ListShaderPacks); + } + self.push(p) + } Act::Done => events.extend(self.back(s)), Act::Cycle(opt) => { opt.cycle(s, right, framebuffer); @@ -2520,6 +2571,17 @@ impl OptionsUi { events.push(Event::ModSettings(i)); } Act::OpenModFolder => events.push(Event::OpenModFolder), + Act::PickShaderPack(i) => { + if let Some(pack) = s.shader_packs.get(i) { + s.horizon.shader_pack = if s.horizon.shader_pack == pack.file { + String::new() + } else { + pack.file.clone() + }; + events.push(Event::ShaderPack); + } + } + Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder), Act::Credits => events.push(Event::Credits), Act::CopyAgentDetails => events.push(Event::CopyAgentDetails), Act::None => {} @@ -3296,26 +3358,29 @@ mod tests { crate::extras::rows().iter().filter(|r| r.is_ok()).count() ); assert_eq!( - click(&mut ui, &mut s, Act::Extra(crate::extras::Item::Zoom)), + click(&mut ui, &mut s, Act::Extra(crate::extras::Item::Sort)), vec![Event::ButtonClick, Event::Changed] ); - assert!(s.extras.zoom); + assert!(s.extras.sort); assert_eq!( - click(&mut ui, &mut s, Act::Extra(crate::extras::Item::ZoomKey)), + click(&mut ui, &mut s, Act::Extra(crate::extras::Item::SortKey)), vec![Event::ButtonClick] ); - assert_eq!(ui.selected_key, Some(crate::extras::ZOOM_KEY)); + assert_eq!(ui.selected_key, Some(crate::extras::SORT_KEY)); assert_eq!( ui.key(&mut s, &atlas, winit::keyboard::KeyCode::KeyC, None), vec![Event::Changed] ); - assert_eq!(s.extras.zoom_key, "key.keyboard.c"); + assert_eq!(s.extras.sort_key, "key.keyboard.c"); assert_eq!( crate::extras::Extras::parse(&s.extras.serialize()), s.extras ); - ui.scroll(&s, size, -1000.0); - let (_, top, bottom, content) = ui.layout(&s, size.0, size.1); + // In a window too short for the page, the wheel scrolls to its end. + let short = (480.0, 180.0); + ui.scroll(&s, short, -1000.0); + let (_, top, bottom, content) = ui.layout(&s, short.0, short.1); + assert!(content > bottom - top); assert_eq!(ui.scroll, content - (bottom - top)); assert_eq!( ui.key(&mut s, &atlas, winit::keyboard::KeyCode::Escape, None), @@ -3867,7 +3932,7 @@ mod tests { #[test] fn extras_and_vanilla_bindings_accept_mouse_buttons() { - use crate::extras::{Extras, SORT_KEY, ZOOM_KEY}; + use crate::extras::{Extras, SORT_KEY}; use winit::event::MouseButton; for button in [ MouseButton::Left, @@ -3876,7 +3941,7 @@ mod tests { MouseButton::Back, MouseButton::Forward, ] { - for name in [SORT_KEY, ZOOM_KEY, "key.jump"] { + for name in [SORT_KEY, "key.jump"] { let mut ui = OptionsUi::default(); let mut s = Settings::default(); ui.selected_key = Some(name); @@ -3885,7 +3950,6 @@ mod tests { let value = keybinds::mouse_name(button); match name { SORT_KEY => assert_eq!(s.extras.sort_key, value), - ZOOM_KEY => assert_eq!(s.extras.zoom_key, value), _ => assert_eq!(s.keys.get(name), value), } assert_eq!(Extras::parse(&s.extras.serialize()), s.extras); @@ -4064,6 +4128,7 @@ mod tests { [ Page::Graphics, Page::GraphicsAdvanced, + Page::ShaderPacks, Page::Controller, Page::Extras, Page::Mods, diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 2a53e1702..74c428923 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -182,6 +182,9 @@ pub struct Settings { pub extras: crate::extras::Extras, /// The Horizon mods turned on (`horizon-mods.txt`), all off by default. pub mods: crate::mod_list::ModList, + /// The packs in `shaderpacks/`, listed when the Shader Packs page opens; the pick is + /// `horizon.shader_pack`. + pub shader_packs: Vec, } impl Default for Settings { fn default() -> Self { @@ -255,6 +258,7 @@ impl Default for Settings { controller: Default::default(), extras: Default::default(), mods: Default::default(), + shader_packs: Vec::new(), } } } @@ -415,6 +419,7 @@ impl Settings { controller: Default::default(), extras: Default::default(), mods: Default::default(), + shader_packs: Vec::new(), auto_jump: f.bool("autoJump"), language: f.string("lang"), force_unicode: f.bool("forceUnicodeFont"), @@ -538,6 +543,21 @@ impl Settings { } f } + /// These settings with one `options.txt` value changed (`horizon-ctl + /// options-set`, as `OptionsFile::set_text` reads it). Horizon's own + /// files (graphics, controller, extras, the mod list) aren't in + /// `options.txt`, so they stay as they are. + pub fn with_option(&self, key: &str, value: &str) -> Result { + let mut file = self.to_file(); + file.set_text(key, value)?; + Ok(Self { + horizon: self.horizon.clone(), + controller: self.controller.clone(), + extras: self.extras.clone(), + mods: self.mods.clone(), + ..Self::from_file(file) + }) + } /// The `options.txt` text (Options.save). pub fn serialize(&self) -> String { self.to_file().serialize() @@ -592,6 +612,21 @@ impl Settings { mod tests { use super::*; #[test] + fn an_option_set_keeps_horizon_files() { + let mut s = Settings::parse("fov:70\n"); + s.mods.enabled.insert("zoom".into()); + s.extras.minimap = true; + s.horizon.fog = !s.horizon.fog; + s.controller.vibration = !s.controller.vibration; + let set = s.with_option("fov", "90").unwrap(); + assert_eq!(set.fov, 90.0); + assert_eq!(set.mods, s.mods); + assert_eq!(set.extras, s.extras); + assert_eq!(set.horizon, s.horizon); + assert_eq!(set.controller, s.controller); + assert!(s.with_option("fov", "200").is_err()); + } + #[test] fn gui_scale_survives_temporary_small_framebuffer() { for requested in [0, 1, 2, 6] { let settings = Settings::parse(&format!("guiScale:{requested}\n")); diff --git a/crates/horizon-client/src/shader_pack_list.rs b/crates/horizon-client/src/shader_pack_list.rs new file mode 100644 index 000000000..c9a8f338b --- /dev/null +++ b/crates/horizon-client/src/shader_pack_list.rs @@ -0,0 +1,109 @@ +//! The shader packs in the `shaderpacks` folder beside `options.txt`, as Options > Horizon +//! Settings > Shader Packs lists them: Horizon's own (docs/shaders.md) and those in the +//! `shaders/` format, side by side. + +use std::path::Path; + +pub const DIR: &str = "shaderpacks"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// A folder with `horizon-shaders.toml`, or a `.hshader`. + Horizon, + /// A folder with a `shaders` folder, or a `.zip`. + Classic, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + /// The folder's or file's name in `shaderpacks`: what the pick saves. + pub file: String, + /// The pack's own name for Horizon's packs, else `file`. + pub title: String, + pub kind: Kind, +} + +/// The packs in `dir`, Horizon's first, each kind by title. A missing folder has none. +pub fn scan(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut packs: Vec = entries.flatten().filter_map(|e| entry(&e.path())).collect(); + packs.sort_by(|a, b| { + (a.kind == Kind::Classic, a.title.to_lowercase()) + .cmp(&(b.kind == Kind::Classic, b.title.to_lowercase())) + }); + packs +} + +fn entry(path: &Path) -> Option { + let file = path.file_name()?.to_str()?.to_owned(); + if file.starts_with('.') { + return None; + } + if horizon_shader_api::package::is_pack(path) { + // Its manifest's name; a pack that can't be read is still listed, under its file + // name: picking it says why in the chat. + let manifest = if path.is_dir() { + std::fs::read_to_string(path.join(horizon_shader_api::MANIFEST)) + .ok() + .and_then(|t| horizon_shader_api::Manifest::parse(&t).ok()) + } else { + horizon_shader_api::Pack::read(path) + .ok() + .map(|p| p.manifest) + }; + let title = manifest.map_or_else(|| file.clone(), |m| m.name); + return Some(Entry { + file, + title, + kind: Kind::Horizon, + }); + } + let zip = path.is_file() + && path + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("zip")); + (zip || path.join("shaders").is_dir()).then(|| Entry { + title: file.clone(), + file, + kind: Kind::Classic, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_both_kinds_horizon_first_and_skips_the_rest() { + let dir = std::env::temp_dir().join(format!("horizon-shader-list-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let d = dir.as_path(); + let manifest = "schema = 1\nid = \"warm\"\nname = \"Warm Light\"\nversion = \"1\"\n\ + api = \"0.1\"\n[[post]]\nfile = \"p.wgsl\"\n"; + std::fs::create_dir(d.join("warm")).unwrap(); + std::fs::write(d.join("warm").join(horizon_shader_api::MANIFEST), manifest).unwrap(); + std::fs::create_dir_all(d.join("Classic Folder/shaders")).unwrap(); + std::fs::write(d.join("archive.zip"), b"").unwrap(); + std::fs::write(d.join("notes.txt"), b"").unwrap(); + std::fs::create_dir(d.join("empty")).unwrap(); + std::fs::create_dir_all(d.join(".hidden/shaders")).unwrap(); + let packs = scan(d); + let listed: Vec<(&str, &str, Kind)> = packs + .iter() + .map(|e| (e.file.as_str(), e.title.as_str(), e.kind)) + .collect(); + assert_eq!( + listed, + [ + ("warm", "Warm Light", Kind::Horizon), + ("archive.zip", "archive.zip", Kind::Classic), + ("Classic Folder", "Classic Folder", Kind::Classic), + ] + ); + assert!(scan(&d.join("missing")).is_empty()); + std::fs::remove_dir_all(d).unwrap(); + } +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 103f7402b..643a604bc 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -639,8 +639,12 @@ impl Streaming { self.lit.remove(&(x, z)); self.meshed.remove(&(x, z)); self.lighting.remove(&(x, z)); - self.meshing.retain(|k, _| (k.0, k.2) != (x, z)); - self.waiting.retain(|k| (k.0, k.2) != (x, z)); + // By key, not by a pass over every pending section: a moved or + // shrunk storage forgets thousands of columns in one frame. + for sy in 0..SECTIONS as i32 { + self.meshing.remove(&(x, sy, z)); + self.waiting.remove(&(x, sy, z)); + } world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index c0a2fc6fd..711a2fce7 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -227,8 +227,9 @@ fn sunrise_weight(d: vec3) -> f32 { } return best; } -@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4 { - let d = view_ray(in.ndc); +// The sky's colour along the view ray `d` (a shader pack's sky stage gets it as its input: +// gfx/native_sky.rs builds that stage from this section). +fn sky_along_ray(d: vec3) -> vec3 { var color = globals.fog_color.rgb; let dist = disc_distance(d, 16.0); if dist.x >= 0.0 { @@ -238,7 +239,10 @@ fn sunrise_weight(d: vec3) -> f32 { if w > 0.0 { color = mix(color, globals.sunrise.rgb, w * globals.sunrise.a); } - return vec4(color, 1.0); + return color; +} +@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4 { + return vec4(sky_along_ray(view_ray(in.ndc)), 1.0); } @fragment fn fs_dark_disc(in: SkyOut) -> @location(0) vec4 { let d = view_ray(in.ndc); diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 3b2920ade..d73956d85 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -311,6 +311,40 @@ impl World { .get(&(x >> 4, z >> 4)) .map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15)) } + /// Whether a block of the box `lo..=hi` may match, from the palettes of + /// the sections it reaches (a palette of the whole registry may hold + /// anything): `false` means [`Self::block`] matches in none of its cells, + /// so a scan over them can stop before reading one. + pub fn may_hold( + &self, + lo: [i32; 3], + hi: [i32; 3], + mut matches: impl FnMut(BlockStateId) -> bool, + ) -> bool { + let top = MIN_Y + SECTIONS as i32 * 16 - 1; + // Heights outside the sections read as state 0. + if (lo[1] < MIN_Y || hi[1] > top) && matches(BlockStateId(0)) { + return true; + } + let sections = (lo[1].max(MIN_Y) - MIN_Y) >> 4..=(hi[1].min(top) - MIN_Y) >> 4; + for cx in lo[0] >> 4..=hi[0] >> 4 { + for cz in lo[2] >> 4..=hi[2] >> 4 { + let Some(chunk) = self.chunks.get(&(cx, cz)) else { + if matches(self.air) { + return true; + } + continue; + }; + for s in sections.clone() { + let blocks = &chunk.sections[s as usize].blocks; + if blocks.is_global() || blocks.maybe_has(|v| matches(BlockStateId(v))) { + return true; + } + } + } + } + false + } /// The block entities to tick this tick, in order (`BlockEntities::tickers`). pub fn block_entity_tickers(&mut self) -> Vec<(crate::block_entities::Pos, u32)> { let (chunks, air) = (&self.chunks, self.air); @@ -333,3 +367,32 @@ impl World { self.chunks.contains_key(&(x >> 4, z >> 4)) } } + +#[cfg(test)] +mod tests { + use super::World; + use crate::chunk::Chunk; + use horizon_world::registry::BlockStateId; + use std::sync::Arc; + + /// A box misses a state only where no section it reaches lists it, and + /// unloaded columns or heights past the world count as their air. + #[test] + fn may_hold_reads_the_palettes_of_the_reached_sections() { + let mut world = World::new(BlockStateId(0), 0); + let mut chunk = Chunk::empty(0, 0); + chunk.set(3, 70, 3, 9); + world.chunks.insert((0, 0), Arc::new(chunk)); + let nine = |s: BlockStateId| s.0 == 9; + // The section of y 64..80 holds 9, the one below does not. + assert!(world.may_hold([0, 64, 0], [1, 65, 1], nine)); + assert!(world.may_hold([10, 79, 10], [12, 80, 12], nine)); + assert!(!world.may_hold([0, 50, 0], [15, 63, 15], nine)); + // A box over the unloaded column next door sees only air. + assert!(!world.may_hold([16, 70, 0], [17, 71, 1], nine)); + assert!(world.may_hold([16, 70, 0], [17, 71, 1], |s| s.0 == 0)); + // Past the top, and the palette of air below it. + assert!(!world.may_hold([0, 400, 0], [0, 401, 0], nine)); + assert!(world.may_hold([0, 400, 0], [0, 401, 0], |s| s.0 == 0)); + } +} diff --git a/crates/horizon-mod-sdk/examples/coords-hud/tests/panel.toml b/crates/horizon-mod-sdk/examples/coords-hud/tests/panel.toml new file mode 100644 index 000000000..eed41a461 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/coords-hud/tests/panel.toml @@ -0,0 +1,36 @@ +# The panel follows the player and the clock; /coords hides and shows it. + +[player] +x = 12.5 +z = -3.25 +yaw = 180.0 + +[clock] +day-time = 29999 + +[[step]] +ticks = 1 +expect.panel = ["XYZ 12.5 / 64.0 / -3.2", "Facing North (-Z)", "Day 2, 12:00"] +expect.corner = "top-left" + +[[step]] +player = { x = -100.0, yaw = 90.0 } +ticks = 1 +expect.panel = ["XYZ -100.0 / 64.0 / -3.2", "Facing West (-X)", "Day 2, 12:00"] + +[[step]] +command = "coords" +expect.feedback = "Coordinates panel hidden" + +# A step's ticks come before its command: the panel goes at the next tick. +[[step]] +ticks = 1 +expect.panel = [] + +[[step]] +command = "coords" +expect.feedback = "Coordinates panel shown" + +[[step]] +ticks = 1 +expect.panel = ["XYZ -100.0 / 64.0 / -3.2", "Facing West (-X)", "Day 2, 12:00"] diff --git a/crates/horizon-mod-sdk/examples/coords-hud/tests/where.toml b/crates/horizon-mod-sdk/examples/coords-hud/tests/where.toml new file mode 100644 index 000000000..99a4aecdf --- /dev/null +++ b/crates/horizon-mod-sdk/examples/coords-hud/tests/where.toml @@ -0,0 +1,17 @@ +# /where puts the position in chat; on the title screen it answers with an error. + +[player] +x = 12.5 +y = 70.2 +z = -3.25 +dimension = "minecraft:the_nether" + +[[step]] +command = "where" +expect.chat = ["12, 70, -4 in minecraft:the_nether"] + +[[step]] +title-screen = true +command = "where" +expect.chat = [] +expect.error = "Not in a world" diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 9088c0c39..5fbfafc24 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -364,6 +364,27 @@ interface render { /// wins) leave the camera vanilla's. With several mods, the strongest /// zoom counts. set-zoom: func(zoom: zoom); + record minimap { + corner: corner, + /// Its side in GUI pixels, 16 to 256. + size: f32, + /// World blocks per map pixel, 0.5 to 4; the map is 128 × 128 pixels. + blocks-per-pixel: f32, + /// The map turns with the player, who faces up, and an N on its rim + /// marks north. Otherwise north is up and the player's arrow turns. + rotate: bool, + /// Round, the corners left clear; otherwise square. + round: bool, + } + /// Shows a map of the world around the player in `corner`, stacked with + /// the game's overlays and the mods' panels, until the next call (none + /// hides it). It looks like a map item: vanilla's map colours with their + /// height shading and water depth, and the player's arrow. Underground, + /// under a roof and in the Nether it maps the floor around the player's + /// height. The game keeps the map's tiles and refreshes them within its + /// own frame budget; hidden, they are dropped. One map shows at a time: + /// the first loaded mod's. + set-minimap: func(minimap: option); } /// What the game calls. Only the hooks `init` asks for are ever called. diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index 17a6c5aa0..3c5fe74f6 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -12,6 +12,8 @@ pub mod manifest; pub mod modpack; #[cfg(feature = "runtime")] mod runtime; +#[cfg(feature = "runtime")] +pub mod testing; pub use content::Content; pub use manifest::{Capability, Manifest, Package, Side, find}; diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 0011fa99d..4dc334ea5 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -52,8 +52,9 @@ use render_bindings::horizon::mods::input; pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, ItemUse}; /// 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, Zoom as ModZoom, + Corner as RenderCorner, FillShape, FrameRate, ItemShape, Minimap as ModMinimap, + Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, TextShape, + Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; @@ -196,6 +197,8 @@ struct State { corner: Option, /// Capability `render`'s zoom, when the mod zooms. zoom: Option, + /// Capability `render`'s minimap, when the mod shows one. + minimap: Option, input: InputState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, @@ -339,6 +342,7 @@ impl Mods { shapes: Vec::new(), corner: None, zoom: None, + minimap: None, input: InputState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, @@ -684,6 +688,12 @@ impl Mods { .filter_map(|e| e.run.as_ref()?.store.data().zoom) .max_by(|a, b| a.factor.total_cmp(&b.factor)) } + /// The minimap the first running mod shows (capability `render`). + pub fn minimap(&self) -> Option { + self.entries + .iter() + .find_map(|e| e.run.as_ref()?.store.data().minimap) + } fn inputs(&self) -> impl Iterator { self.entries .iter() @@ -1013,6 +1023,9 @@ const SHAKE_SECONDS: f32 = 10.0; /// or more, and turning never stops. const ZOOM_MAX: f32 = 10.0; const TURN_MIN: f32 = 0.05; +/// `set-minimap`'s side in GUI pixels and its blocks per map pixel. +const MINIMAP_SIZE: (f32, f32) = (16.0, 256.0); +const MINIMAP_SCALE: (f32, f32) = (0.5, 4.0); /// A mod's corner panel: shapes in a `width` × `height` box the game /// places in `corner`, stacked with the other overlays. @@ -1094,6 +1107,14 @@ impl render::Host for State { }, }); } + fn set_minimap(&mut self, minimap: Option) { + let finite = |v: f32, lo: f32, hi: f32| if v.is_finite() { v.clamp(lo, hi) } else { lo }; + self.minimap = minimap.map(|m| ModMinimap { + size: finite(m.size, MINIMAP_SIZE.0, MINIMAP_SIZE.1), + blocks_per_pixel: finite(m.blocks_per_pixel, MINIMAP_SCALE.0, MINIMAP_SCALE.1), + ..m + }); + } fn frame_stats(&mut self) -> FrameRate { let (fps, min, low) = self.snapshot.frame; FrameRate { fps, min, low } diff --git a/crates/horizon-mods/src/testing.rs b/crates/horizon-mods/src/testing.rs new file mode 100644 index 000000000..d8c8076b4 --- /dev/null +++ b/crates/horizon-mods/src/testing.rs @@ -0,0 +1,416 @@ +//! A mod run with no game: `cargo horizon-mod test` (docs/mods.md, "Testing a mod"). +//! +//! [`TestGame`] loads one `.hmod` from a scratch copy (its `storage` lives and +//! dies with the run) into the same sandbox the game uses, and plays the game's +//! part: the snapshot, ticks, frames, chat lines and commands. [`Script`] is a +//! test written in TOML, `tests/.toml` in the mod's folder: steps, each +//! saying what happens and what the mod must have shown by then. +use crate::{Clock, Corner, Mods, Output, Panel, Player, Snapshot, Status}; +use serde::Deserialize; +use std::{ + path::{Path, PathBuf}, + sync::atomic::{AtomicUsize, Ordering}, +}; + +/// One mod in the sandbox, driven by a test. +pub struct TestGame { + mods: Mods, + dir: PathBuf, + hmod: PathBuf, + /// What the mod reads with `game-read`; ticks move the clock as the game does. + pub player: Option, + pub clock: Option, + tick: u64, +} + +/// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing +/// south, full health and food, at the first tick of a new world's first morning. +pub fn default_player() -> Player { + Player { + x: 0.5, + y: 64.0, + z: 0.5, + yaw: 0.0, + pitch: 0.0, + health: 20.0, + food: 20, + dimension: "minecraft:overworld".into(), + } +} + +impl TestGame { + /// Starts the mod at `hmod`, as the game would with it turned on. Errs + /// when it doesn't start, with the game's reason. + pub fn load(hmod: &Path) -> Result { + static RUN: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!( + "horizon-mod-test-{}-{}", + std::process::id(), + RUN.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let copy = dir.join(hmod.file_name().unwrap_or("mod.hmod".as_ref())); + let mut game = TestGame { + mods: Mods::default(), + hmod: copy.clone(), + dir, + player: Some(default_player()), + clock: Some(Clock { + game_time: 0, + day_time: 0, + }), + tick: 0, + }; + copy_mod(hmod, ©)?; + game.start()?; + Ok(game) + } + + fn start(&mut self) -> Result<(), String> { + self.mods = Mods::load(std::slice::from_ref(&self.hmod), |_| true, |_| false); + match &self.mods.entries()[0].status { + Status::Failed(reason) => Err(format!("the mod didn't start: {reason}")), + _ if !self.mods.is_running() => Err("the mod has no code to run".into()), + _ => Ok(()), + } + } + + /// Stops the mod and starts it again, as a rebuild does in the game: its + /// memory starts over, its `storage` stays. + pub fn reload(&mut self) -> Result<(), String> { + self.mods = Mods::default(); + self.start() + } + + fn snapshot(&mut self) { + self.mods.set_snapshot(Snapshot { + player: self.player.clone(), + clock: self.clock, + // The GUI of a 1280 x 720 window at scale 3, as the trial run's. + gui_size: (427.0, 240.0), + ..Snapshot::default() + }); + } + + /// `n` game ticks; each moves the clock one tick on, as the game does. + pub fn tick(&mut self, n: u64) { + for _ in 0..n { + self.tick += 1; + if let Some(clock) = &mut self.clock { + clock.game_time += 1; + clock.day_time += 1; + } + self.snapshot(); + self.mods.tick(self.tick); + } + } + /// `n` frames, 1/60 s apart. + pub fn frames(&mut self, n: u64) { + self.snapshot(); + for _ in 0..n { + self.mods.frame(1.0 / 60.0); + } + } + /// A chat line the player receives. + pub fn chat(&mut self, line: &str) { + self.snapshot(); + self.mods.chat(line); + } + /// `/line` typed by the player (without the slash); false when the mod + /// owns no such command. + pub fn command(&mut self, line: &str) -> bool { + self.snapshot(); + self.mods.command(line) + } + + /// The scratch copy the mod runs from; its `storage` is beside it. + pub fn hmod(&self) -> &Path { + &self.hmod + } + /// The commands the mod registered. + pub fn commands(&self) -> Vec { + self.mods.commands().map(str::to_owned).collect() + } + pub fn panel(&self) -> Option<&Panel> { + self.mods.panels().next() + } + pub fn status(&self) -> &Status { + &self.mods.entries()[0].status + } + /// What the mod showed since the last call. + pub fn drain(&mut self) -> Vec { + self.mods.drain() + } +} + +impl Drop for TestGame { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// A `.hmod` file, or a mod folder (`horizon-mod.toml` + `mod.wasm`). +fn copy_mod(from: &Path, to: &Path) -> Result<(), String> { + let err = |e: std::io::Error| format!("{}: {e}", from.display()); + if !from.is_dir() { + return std::fs::copy(from, to).map(drop).map_err(err); + } + std::fs::create_dir_all(to).map_err(err)?; + for entry in std::fs::read_dir(from).map_err(err)? { + let entry = entry.map_err(err)?; + if entry.file_type().map_err(err)?.is_file() { + std::fs::copy(entry.path(), to.join(entry.file_name())).map_err(err)?; + } + } + Ok(()) +} + +/// A test in TOML: where the player starts, then steps run in order. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub struct Script { + #[serde(default)] + pub player: PlayerSet, + #[serde(default)] + pub clock: ClockSet, + #[serde(default, rename = "step")] + pub steps: Vec, +} + +/// Fields of the player to change; the others keep their values. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PlayerSet { + x: Option, + y: Option, + z: Option, + yaw: Option, + pitch: Option, + health: Option, + food: Option, + dimension: Option, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub struct ClockSet { + game_time: Option, + day_time: Option, +} + +/// One step. Its parts happen in this order: `reload`, `title-screen`, +/// `player`, `clock`, `ticks`, `frames`, `chat`, `command`; then `expect` is +/// checked against what the mod showed during the step. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub struct Step { + #[serde(default)] + reload: bool, + /// Leave the world: the mod reads no player and no clock until a step sets them. + #[serde(default)] + title_screen: bool, + player: Option, + clock: Option, + #[serde(default)] + ticks: u64, + #[serde(default)] + frames: u64, + chat: Option, + command: Option, + #[serde(default)] + expect: Expect, +} + +/// What a step checks; a part left out is not checked. +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub struct Expect { + /// The commands the mod owns. + commands: Option>, + /// Every chat line shown during the step, in order. + chat: Option>, + /// The command's feedback, and its red error. + feedback: Option, + error: Option, + /// The panel's lines (`[]`: no panel) and its corner. + panel: Option>, + corner: Option, + /// The mod is turned off during this step, for a reason holding this text. + /// Without it, a mod that stops fails the test. + stopped: Option, +} + +impl Script { + pub fn parse(text: &str) -> Result { + toml::from_str(text).map_err(|e| e.to_string()) + } + + /// Runs every step on `game`; the error names the first step that failed. + pub fn run(&self, game: &mut TestGame) -> Result<(), String> { + if let Some(p) = &mut game.player { + self.player.apply(p); + } + if let Some(c) = &mut game.clock { + self.clock.apply(c); + } + for (i, step) in self.steps.iter().enumerate() { + step.run(game) + .map_err(|e| format!("step {} ({}): {e}", i + 1, step.describe()))?; + } + Ok(()) + } +} + +impl PlayerSet { + fn apply(&self, p: &mut Player) { + let set = |to: &mut f64, v: Option| *to = v.unwrap_or(*to); + set(&mut p.x, self.x); + set(&mut p.y, self.y); + set(&mut p.z, self.z); + p.yaw = self.yaw.unwrap_or(p.yaw); + p.pitch = self.pitch.unwrap_or(p.pitch); + p.health = self.health.unwrap_or(p.health); + p.food = self.food.unwrap_or(p.food); + if let Some(d) = &self.dimension { + p.dimension.clone_from(d); + } + } +} + +impl ClockSet { + fn apply(&self, c: &mut Clock) { + c.game_time = self.game_time.unwrap_or(c.game_time); + c.day_time = self.day_time.unwrap_or(c.day_time); + } +} + +impl Step { + fn describe(&self) -> String { + let mut parts = Vec::new(); + if self.reload { + parts.push("reload".to_string()); + } + let count = |n: u64, what: &str| format!("{n} {what}{}", if n == 1 { "" } else { "s" }); + if self.ticks > 0 { + parts.push(count(self.ticks, "tick")); + } + if self.frames > 0 { + parts.push(count(self.frames, "frame")); + } + if let Some(line) = &self.chat { + parts.push(format!("chat {line:?}")); + } + if let Some(line) = &self.command { + parts.push(format!("/{line}")); + } + if parts.is_empty() { + parts.push("checks".into()); + } + parts.join(", ") + } + + fn run(&self, game: &mut TestGame) -> Result<(), String> { + if self.reload { + game.reload()?; + } + if self.title_screen { + game.player = None; + game.clock = None; + } + if let Some(set) = &self.player { + set.apply(game.player.get_or_insert_with(default_player)); + } + if let Some(set) = &self.clock { + set.apply(game.clock.get_or_insert(Clock { + game_time: 0, + day_time: 0, + })); + } + game.tick(self.ticks); + game.frames(self.frames); + if let Some(line) = &self.chat { + game.chat(line); + } + let owned = self.command.as_ref().map(|line| game.command(line)); + let out = game.drain(); + let stopped = out.iter().find_map(|o| match o { + Output::Stopped { reason, .. } => Some(reason.as_str()), + _ => None, + }); + let e = &self.expect; + match (stopped, &e.stopped) { + (Some(reason), Some(want)) if !reason.contains(want.as_str()) => { + return Err(format!("the mod stopped ({reason}), expected {want:?}")); + } + (Some(_), Some(_)) => return Ok(()), + (Some(reason), None) => return Err(format!("the mod stopped: {reason}")), + (None, Some(want)) => { + return Err(format!( + "the mod kept running, expected it to stop ({want:?})" + )); + } + (None, None) => {} + } + if owned == Some(false) { + let line = self.command.as_deref().unwrap_or_default(); + let name = line.split(' ').next().unwrap_or_default(); + return Err(format!("the mod owns no command /{name}")); + } + if let Some(want) = &e.commands { + same("commands", want, &game.commands())?; + } + if let Some(want) = &e.chat { + let got: Vec = out + .iter() + .filter_map(|o| match o { + Output::Chat { text, .. } => Some(text.clone()), + _ => None, + }) + .collect(); + same("chat", want, &got)?; + } + let feedback = |error: bool| { + out.iter().rev().find_map(|o| match o { + Output::Feedback { text, error: e } if *e == error => Some(text.clone()), + _ => None, + }) + }; + if let Some(want) = &e.feedback { + same("feedback", &Some(want.clone()), &feedback(false))?; + } + if let Some(want) = &e.error { + same("error", &Some(want.clone()), &feedback(true))?; + } + if let Some(want) = &e.panel { + let got: Vec = game + .panel() + .map(|p| p.lines.iter().map(|l| l.text.clone()).collect()) + .unwrap_or_default(); + same("panel", want, &got)?; + } + if let Some(want) = &e.corner { + let got = game.panel().map(|p| corner_name(p.corner).to_string()); + same("corner", &Some(want.clone()), &got)?; + } + Ok(()) + } +} + +fn corner_name(c: Corner) -> &'static str { + match c { + Corner::TopLeft => "top-left", + Corner::TopRight => "top-right", + Corner::BottomLeft => "bottom-left", + Corner::BottomRight => "bottom-right", + } +} + +fn same(what: &str, want: &T, got: &T) -> Result<(), String> { + if want == got { + return Ok(()); + } + Err(format!( + "{what}\n expected: {want:?}\n got: {got:?}" + )) +} diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 3b33ab4b2..0be4fa47d 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -4,6 +4,7 @@ use horizon_mods::{ Clock, Corner, HeldItem, Mods, Output, Package, Player, Shape, Snapshot, Status, manifest::componentize, + testing::{Script, TestGame}, }; use std::{ path::{Path, PathBuf}, @@ -632,6 +633,32 @@ fn render_zoom_is_clamped_and_the_strongest_counts() { assert_eq!(zoom(&mut mods, "x 0 1"), None); } +#[test] +fn render_minimap_is_clamped_and_hidden() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let map = |mods: &mut Mods, args: &str| { + assert!(mods.command(&format!("minimap {args}"))); + mods.minimap() + .map(|m| (m.corner, m.size, m.blocks_per_pixel, m.rotate, m.round)) + }; + assert!(mods.minimap().is_none()); + let corner = horizon_mods::RenderCorner::BottomLeft; + assert_eq!( + map(&mut mods, "96 2 1 0"), + Some((corner, 96.0, 2.0, true, false)) + ); + // The side and the scale are clamped; NaN takes the smallest. + assert_eq!( + map(&mut mods, "999 0.1 0 1"), + Some((corner, 256.0, 0.5, false, true)) + ); + assert_eq!( + map(&mut mods, "x 9 0 0"), + Some((corner, 16.0, 4.0, false, false)) + ); + assert_eq!(map(&mut mods, "off"), None); +} + #[test] fn corner_panels_text_width_and_readings() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); @@ -703,3 +730,80 @@ capabilities = ["registries"] // Content has no hooks: the game's per-tick mod work stays skipped. assert!(!mods.is_running()); } + +/// `cargo horizon-mod test` on the example: its own `tests/*.toml` pass. +#[test] +fn the_examples_test_scripts_pass() { + let tests = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples/coords-hud/tests"); + let mut ran = 0; + for entry in std::fs::read_dir(tests).unwrap() { + let path = entry.unwrap().path(); + let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); + let mut game = TestGame::load(&mods_dir().join("coords_hud.hmod")).unwrap(); + script + .run(&mut game) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())); + ran += 1; + } + assert_eq!(ran, 2); +} + +#[test] +fn a_test_script_says_which_step_failed_and_why() { + let script = Script::parse( + r#" + [[step]] + ticks = 3 + command = "hello there" + expect.chat = ["hello there after 2 ticks"] + "#, + ) + .unwrap(); + let mut game = TestGame::load(&mods_dir().join("horizon_mods_test_guest.hmod")).unwrap(); + assert_eq!( + script.run(&mut game).unwrap_err(), + "step 1 (3 ticks, /hello there): chat\n expected: [\"hello there after 2 ticks\"]\n \ + got: [\"hello there after 3 ticks\"]" + ); + assert!( + Script::parse("[[step]]\ntick = 1").is_err(), + "a typo is an error" + ); +} + +#[test] +fn a_test_script_reloads_and_expects_a_stop() { + let script = Script::parse( + r#" + [[step]] + command = "save kept" + expect.feedback = "saved" + + [[step]] + reload = true + command = "load" + expect.chat = ["kept"] + + [[step]] + command = "panic" + expect.stopped = "panic" + + [[step]] + reload = true + command = "nope" + "#, + ) + .unwrap(); + let mut game = TestGame::load(&mods_dir().join("horizon_mods_test_guest.hmod")).unwrap(); + let dir = game.hmod().parent().unwrap().to_path_buf(); + assert_eq!( + script.run(&mut game).unwrap_err(), + "step 4 (reload, /nope): the mod owns no command /nope" + ); + drop(game); + assert!( + !dir.exists(), + "the scratch copy and its storage are removed" + ); +} diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 9bede11f9..3d4c66076 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -96,6 +96,7 @@ impl Mod for Guest { "input_held", "input_wheel", "zoom", + "minimap", "corner", "readings", ] @@ -198,6 +199,24 @@ impl Mod for Guest { turn, }); } + // `minimap off`, or `minimap SIZE BLOCKS-PER-PIXEL ROTATE ROUND`. + "minimap" => { + let words: Vec<&str> = args.split(' ').collect(); + let number = |i: usize| { + words + .get(i) + .and_then(|w| w.parse().ok()) + .unwrap_or(f32::NAN) + }; + let map = (args != "off").then(|| render::Minimap { + corner: render::Corner::BottomLeft, + size: number(0), + blocks_per_pixel: number(1), + rotate: words.get(2) == Some(&"1"), + round: words.get(3) == Some(&"1"), + }); + render::set_minimap(map); + } // Clamped to (1, 10); the two after it shake nothing. "render_shake" => { render::shake(2.0, 99.0); diff --git a/crates/horizon-shader-api/src/check.rs b/crates/horizon-shader-api/src/check.rs index 6c43718f7..c3ecdd158 100644 --- a/crates/horizon-shader-api/src/check.rs +++ b/crates/horizon-shader-api/src/check.rs @@ -60,6 +60,10 @@ pub struct CheckedStage { pub label: String, pub module: naga::Module, pub info: ModuleInfo, + /// The stage's WGSL without the entry points (the prelude, the shared + /// files, the file), for a renderer that calls the stage function from + /// its own shader (the sky). + pub source: String, pub expressions: usize, pub texture_reads: usize, } @@ -169,6 +173,7 @@ pub fn check_stage(pack: &Pack, kind: StageKind, file: &str) -> Result)` | 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. | @@ -400,6 +410,7 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `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. | +| `set-minimap` | `func(minimap: option)` | Shows a map of the world around the player in `corner`, stacked with the game's overlays and the mods' panels, until the next call (none hides it). It looks like a map item: vanilla's map colours with their height shading and water depth, and the player's arrow. Underground, under a roof and in the Nether it maps the floor around the player's height. The game keeps the map's tiles and refreshes them within its own frame budget; hidden, they are dropped. One map shows at a time: the first loaded mod's. | ## `events` diff --git a/docs/api/mods.md b/docs/api/mods.md index 7b8c5a464..211a06f8b 100644 --- a/docs/api/mods.md +++ b/docs/api/mods.md @@ -19,7 +19,7 @@ the player before the mod is turned on, and checked against the component's real | Capabilities | 5: `game-read`, `chat`, `hud`, `storage`, `registries` | | Manifest `api` lines served | 2: `0.1` (code), `0.2` (content) | | SDK | the `Mod` trait (5 methods), `Registration` (4 builders), `export_mod!`, log helpers | -| `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `check` | +| `cargo horizon-mod` | `new` (templates `code` and `content`), `build`, `run`, `test`, `check` | | Example mods | `coords-hud` (code), `ruby-content` (content) | ## Guide @@ -33,7 +33,10 @@ The step-by-step guide, from installing the tools to publishing on the registry, ([The manifest](../mods.md#the-manifest)). 3. `cargo horizon-mod run` builds the `.hmod` and starts the game with it as a dev mod; after an edit, `cargo horizon-mod build` and the running game reloads it. -4. Content mods: [Content mods (API 0.2)](../mods.md#content-mods-api-02). +4. `cargo horizon-mod test` runs the mod's `tests/*.toml` scripts in the sandbox, with no game: ticks, commands, + chat lines and the player's position in, chat, feedback and the HUD panel checked + ([Testing a mod](../mods.md#testing-a-mod)). +5. Content mods: [Content mods (API 0.2)](../mods.md#content-mods-api-02). ## Reference @@ -94,11 +97,12 @@ What real mods need next, in the order modpacks and servers need it: - **Config**: typed settings the game shows and stores for the mod, on the server too. - **Keys and the crosshair target**: keybinds in Controls; what the player is looking at. - **Script mods and other languages**: see [Ways in](#ways-in). -- **SDK**: a headless test runner (load a mod, feed it ticks and events, assert on its output, no window), templates - per kind of mod, typed wrappers in the SDK for every interface. Dev mods already reload when rebuilt. +- **SDK**: templates per kind of mod, typed wrappers in the SDK for every interface. Dev mods already reload when + rebuilt, and `cargo horizon-mod test` runs a mod headless. ## Changelog +- SDK: `cargo horizon-mod test` and `horizon_mods::testing`, test scripts in TOML; the template has one. - Experimental: `ui` button widget; `render.set-corner`, `text-width`, `frame-stats`; `input.mapping`, `clicks-per-second` (what the official FPS, keystrokes and zoom mods need). - Experimental `input` (`experimental = ["input"]`): `claim-items`, `register-key`, `held`, `poll` (use-start, diff --git a/docs/api/shaders.md b/docs/api/shaders.md index 675c5e3fc..7461332e4 100644 --- a/docs/api/shaders.md +++ b/docs/api/shaders.md @@ -91,11 +91,12 @@ pack exist ([stability.md](stability.md)). ## Not there yet -The stages and everything that runs a pack (the format above is read and checked). The order: the renderer hooks shared with the format loader, then the material and post -stages with options and hot reload, then the overlay, lighting, sky and shadow stages. +The material stage in the game (the sky and post stages run, with hot reload), option values other than the defaults, +then the overlay, lighting and shadow stages. ## Changelog +- 2026-10-26: the sky stage in the game: the pack's `sky` gets vanilla's colour along each ray. - 2026-10-26: the post stage in the game (`HORIZON_SHADER_PACK`, hot reload with the last good pack kept). - 2026-10-25: `horizon-shader` (`new`, `check`, `pack`), three templates, the example pack and the guide. - 2026-10-25: the check (naga validation, signatures, options, budgets, SPIR-V/Metal/HLSL translation). diff --git a/docs/api/stability.md b/docs/api/stability.md index d5bd0e545..5c1b32362 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -114,3 +114,7 @@ Deprecations and breaking changes are in bold. The release notes of the game rel 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. +- **`render.set-minimap`** draws a map the game makes, not one a mod composes: reading the blocks around the player + for a map image costs too much through hook calls, so the game keeps the tiles (vanilla's map colours) and the mod + picks the corner, side, scale and shape. One map shows at a time, the first loaded mod's. It is a new function and a + new type, so mods built before it keep loading. diff --git a/docs/extras.md b/docs/extras.md index 26ddbe161..ac0196c17 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, 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,10 +10,10 @@ 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) | +| 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` | -| Minimap colours, tiles and image | `crates/horizon-client/src/minimap.rs` | +| HUD drawing (a mod's minimap, corner stacking) | `crates/horizon-client/src/extras_hud.rs` | +| Minimap colours, tiles and image (for `render.set-minimap`) | `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` | | Mouse Tweaks-style controls, sort buttons | `crates/horizon-client/src/game/tweaks.rs` | @@ -35,10 +34,9 @@ extras stay out of the way of other input and options work. `horizon-graphics.txt`. `options.txt` is untouched, so a vanilla client can share the folder. Unknown or broken lines fall back to the defaults. -The zoom key is a Horizon setting stored in that file (`zoomKey:key.keyboard.z`) -and bound on the Extras page, not in vanilla's Key Binds screen: Horizon has no -Horizon category in Controls, and adding one would put a non-vanilla mapping into -`options.txt`. +Extras' keys (the sort key) are Horizon settings stored in that file and bound on +the Extras page, not in vanilla's Key Binds screen: Horizon has no Horizon category +in Controls, and adding one would put a non-vanilla mapping into `options.txt`. ## The extras @@ -62,50 +60,25 @@ Horizon category in Controls, and adding one would put a non-vanilla mapping int - Off: nothing is gathered and the shaders' loop runs zero times (the count is 0), so it costs nothing measurable (numbers in the pull request, #814). -### Zoom (`zoom`, default off) -- Hold the zoom key (default **Z**, unused by every vanilla 26.3 key mapping; C - is `key.saveToolbarActivator`) to zoom. The key does nothing while zoom is off. -- It zooms only while playing: in chat, signs, books, text fields and every - other screen the key is typed or handled as usual. The key is never taken - from vanilla's mappings: one bound to the same key still acts (a key bound - twice triggers both, as vanilla's do), and the Extras page marks the zoom key - "Also bound" and names the mapping. -- Starts at the default level (4x, settable 2x to 10x); the scroll wheel changes - it while the key is held (and does not move the hotbar then). -- **Smooth** (default on) goes through vanilla's own FOV easing: the zoom divides - the field-of-view modifier target `Camera.tickFov` eases toward, the path the - spyglass uses (`AbstractClientPlayer.getFieldOfViewModifier` returns 0.1 while - scoping). The modifier keeps vanilla's 0.1 floor, so 10x is the deepest zoom. - Off applies the zoom to the final FOV with no easing. -- While scoping with a spyglass the zoom does nothing: the spyglass view and its - overlay stay exactly vanilla's. -- **Slower turning** (default on) divides mouse turning by the zoom factor. -- With zoom off (or the key up) the FOV target and mouse are vanilla's, bit for - bit; the FOV harness covers this. +### Moved to the mod browser -### 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). +The **FPS counter**, **Keystrokes**, **Zoom** and the **Minimap** 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 (Zoom's key too, into +`horizon-mods.txt`, when it wasn't Z), and reads one line in the chat ("Zoom 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`. -### 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. - -### Minimap (`minimap`, default off) -- A corner map (top right by default), square or round, small/medium/large, - zoom 0.5 to 4 blocks per pixel, rotating with the player or north up, with the - player arrow (vanilla's map decoration sprite). -- Colours are vanilla's `MapColor` per block, as map items use, with the map - item's height shading and water-depth dithering. -- Underground, in the Nether and under any roof, it maps the floor around the - player's height instead of the top block, so caves read sensibly. -- Cost: one cached 16x16 tile per loaded chunk (packed map colour and height). - Tiles are filled nearest first and refreshed when blocks change, within a time - budget of 0.3 ms a frame; composing the 128x128 image is a few thousand - lookups, done only when the view moved or a tile changed, and uploaded into a - dedicated atlas slot. With the minimap off nothing runs. +The game still draws the minimap, for the mod (`render.set-minimap`, [mods.md](mods.md)): +- a corner map (top right by default), square or round, small/medium/large, zoom 0.5 to 4 blocks per pixel, rotating + with the player or north up, with the player arrow (vanilla's map decoration sprite); +- vanilla's `MapColor` per block, as map items use, with the map item's height shading and water-depth dithering; +- underground, in the Nether and under any roof, the floor around the player's height instead of the top block; +- one cached 16x16 tile per loaded chunk (packed map colour and height), filled nearest first and refreshed when + blocks change within 0.3 ms a frame; the 128x128 image is recomposed only when the view moved or a tile changed, and + uploaded into a dedicated atlas slot. With no mod showing a map, nothing runs. ### Auto-reconnect (`autoReconnect`, default off) - On the "Connection lost" screen after a multiplayer connection drops, a @@ -162,11 +135,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 a mod's 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 +A mod's minimap stays under 0.3 ms of CPU per frame (tile budget) plus a 64 KiB texture upload when its image changes. diff --git a/docs/horizon-ctl-commands.md b/docs/horizon-ctl-commands.md index 394aac5bf..9b3d792c7 100644 --- a/docs/horizon-ctl-commands.md +++ b/docs/horizon-ctl-commands.md @@ -94,7 +94,7 @@ Every command `horizon-ctl` takes, its MCP tool in `horizon-ctl mcp` (the launch | `respawn` | `respawn` | Respawn from the death screen | none | | `pause` | `pause` | Open the pause menu | none | | `resume` | `resume` | Leave the pause menu | none | -| `options [PAGE]` | `options` | Open the options screen, or one of its pages (Horizon's too) | `page` (main, video, sound, controls, keybinds, controller, controller-binds, mouse, chat, accessibility, language, font, packs, mods, graphics, graphics-advanced, extras, horizon, agent): the page (default: the main options) | +| `options [PAGE]` | `options` | Open the options screen, or one of its pages (Horizon's too) | `page` (main, video, sound, controls, keybinds, controller, controller-binds, mouse, chat, accessibility, language, font, packs, mods, shader-packs, graphics, graphics-advanced, extras, horizon, agent): the page (default: the main options) | | `book [next\|back\|take\|done]` | `book` | The open book or lectern: its page text, or press one of its buttons | `action` (next, back, take, done): a button to press | | `signedit X Y Z [front\|back]` | `signedit` | Open the sign editor of the sign at X Y Z (then type and close) | `x` (integer, required): block X
`y` (integer, required): block Y
`z` (integer, required): block Z
`side` (front, back): which side | | `mount-menu` | `mount_menu` | Open the inventory of the horse, donkey, mule or llama being ridden | none | diff --git a/docs/mods.md b/docs/mods.md index 2895f897e..e13e362e5 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,9 +15,9 @@ 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, Minimap | | Runtime | `crates/horizon-mods` | wasmtime 48 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`) | +| Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / test / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | | Launcher mod browser (Modrinth, CurseForge with a key) | [mod-browser.md](mod-browser.md) | resource packs, modpacks | | Registry index (`index.json`, `.hpack`), signatures | `horizon_mods::index`, [api/mod-index.md](api/mod-index.md) | schema 1; launcher and website next | @@ -89,7 +89,7 @@ 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; `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"]` | +| `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); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). 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..: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 | @@ -220,11 +220,12 @@ Benchmarks (`--benchmark`) never load mods. ```sh rustup target add wasm32-unknown-unknown cargo install --git https://github.com/ludovic111/horizon cargo-horizon-mod -cargo horizon-mod new my-mod # Cargo.toml, horizon-mod.toml, src/lib.rs +cargo horizon-mod new my-mod # Cargo.toml, horizon-mod.toml, src/lib.rs, tests/hello.toml # (--template content: a content mod, no code) cd my-mod cargo horizon-mod run # build, then start the game with it cargo horizon-mod build # again after an edit: the running game reloads it +cargo horizon-mod test # build, then run tests/*.toml with no game ``` `run` starts `horizon-client` (on `PATH`, or `--game PATH`, or @@ -245,13 +246,73 @@ and each of its commands: it must start and never trap or overrun. It checks a `.hpack` and a resource pack `.zip` too, and a signature with `--key --signature .minisig`. +### Testing a mod + +`cargo horizon-mod test` builds the mod, then runs each `tests/.toml` in +the sandbox the game uses, with no game and no window: the test plays the +game's part (the player and the clock the mod reads, ticks, frames, chat lines, +commands) and checks what the mod showed. A script fails at its first wrong +step, with what it expected and what it got; the command fails if any script +does. `--debug` builds without optimizing, `--hmod ` tests a `.hmod` +already built, and a name runs only the scripts whose path holds it. Each +script gets a scratch copy of the mod, so its `storage` starts empty and is +removed afterwards. + +```toml +# tests/panel.toml (examples/coords-hud) +[player] # where the script starts; unset fields keep the defaults +x = 12.5 # (0.5 64 0.5, yaw 0, 20 health and food, the Overworld) +z = -3.25 +yaw = 180.0 + +[clock] # day-time 0 is 6:00 on day 1; each tick adds one +day-time = 29999 + +[[step]] +ticks = 1 +expect.panel = ["XYZ 12.5 / 64.0 / -3.2", "Facing North (-Z)", "Day 2, 12:00"] +expect.corner = "top-left" + +[[step]] +command = "coords" +expect.feedback = "Coordinates panel hidden" +``` + +A step's parts happen in this order: + +| Key | Does | +| --- | --- | +| `reload = true` | stops the mod and starts it again, as a rebuild does in the game: its memory starts over, its `storage` stays | +| `title-screen = true` | no player and no clock until a step sets them | +| `player = { x = 3.0, ... }`, `clock = { day-time = 0 }` | changes those fields (`x y z yaw pitch health food dimension`, `game-time day-time`) | +| `ticks = n`, `frames = n` | that many ticks (the game's tick counter and the clock move on), then frames 1/60 s apart | +| `chat = " hi"` | a chat line the player receives | +| `command = "where north"` | the player types `/where north`; a command the mod doesn't own fails the step | + +Then `expect` checks what the mod did during the step; a key left out is not +checked: + +| `expect.` | Checks | +| --- | --- | +| `commands = ["where"]` | the commands the mod owns | +| `chat = ["..."]` | every chat line it showed, in order (`[]`: none) | +| `feedback = "..."`, `error = "..."` | the command's answer, shown plain or in red | +| `panel = ["..."]`, `corner = "top-left"` | its HUD panel's lines (`[]`: no panel) and corner | +| `stopped = "panic"` | the mod was turned off, for a reason holding this text; without it, a mod that traps, panics or overruns fails the test | + +Unknown keys are errors, so a typo never passes silently. The same runner is +`horizon_mods::testing` for Rust code that drives a mod (`TestGame`, +`Script`): Horizon's own tests run the examples' scripts with it. Scripts test +any mod, whatever it was written in. + ### Template layout ``` my-mod/ ├── Cargo.toml # cdylib, horizon-mod-sdk, release: opt-level "s", LTO ├── horizon-mod.toml # the manifest -└── src/lib.rs # impl Mod, export_mod! +├── src/lib.rs # impl Mod, export_mod! +└── tests/hello.toml # cargo horizon-mod test ``` A mod is a type implementing `horizon_mod_sdk::Mod`; its state lives in the @@ -428,6 +489,8 @@ 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` | +| Minimap | `minimap` | Extras > Minimap | `corner`: as above, default `top_right`; `size`: `64`, `96` (default), `128`; `shape`: `square` (default), `round`; `zoom` (blocks per pixel): `0.5`, `1` (default), `2`, `4`; `rotate`: `false` (default), `true`. The game draws the map (`render.set-minimap`) | ## Versions and compatibility diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index e8e030c83..846a24e18 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -53,7 +53,7 @@ A harness can declare, at the top level of its script: ### Which harnesses a change affects -`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `.local/parity-runner/reach-cache.json`. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. +`--changed` and `--changed-files` narrow each harness's Rust sources to those its probes can reach (`tools/parity_reach.py`), so a change to one module of `horizon-client` no longer reruns every harness whose probe links the crate. The narrowing works on items, not files: from the probe modules a harness ran (or the binary it built), a free item (fn, type, const, static) is reached when a reached item names it in its own module, through a path or an import of a module that is named, or through a glob import; an inherent impl's methods count one by one once their type is reached and their name is mentioned; a trait impl counts once its trait and its type are reached (std's traits and types always are); a macro counts once invoked. Names match by spelling, so the result only over-approximates. A reached file's parent modules count through their `mod` declarations of it, compared with the merge base; Rust files a change adds take part, a dependency that was deleted counts as changed, code under `#[cfg(test)]` never counts, and a harness whose probe can't be found keeps every source. Parses are cached by content in `reach-cache.json` of the shared parity folder (beside `passes/`), so a new worktree starts warm; a harness's search stops as soon as it reaches a changed file, and after `PARITY_REACH_BUDGET` seconds (default 180) the remaining harnesses count every source their probes link, so choosing never holds a slow machine for long. `--by-crate` turns the narrowing off. On the last 20 pull requests merged on 2026-10-25, the harnesses picked went from 2255 to 1061 (2384 to 1592 harness-minutes; game-binary harnesses, which link all of `game/`, set the floor), and every harness a CI parity run failed in the week before was still picked; every source file a sample of probes executed (LLVM `-C instrument-coverage`) is among those kept. Building the graph takes 15 s cold, under a second warm, and up to a minute and a half on a change that reaches many harnesses. ## The gate diff --git a/docs/shaders.md b/docs/shaders.md index 394397193..d64ca041c 100644 --- a/docs/shaders.md +++ b/docs/shaders.md @@ -13,9 +13,9 @@ Horizon's own format. | Authoring tool | `horizon-shader` (same crate) | `new`, `check`, `pack` | | Templates | `crates/horizon-shader-api/templates/` | post, sky, material | | Example pack | `crates/horizon-shader-api/packs/golden_hour` | a warm sky and two post passes | -| In the game: the post stage | `HORIZON_SHADER_PACK=` (for development, until the Shader Packs page) | post passes, hot reload | +| In the game: the sky and post stages | Options > Horizon Settings > Shader Packs | sky, post passes, hot reload | | The registry and the launcher | `shader` kind ([api/mod-index.md](api/mod-index.md)); the Mods page's Shader packs tab | checked, then installed into `shaderpacks/` | -| In the game: sky and material | | not yet | +| In the game: the material stage | | not yet | ## Quick start @@ -47,12 +47,14 @@ my_pack 0.1.0 (shader API 0.1): FAILED ## Trying a pack in the game -Until the Shader Packs page lists them, put the pack folder (or its `.hshader`) in `shaderpacks/` beside `options.txt` -and start the game with `HORIZON_SHADER_PACK=`. The game checks the pack first, and refuses -one that fails, with its problems in the chat. While it runs, the game looks at the pack twice a second: save a file +Put the pack folder (or its `.hshader`) in `shaderpacks/` beside `options.txt` (Open Pack Folder opens it) and pick +it on Options > Horizon Settings > Shader Packs, which lists Horizon's packs, marked (Horizon), beside packs in the +`shaders/` format; one runs at a time, and clicking it again turns it off. `HORIZON_SHADER_PACK=` runs a pack whatever the page says, for development. The game checks the pack first, and refuses one that +fails, with its problems in the chat. While it runs, the game looks at the pack twice a second: save a file and the pack is checked and rebuilt in place ("Shader pack ... reloaded"); if the new version fails, the chat says -where and the last good version keeps drawing. The post passes run today; the sky and material stages are checked -but not drawn yet. +where and the last good version keeps drawing. The sky and post stages run today; the material stage is checked but +not drawn yet. ## A pack @@ -87,7 +89,7 @@ by Horizon: a pack changes how things look, not how they are drawn. | Stage | Your function | What it does | | --- | --- | --- | -| `[sky]` | `fn sky(input: SkyInput) -> vec4` | the sky's colour along each view ray; the sun, moon, stars and clouds are drawn over it | +| `[sky]` | `fn sky(input: SkyInput) -> vec4` | the sky's colour along each view ray, opaque (alpha is ignored), drawn where vanilla draws its sky dome (the Overworld's sky; not the Nether's or the End's); the sun, moon, stars and clouds are drawn over it | | `[material]` | `fn material(input: MaterialInput) -> Surface` | the lit colour of each point of a block's surface, before the alpha test and fog | | `[[post]]` | `fn post(input: PostInput) -> vec4` | a full-screen pass over the world's picture (up to 8, in order), under the hand and HUD | @@ -128,11 +130,11 @@ one keeps drawing), the launcher before it installs one, and the registry's CI b 6. Every entry point translated for Vulkan (SPIR-V), Metal and DirectX 12 (HLSL), with the options at their defaults, minimums and maximums. -`[budget] gpu_ms` is the GPU time your pack aims to add to a frame; the game's overlay will show each pass's time -against it. +`[budget] gpu_ms` is the GPU time your pack aims to add to a frame. To compare, open F3 in the game: while it is +open, each pass is timed on the GPU and the overlay shows the pack's total and its costliest passes, by their `name` +(the median of the last 15 timed frames). Timing waits for nothing, so it does not slow the game. In a timed frame the sky +stage draws in a pass of its own (it shares the world's pass otherwise), so its time includes clearing the picture. ## Next -The renderer hooks (shared with the Iris/OptiFine loader), then the post stage in the game with hot reload and the -GPU time per pass, Options > Shader packs listing these packs, then the material and sky stages, and the registry's -`shader` kind with installs from the launcher. +The material stage in the game. diff --git a/mods/official/minimap/Cargo.toml b/mods/official/minimap/Cargo.toml new file mode 100644 index 000000000..e6aafb7c4 --- /dev/null +++ b/mods/official/minimap/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "minimap" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official minimap: a map of the terrain around you in a corner." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/minimap/horizon-mod.toml b/mods/official/minimap/horizon-mod.toml new file mode 100644 index 000000000..51bd7ef94 --- /dev/null +++ b/mods/official/minimap/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "minimap" +name = "Minimap" +version = "1.0.0" +description = "A map of the terrain around you in a corner, in map colours, square or round, north up or turning with you. Horizon's own, formerly an extra." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["render", "ui", "storage"] +experimental = ["render", "ui"] diff --git a/mods/official/minimap/src/lib.rs b/mods/official/minimap/src/lib.rs new file mode 100644 index 000000000..ea8c45b72 --- /dev/null +++ b/mods/official/minimap/src/lib.rs @@ -0,0 +1,135 @@ +//! Horizon's official minimap, formerly the built-in extra: a map of the +//! terrain around the player in a corner (`render.set-minimap`; the game +//! keeps its tiles). Its settings page has the extra's five options, kept in +//! the mod's storage (`corner`, `size`, `shape`, `zoom`, `rotate`) with the +//! extra's values, where the game writes a player's old extra settings when +//! it installs the mod for them. +use horizon_mod_sdk::{ + Mod, Registration, + render::{self, Corner, Minimap as MapView}, + storage, + ui::{self, ButtonWidget, Widget}, +}; + +/// (corner, stored value, label), in the extra's order. +const CORNERS: [(Corner, &str, &str); 4] = [ + (Corner::TopLeft, "top_left", "Top left"), + (Corner::TopRight, "top_right", "Top right"), + (Corner::BottomLeft, "bottom_left", "Bottom left"), + (Corner::BottomRight, "bottom_right", "Bottom right"), +]; +/// (side in GUI pixels, label). +const SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")]; +/// Blocks per map pixel. +const ZOOMS: [f32; 4] = [0.5, 1.0, 2.0, 4.0]; +/// Settings page buttons. +const CORNER_BUTTON: u32 = 1; +const SIZE_BUTTON: u32 = 2; +const SHAPE_BUTTON: u32 = 3; +const ZOOM_BUTTON: u32 = 4; +const ROTATE_BUTTON: u32 = 5; + +/// Indexes into the tables above, and the two switches. +struct Minimap { + corner: usize, + size: usize, + round: bool, + zoom: usize, + rotate: bool, +} + +impl Minimap { + fn show(&self) { + render::set_minimap(Some(MapView { + corner: CORNERS[self.corner].0, + size: f32::from(SIZES[self.size].0), + blocks_per_pixel: ZOOMS[self.zoom], + rotate: self.rotate, + round: self.round, + })); + } + fn page(&self) { + let button = |id, label: String| Widget::Button(ButtonWidget { id, label }); + let n = ZOOMS[self.zoom]; + let blocks = if n < 1.0 { + "½ block".to_owned() + } else if n == 1.0 { + "1 block".to_owned() + } else { + format!("{n} blocks") + }; + ui::set_settings(&[ + button(CORNER_BUTTON, format!("Corner: {}", CORNERS[self.corner].2)), + button(SIZE_BUTTON, format!("Size: {}", SIZES[self.size].1)), + button( + SHAPE_BUTTON, + format!("Shape: {}", if self.round { "Round" } else { "Square" }), + ), + button(ZOOM_BUTTON, format!("Zoom: {blocks} per pixel")), + button( + ROTATE_BUTTON, + format!( + "Turn with the player: {}", + if self.rotate { "ON" } else { "OFF" } + ), + ), + ]); + } + fn save(&self) { + let _ = storage::set("corner", CORNERS[self.corner].1.as_bytes()); + let _ = storage::set("size", SIZES[self.size].0.to_string().as_bytes()); + let _ = storage::set("shape", if self.round { b"round" } else { b"square" }); + let _ = storage::set("zoom", ZOOMS[self.zoom].to_string().as_bytes()); + let _ = storage::set("rotate", if self.rotate { b"true" } else { b"false" }); + } +} + +fn stored(key: &str) -> Option { + storage::get(key) + .and_then(|v| String::from_utf8(v).ok()) + .map(|v| v.trim().to_owned()) +} + +impl Mod for Minimap { + fn init() -> Result<(Self, Registration), String> { + // The extra's defaults: top right, medium, square, 1 block per + // pixel, north up. An unknown value keeps the default. + let find = |key: &str, values: &[String], default: usize| { + stored(key) + .and_then(|v| values.iter().position(|s| *s == v)) + .unwrap_or(default) + }; + let corners: Vec = CORNERS.iter().map(|c| c.1.to_owned()).collect(); + let sizes: Vec = SIZES.iter().map(|s| s.0.to_string()).collect(); + let zooms: Vec = ZOOMS.iter().map(f32::to_string).collect(); + let map = Minimap { + corner: find("corner", &corners, 1), + size: find("size", &sizes, 1), + round: stored("shape").as_deref() == Some("round"), + zoom: find("zoom", &zooms, 1), + rotate: stored("rotate").as_deref() == Some("true"), + }; + map.show(); + map.page(); + Ok((map, Registration::new())) + } + fn ui_select(&mut self, id: u32, _row: u32) { + let next = |i: usize, n: usize| (i + 1) % n; + match id { + CORNER_BUTTON => self.corner = next(self.corner, CORNERS.len()), + SIZE_BUTTON => self.size = next(self.size, SIZES.len()), + SHAPE_BUTTON => self.round = !self.round, + ZOOM_BUTTON => self.zoom = next(self.zoom, ZOOMS.len()), + ROTATE_BUTTON => self.rotate = !self.rotate, + _ => return, + } + self.save(); + self.show(); + self.page(); + } + fn ui_settings_opened(&mut self) { + self.page(); + } +} + +horizon_mod_sdk::export_mod!(Minimap); diff --git a/mods/official/zoom/Cargo.toml b/mods/official/zoom/Cargo.toml new file mode 100644 index 000000000..2225b00e8 --- /dev/null +++ b/mods/official/zoom/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "zoom" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official zoom: hold a key to zoom, the wheel changes it while held." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/zoom/horizon-mod.toml b/mods/official/zoom/horizon-mod.toml new file mode 100644 index 000000000..bd699d0b5 --- /dev/null +++ b/mods/official/zoom/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "zoom" +name = "Zoom" +version = "1.0.0" +description = "Hold a key to zoom in; the mouse wheel changes the zoom while you hold it. Horizon's own, formerly an extra." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["render", "input", "ui", "storage"] +experimental = ["render", "input", "ui"] diff --git a/mods/official/zoom/src/lib.rs b/mods/official/zoom/src/lib.rs new file mode 100644 index 000000000..072a40eb0 --- /dev/null +++ b/mods/official/zoom/src/lib.rs @@ -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, +} + +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 { + 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::().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); diff --git a/tests/test_parity_reach.py b/tests/test_parity_reach.py index 9b7464b47..07e3df9e3 100644 --- a/tests/test_parity_reach.py +++ b/tests/test_parity_reach.py @@ -101,6 +101,16 @@ class ReachTests(unittest.TestCase): (self.root / "crates/a/src/unused.rs").unlink() self.assertIn("crates/a/src/unused.rs", self.narrowed()) + def test_a_search_told_to_stop_still_keeps_the_file_it_stopped_at(self): + graph = parity_reach.SourceGraph(self.root, parity.rust_code) + kept = parity_reach.narrow(self.dependencies, PROBE, graph, {"crates/a/src/used.rs"}, {"crates/a/src/used.rs"}) + self.assertEqual(kept["crates/a/src/used.rs"], (True, set())) + self.assertFalse(graph.results, "a partial search is not remembered") + # A stop file outside the harness's sources doesn't end its search. + full = parity_reach.narrow(self.dependencies, PROBE, graph, (), {"crates/b/src/lib.rs"}) + self.assertIn("crates/a/src/display.rs", full) + self.assertTrue(graph.results) + def test_unknown_probes_keep_everything(self): self.assertEqual(set(self.narrowed(artifacts=[])), set(self.dependencies)) self.assertEqual(set(self.narrowed(artifacts=[["example", "missing", "release", ["-p", "a"], True]])), diff --git a/tools/parity.py b/tools/parity.py index 3f18b922d..285e7268b 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -1245,14 +1245,20 @@ def affected_harnesses(found, records, changed, reach=True, base=None): commit), only declarations of modules the harness doesn't reach changed (tools/parity_reach.py).""" if changed & SHARED_INPUTS: return set(found) - graph = None + graph, stop = None, frozenset() + # Parses are keyed by content, so every worktree sharing the vanilla data shares them. + cache_path = (SHARED if SHARED.is_dir() else STATE_DIR) / "reach-cache.json" if reach and any(path.startswith("crates/") for path in changed): - cache_path = STATE_DIR / "reach-cache.json" try: cache = json.loads(cache_path.read_text(encoding="utf-8")) except (OSError, ValueError): cache = {} graph = parity_reach.SourceGraph(ROOT, rust_code, cache) + # A changed file that differs in more than its `mod` declarations counts as soon as a harness reaches it, + # so the search for that harness can stop there. + stop = frozenset(path for path in changed if parity_reach.is_workspace_rust(path) + and parity_reach.declarations_changed(ROOT, path, (), base, True)) + budget, started, over = float(os.environ.get("PARITY_REACH_BUDGET") or 180), time.monotonic(), False affected = set() for name, script in found.items(): record = records.get(name) or {} @@ -1265,16 +1271,31 @@ def affected_harnesses(found, records, changed, reach=True, base=None): affected.add(name) continue plain = {path.split(KEEP)[0] for path in dependencies} - if graph is not None and plain & changed: - narrowed = parity_reach.narrow(dependencies, recorded_artifacts(record), graph, changed) - if any(path.split(KEEP)[0] in changed and (children is None or parity_reach.declarations_changed( - ROOT, path.split(KEEP)[0], children, base, whole)) for path, (whole, children) in narrowed.items()): - affected.add(name) - elif plain & changed: + hit = plain & changed + if not hit: + continue + if graph is None or any(not path.startswith("crates/") for path in hit): + affected.add(name) # no narrowing, or a file narrowing always keeps (tools/, Java oracles) + continue + if not over and time.monotonic() - started > budget: + over = True + print(f"note: choosing harnesses took over {budget:.0f} s (PARITY_REACH_BUDGET): the rest count every " + "source their probes link", flush=True) + if over: + affected.add(name) + continue + narrowed = parity_reach.narrow(dependencies, recorded_artifacts(record), graph, changed, stop) + if any(path.split(KEEP)[0] in changed and (children is None or parity_reach.declarations_changed( + ROOT, path.split(KEEP)[0], children, base, whole)) for path, (whole, children) in narrowed.items()): affected.add(name) if graph is not None: - STATE_DIR.mkdir(parents=True, exist_ok=True) - cache_path.write_text(json.dumps(graph.saved_cache()), encoding="utf-8") + saved = graph.saved_cache() + if len(cache) + len(saved) < 4 * max(len(saved), 1): + saved = {**cache, **saved} # other worktrees' versions of the files too, within bounds + cache_path.parent.mkdir(parents=True, exist_ok=True) + temporary = cache_path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text(json.dumps(saved), encoding="utf-8") + temporary.replace(cache_path) return affected diff --git a/tools/parity_reach.py b/tools/parity_reach.py index 0c3051b86..dc61f6215 100644 --- a/tools/parity_reach.py +++ b/tools/parity_reach.py @@ -25,8 +25,9 @@ assets, fonts) that only unreached sources name; a dependency that no longer exi a change adds take part. """ +import functools import hashlib -from pathlib import Path, PurePosixPath +from pathlib import Path import re import subprocess @@ -478,9 +479,10 @@ class SourceGraph: seeds=seeds, node_sets={}) return self.tables - def reachable(self, entries, universe, reasons=None): + def reachable(self, entries, universe, reasons=None, stop=frozenset()): """The files of universe (workspace Rust sources) holding an item reachable from entries (by the rules in - this module's doc), and the entries. reasons, a dict, gets why each file was reached (for debugging).""" + this module's doc), and the entries. reasons, a dict, gets why each file was reached (for debugging). The + search ends early, with only part of the answer, once it reaches a file of stop.""" # Searching every source of the crates involved (not only those Cargo listed) only adds reach, and lets # harnesses with the same entries (the game binary's) share one search. crates = frozenset(crate_of(path) for path in universe) @@ -488,11 +490,12 @@ class SourceGraph: if reasons is None and key in self.results: return self.results[key] & set(universe) everything = {path for path in self.files if crate_of(path) in crates} | set(universe) - files = self.search(entries, everything, reasons) - self.results[key] = files + files, complete = self.search(entries, everything, reasons, stop) + if complete: + self.results[key] = files return files & set(universe) - def search(self, entries, universe, reasons): + def search(self, entries, universe, reasons, stop=frozenset()): targets = {self.target(path) for path in entries} universe = {path for path in universe if (self.is_library(path) or self.target(path) in targets) and path not in self.test_only} @@ -600,71 +603,80 @@ class SourceGraph: files.add(path) if reasons is not None: reasons[path] = why + if path in stop: + raise Stop - for path in universe: - if path.endswith("/src/lib.rs") or path in entries or path not in self.parent: - open_module(path, "crate root or entry") - for node in seeds: - reach(node, "entry" if node[0] in entries else "always counted") - for path in entries & universe: - files.add(path) - if reasons is not None: - reasons.setdefault(path, "entry") - while queue: - node = queue.pop() - path, index, member = node - item = item_of(node) - crate = crate_of(path) - label = (item.get("names") or [item["kind"]])[0] if member is None else item["members"][member]["name"] - source = sets_of(node, item) - why = f"{path} ({label})" - # Plain mentions reach items of this file and of the modules above it. - ancestor, new = path, source["mentions"] - while ancestor is not None and new: - known = local.setdefault(ancestor, set()) - new = new - known - known |= new + try: + for path in universe: + if path.endswith("/src/lib.rs") or path in entries or path not in self.parent: + open_module(path, "crate root or entry") + for node in seeds: + reach(node, "entry" if node[0] in entries else "always counted") + for path in entries & universe: + files.add(path) + if reasons is not None: + reasons.setdefault(path, "entry") + while queue: + node = queue.pop() + path, index, member = node + item = item_of(node) + crate = crate_of(path) + label = (item.get("names") or [item["kind"]])[0] if member is None else item["members"][member]["name"] + source = sets_of(node, item) + why = f"{path} ({label})" + # Plain mentions reach items of this file and of the modules above it. + ancestor, new = path, source["mentions"] + while ancestor is not None and new: + known = local.setdefault(ancestor, set()) + new = new - known + known |= new + for name in new: + wake(by_file_name.get((ancestor, name), ()), f"{why} mentions {name}") + ancestor = self.parent.get(ancestor) + if item["kind"] == "use" and item["glob"]: + for name in item["names"]: + for target in sees.get(crate, {crate}): + for module in list(by_module.get((target, name), ())) + \ + ([f"crates/{idents[name]}/src/lib.rs"] if name in idents else []): + if module not in globbed and module in universe: + globbed.add(module) + wake([(module, index, None) for index in range(len(self.parse(module)["items"]))] + if self.parse(module) else [], f"{why} glob-imports {name}") + visible_to = sees.get(crate, {crate}) + new = source["paths"] - done["paths"].setdefault(crate, set()) + done["paths"][crate] |= new for name in new: - wake(by_file_name.get((ancestor, name), ()), f"{why} mentions {name}") - ancestor = self.parent.get(ancestor) - if item["kind"] == "use" and item["glob"]: - for name in item["names"]: - for target in sees.get(crate, {crate}): - for module in list(by_module.get((target, name), ())) + \ - ([f"crates/{idents[name]}/src/lib.rs"] if name in idents else []): - if module not in globbed and module in universe: - globbed.add(module) - wake([(module, index, None) for index in range(len(self.parse(module)["items"]))] - if self.parse(module) else [], f"{why} glob-imports {name}") - visible_to = sees.get(crate, {crate}) - new = source["paths"] - done["paths"].setdefault(crate, set()) - done["paths"][crate] |= new - for name in new: - for target in visible_to: - path_names.setdefault(target, set()).add(name) - for module in by_module.get((target, name), ()): - if module in universe and self.parent[module] in opened: - open_module(module, f"{why} names {name}") - for key, table, wanted in (("qualified", qualified, lambda other: True), - ("invokes", invoked, lambda other: item_of(other)["kind"] == "macro"), - ("mentions", mentioned, lambda other: other[2] is not None or other[0] in globbed)): - new = source[key] - done[key].setdefault(crate, set()) - done[key][crate] |= new - for name in new: - table.setdefault(name, set()).add(crate) - wake([other for other in by_name.get(name, ()) if crate_of(other[0]) in visible_to and wanted(other)], - f"{why} {key} {name}") - if item["kind"] in TYPE_KINDS and member is None: - own = types.setdefault(crate, set()) - local_types.setdefault(path, set()).update(names(node)) - if not names(node) <= own: - own |= names(node) - visible_cache.clear() - seeing = seen_by.get(crate, {crate}) - for name in names(node): # also when the crate has one by that name already: impls of this one - wake([other for other in by_type.get(name, ()) if crate_of(other[0]) in seeing], - f"implements for {name}, defined in {path}") - return files + for target in visible_to: + path_names.setdefault(target, set()).add(name) + for module in by_module.get((target, name), ()): + if module in universe and self.parent[module] in opened: + open_module(module, f"{why} names {name}") + for key, table, wanted in (("qualified", qualified, lambda other: True), + ("invokes", invoked, lambda other: item_of(other)["kind"] == "macro"), + ("mentions", mentioned, lambda other: other[2] is not None or other[0] in globbed)): + new = source[key] - done[key].setdefault(crate, set()) + done[key][crate] |= new + for name in new: + table.setdefault(name, set()).add(crate) + wake([other for other in by_name.get(name, ()) if crate_of(other[0]) in visible_to and wanted(other)], + f"{why} {key} {name}") + if item["kind"] in TYPE_KINDS and member is None: + own = types.setdefault(crate, set()) + local_types.setdefault(path, set()).update(names(node)) + if not names(node) <= own: + own |= names(node) + visible_cache.clear() + seeing = seen_by.get(crate, {crate}) + for name in names(node): # also when the crate has one by that name already: impls of this one + wake([other for other in by_type.get(name, ()) if crate_of(other[0]) in seeing], + f"implements for {name}, defined in {path}") + except Stop: + return files, False + return files, True + + +class Stop(Exception): + """A search reached a file it was told to stop at.""" def impl_subject(header): @@ -682,13 +694,19 @@ def impl_subject(header): return parameters, re.split(r"\bwhere\b", header)[0] +_CRATES = {} + + def crate_of(path): - return path.split("/", 2)[1] + """The crate folder of a crates//... path (called millions of times by a search: cached).""" + crate = _CRATES.get(path) + if crate is None: + crate = _CRATES[path] = path.split("/", 2)[1] + return crate def is_workspace_rust(path): - parts = PurePosixPath(path).parts - return len(parts) > 2 and parts[0] == "crates" and path.endswith(".rs") + return path.startswith("crates/") and path.endswith(".rs") and path.count("/") >= 2 DECLARATION_LINE = re.compile(rf"\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+({IDENT})\s*;") @@ -718,6 +736,11 @@ def declarations_changed(root, path, children, base, whole): missing.""" if base is None: return True + return _declarations_changed(str(root), path, frozenset(children), base, whole) + + +@functools.lru_cache(maxsize=None) +def _declarations_changed(root, path, children, base, whole): try: head = (Path(root) / path).read_text(encoding="utf-8", errors="replace") before = subprocess.run(["git", "show", f"{base}:{path}"], cwd=root, capture_output=True, text=True, check=True).stdout @@ -726,36 +749,37 @@ def declarations_changed(root, path, children, base, whole): return declarations(head, children, whole) != declarations(before, children, whole) -def narrow(dependencies, artifacts, graph, changed=()): +def narrow(dependencies, artifacts, graph, changed=(), stop=frozenset()): """A harness's dependencies narrowed to what its entry points can reach: {dependency: (whole, children)}, where whole says the file counts for its own content (else only through its `mod` declarations of children, as a module ancestor of a reached file) and children are its reached child modules. Without known entry points (a - probe or binary the harness built that isn't found here), every dependency is kept whole.""" + probe or binary the harness built that isn't found here), every dependency is kept whole. The search may end + as soon as it reaches a file of stop (changed files that count once reached): then only part is returned.""" plain = [dependency.split("#keep:")[0] for dependency in dependencies] - crates = {PurePosixPath(path).parts[1] for path in plain if path.startswith("crates/")} + crates = {crate_of(path) for path in plain if path.startswith("crates/") and path.count("/") >= 2} rust = {path for path in plain if is_workspace_rust(path)} - added = {path for path in changed if is_workspace_rust(path) and PurePosixPath(path).parts[1] in crates + added = {path for path in changed if is_workspace_rust(path) and crate_of(path) in crates and path not in rust and (graph.root / path).is_file()} entries = graph.entries(artifacts, rust) if entries is None: return {dependency: (True, None) for dependency in dependencies} missing = {path for path in rust if graph.parse(path) is None} - reached = graph.reachable(entries, rust | added | entries) | missing + reached = graph.reachable(entries, rust | added | entries, stop=frozenset(stop) & (rust | added)) | missing named, named_in_crate = set(), {} for path in rust | added: parsed = graph.parse(path) file_names = set(parsed["file_names"]) if parsed else set() if path in reached: named |= file_names - named_in_crate.setdefault(PurePosixPath(path).parts[1], set()).update(file_names) + named_in_crate.setdefault(crate_of(path), set()).update(file_names) kept = {} for dependency, path in zip(dependencies, plain): if is_workspace_rust(path): if path in reached: kept[dependency] = (True, set()) elif not path.startswith("crates/") or path.endswith(("Cargo.toml", "build.rs")) \ - or PurePosixPath(path).name in named \ - or PurePosixPath(path).name not in named_in_crate.get(PurePosixPath(path).parts[1], ()): + or path.rsplit("/", 1)[-1] in named \ + or path.rsplit("/", 1)[-1] not in named_in_crate.get(crate_of(path), ()): kept[dependency] = (True, None) for path in sorted(added & reached): kept[path] = (True, set()) diff --git a/website/docs/index.md b/website/docs/index.md index 24f969840..5a64a4a8a 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -7,7 +7,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust. You install it with a - **A new game program, not a mod.** Horizon is written from scratch in Rust. It reads the same worlds, plays by the same rules and generates the same terrain as the Java game. - **Checked against vanilla.** {{HARNESSES}} automated tests ("harnesses") feed the same inputs to Horizon and to the real game, then compare the results. Today every subsystem matches in every harness that compares it. That is {{PERCENT}} of what the harnesses compare, which is not proof that nothing else differs. The [status table](/#parity) lists what is covered. - **Light and fast.** It starts quickly, uses little memory and draws efficiently. See [Performance](/docs/performance) for what is measured and what is not. -- **A few things vanilla doesn't have.** Its own settings, added to vanilla's menus the way mods add theirs, graphics presets, distant terrain, controller support, optional extras such as zoom, a minimap and dynamic lights, an invite code to play your world with friends, and a server you can run without Java. +- **A few things vanilla doesn't have.** Its own settings, added to vanilla's menus the way mods add theirs, graphics presets, distant terrain, controller support, optional extras such as dynamic lights, official mods such as zoom and a minimap, an invite code to play your world with friends, and a server you can run without Java. ## What Horizon is not diff --git a/website/docs/mods.md b/website/docs/mods.md index 405c62976..34330835d 100644 --- a/website/docs/mods.md +++ b/website/docs/mods.md @@ -32,7 +32,7 @@ cd my-mod cargo horizon-mod build ``` -The [Mod API](/docs/api/mods) lists what a mod can do today and what comes next, and its [reference](/docs/api/mods-reference) every function. Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](/docs/modpacks)). +`cargo horizon-mod test` runs the mod's test scripts (`tests/*.toml`: ticks, commands and the player's position in, chat and HUD lines checked) with no game open. The [Mod API](/docs/api/mods) lists what a mod can do today and what comes next, and its [reference](/docs/api/mods-reference) every function. Java mod jars don't run in Horizon: their code calls and patches Minecraft's Java classes, and Horizon has none. What carries over is the data and assets inside a jar ([modpacks](/docs/modpacks)). ## Finding resource packs and modpacks diff --git a/website/docs/settings.md b/website/docs/settings.md index 29eb0a760..1e36bee11 100644 --- a/website/docs/settings.md +++ b/website/docs/settings.md @@ -63,7 +63,7 @@ Horizon plays with PlayStation (DualShock 4 and DualSense), Xbox (360, One and S ## Extras -**Options, Horizon Settings, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, zoom, a minimap, an FPS counter, a keystroke display, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. One more is **dynamic lights**: a torch, lantern or other light source that you hold, that lies dropped as an item, or a burning mob, lights the blocks around it. It is client-side only, so other players do not see it. +**Options, Horizon Settings, Extras** holds small, optional conveniences. Every one is off by default, so a fresh install behaves like vanilla: fullbright, auto-reconnect, Mouse Tweaks-style inventory controls and inventory sorting. The FPS counter, the keystroke display, zoom and the minimap are official mods now, in **Options, Mods**: if you had one on, the game installed it for you on its first start after the update, with your settings. One more is **dynamic lights**: a torch, lantern or other light source that you hold, that lies dropped as an item, or a burning mob, lights the blocks around it. It is client-side only, so other players do not see it. ## Where your settings are stored