From 9e71837df99a26c8ec77922d2718e8daeb46b2bd Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:56:15 +0000 Subject: [PATCH 01/65] Keep server logging from panicking on a closed stdout pipe Co-Authored-By: OpenAI GPT-6.1 Sol --- crates/horizon-client/src/game/dedicated.rs | 112 +++++++++++++++++++- 1 file changed, 111 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..4a3b5b4ca 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -24,6 +24,7 @@ use horizon_client::{ use horizon_protocol::text::translatable; use horizon_world::nbt::{JavaString, Tag}; use std::{ + io::Write, path::PathBuf, sync::{Arc, Mutex, OnceLock, mpsc}, time::{Duration, Instant}, @@ -89,7 +90,9 @@ fn log_from(thread: &str, level: &str, message: &str) { } }); // Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log. - println!( + // The launcher can close its stdout pipe while the server keeps running. + let _ = writeln!( + std::io::stdout().lock(), "[{}] [{thread}/{level}]: {message}", chrono::Local::now().format("%H:%M:%S") ); @@ -1308,3 +1311,110 @@ fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?); Some((w, h)) } + +#[cfg(test)] +mod tests { + use super::{capture_log, log, log_from}; + use std::{ + fs, + io::{self, BufRead, BufReader, Read, Write}, + process::{Command, Stdio}, + time::{SystemTime, UNIX_EPOCH}, + }; + + const LOGIN: &str = "Player[/127.0.0.1:0] logged in with entity id 2 at (0.5, 115.0, 0.5)"; + const WARNING: &str = "Authentication warning"; + const READY: &str = "horizon-console-log-ready\n"; + const CHILD_HOME: &str = "HORIZON_TEST_CONSOLE_LOG_HOME"; + + fn assert_log_lines(text: &str) { + let expected = [ + format!("] [Server thread/INFO]: {LOGIN}"), + format!("] [User Authenticator #1/WARN]: {WARNING}"), + ]; + assert_eq!(text.lines().count(), expected.len()); + for (line, suffix) in text.lines().zip(expected) { + assert!(line.starts_with('[')); + assert!(chrono::NaiveTime::parse_from_str(&line[1..9], "%H:%M:%S").is_ok()); + assert_eq!(&line[9..], suffix); + } + } + + #[test] + fn console_logging_survives_closed_stdout() { + if let Some(home) = std::env::var_os(CHILD_HOME) { + horizon_client::logging::init(std::path::Path::new(&home), "Server thread"); + // Let the parent close the real stdout pipe only after libtest's startup output. + io::stdout().write_all(READY.as_bytes()).unwrap(); + io::stdout().flush().unwrap(); + io::stdin().read_exact(&mut [0]).unwrap(); + std::thread::Builder::new() + .name("Server thread".into()) + .spawn(|| { + let captured = capture_log(|| { + log("INFO", LOGIN); + log_from("User Authenticator #1", "WARN", WARNING); + }); + assert_eq!(captured, [LOGIN, WARNING]); + horizon_client::logging::flush(); + }) + .unwrap() + .join() + .unwrap(); + // Libtest's final status also writes to stdout; only the game logger is under test. + std::process::exit(0); + } + + for closed_stdout in [false, true] { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let home = std::env::temp_dir().join(format!( + "horizon-console-log-test-{}-{unique}", + std::process::id() + )); + fs::create_dir(&home).unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "game::dedicated::tests::console_logging_survives_closed_stdout", + "--nocapture", + ]) + .env(CHILD_HOME, &home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + loop { + let mut line = String::new(); + assert!( + stdout.read_line(&mut line).unwrap() > 0, + "child was not ready" + ); + if line.ends_with(READY) { + break; + } + } + if closed_stdout { + drop(stdout); // No reader remains: the next console write gets EPIPE. + } else { + child.stdout = Some(stdout.into_inner()); + } + child.stdin.take().unwrap().write_all(&[1]).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "closed_stdout={closed_stdout}: {}", + String::from_utf8_lossy(&output.stderr) + ); + if !closed_stdout { + assert_log_lines(std::str::from_utf8(&output.stdout).unwrap()); + } + assert_log_lines(&fs::read_to_string(home.join("logs/latest.log")).unwrap()); + fs::remove_dir_all(home).unwrap(); + } + } +} From 6f4c2cfbbc9dad4ef51e695c08a1d086fd88cf0d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:16:19 +0100 Subject: [PATCH 02/65] Count the hurt tilt down while the player is dead or riding --- crates/horizon-client/src/game/remote.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..54659e0f9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3219,6 +3219,11 @@ impl Game<'_> { resources: self.motion, } .controlled_simulation_tick(keys)?; + } else { + // LivingEntity.baseTick counts hurtTime down for a dead or riding + // player too (controlled_simulation_tick does it otherwise): left + // at 10, the hurt tilt restarted every frame and shook the camera. + player.health.advance_clock(); } // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. From cfd2dc83922ce606c518b085443d634f3931b23e Mon Sep 17 00:00:00 2001 From: Senjin Date: Mon, 26 Oct 2026 16:45:57 +0100 Subject: [PATCH 03/65] HDR: present HDR10 (PQ) where the surface offers it, scRGB otherwise HDR10 is what games usually present and what the display receives: a compositor composes in it or converts to it anyway. The NVIDIA driver offers it on Wayland next to scRGB. A 10-bit swapchain also halves the last pass's bandwidth; the frame before it is 8-bit, so nothing is lost. hdr.wgsl converts the same linear light to BT.2020 (BT.2087) and encodes it with the ST 2084 curve. HORIZON_HDR_OUTPUT=pq or scrgb allows only that one, for comparing them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 34 ++++----- crates/horizon-client/src/gfx/hdr.rs | 99 +++++++++++++++++++++++---- crates/horizon-client/src/graphics.rs | 2 +- crates/horizon-client/src/hdr.wgsl | 25 ++++++- docs/graphics.md | 2 +- 5 files changed, 127 insertions(+), 35 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 904370c04..86df94c0c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -505,10 +505,10 @@ pub struct Renderer { occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). world_post: world_post::Post, - /// HDR output (Horizon setting): `Some` while the swapchain is scRGB. + /// HDR output (Horizon setting): `Some` while the swapchain is HDR. hdr: Option, - /// Whether the window's surface can present scRGB. - hdr_capable: bool, + /// The HDR output the window's surface can present. + hdr_output: Option, /// 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. @@ -1057,7 +1057,7 @@ impl Renderer { let info = adapter.get_info(); crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info)); let size = window.inner_size(); - let (config, present_modes, hdr_capable) = if let Some(surface) = &surface { + let (config, present_modes, hdr_output) = if let Some(surface) = &surface { let mut config = surface .get_default_config(&adapter, size.width.max(1), size.height.max(1)) .ok_or("surface has no supported configuration")?; @@ -1085,7 +1085,7 @@ impl Renderer { )); } surface.configure(&device, &config); - (config, caps.present_modes.clone(), hdr::supported(&caps)) + (config, caps.present_modes.clone(), hdr::output(&caps)) } else { let format = wgpu::TextureFormat::Bgra8Unorm; let config = wgpu::SurfaceConfiguration { @@ -1099,7 +1099,7 @@ impl Renderer { view_formats: vec![format], color_space: wgpu::SurfaceColorSpace::default(), }; - (config, Vec::new(), false) + (config, Vec::new(), None) }; let offscreen = surface .is_none() @@ -2441,7 +2441,7 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, hdr: None, - hdr_capable, + hdr_output, pack_post: None, native: None, pass_timing: pack_timing::PassTiming::logging(), @@ -2961,24 +2961,24 @@ impl Renderer { } } /// The swapchain's configuration: `config` (what every pipeline draws in), or - /// scRGB while HDR output is on. + /// HDR10 or scRGB while HDR output is on. fn surface_config(&self) -> wgpu::SurfaceConfiguration { let mut config = self.config.clone(); - if self.hdr.is_some() { - config.format = hdr::FORMAT; - config.view_formats = vec![hdr::FORMAT]; - config.color_space = hdr::COLOR_SPACE; + if let Some(hdr) = &self.hdr { + config.format = hdr.output.format(); + config.view_formats = vec![hdr.output.format()]; + config.color_space = hdr.output.color_space(); config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT; } config } - /// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's + /// HDR output (Horizon setting): HDR10 or scRGB at `paper_white` nits, the world's /// highlights expanded up to `peak` nits. Off where the surface can't present it. pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) { - let on = on && self.hdr_capable && self.surface.is_some(); - if on != self.hdr.is_some() { - self.hdr = - on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix())); + let output = self.hdr_output.filter(|_| on && self.surface.is_some()); + if output.is_some() != self.hdr.is_some() { + let format = self.config.format.remove_srgb_suffix(); + self.hdr = output.map(|output| hdr::Hdr::new(&self.device, format, output)); self.configure_surface(); } if let Some(hdr) = &mut self.hdr diff --git a/crates/horizon-client/src/gfx/hdr.rs b/crates/horizon-client/src/gfx/hdr.rs index 11deed546..8b9df7af0 100644 --- a/crates/horizon-client/src/gfx/hdr.rs +++ b/crates/horizon-client/src/gfx/hdr.rs @@ -1,17 +1,50 @@ //! HDR output (Horizon setting, off by default): the frame renders exactly as //! without it, into an 8-bit target in vanilla's gamma space, and one pass -//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white, -//! expanding the world's highlights towards their peak brightness. The world -//! is copied aside before the hand and HUD so only it is expanded. +//! (`hdr.wgsl`) writes it to an HDR10 or scRGB swapchain at the player's paper +//! white, expanding the world's highlights towards their peak brightness. The +//! world is copied aside before the hand and HUD so only it is expanded. -/// The swapchain format and colour space HDR output presents in. -pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; -pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear; +/// The swapchain HDR output presents to. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Output { + /// HDR10: 10-bit BT.2020 with the PQ curve, the display's own signal. + Pq, + /// scRGB: linear 16-bit float, BT.709 primaries, 1.0 = 80 nits. + ScRgb, +} -/// Whether `caps` can present scRGB. -pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool { - caps.color_spaces(FORMAT) - .contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR) +impl Output { + pub fn format(self) -> wgpu::TextureFormat { + match self { + Self::Pq => wgpu::TextureFormat::Rgb10a2Unorm, + Self::ScRgb => wgpu::TextureFormat::Rgba16Float, + } + } + pub fn color_space(self) -> wgpu::SurfaceColorSpace { + match self { + Self::Pq => wgpu::SurfaceColorSpace::Bt2100Pq, + Self::ScRgb => wgpu::SurfaceColorSpace::ExtendedSrgbLinear, + } + } + fn space(self) -> wgpu::SurfaceColorSpaces { + match self { + Self::Pq => wgpu::SurfaceColorSpaces::BT2100_PQ, + Self::ScRgb => wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR, + } + } +} + +/// The HDR output `caps` can present: HDR10 where offered, else scRGB. +/// `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only that one. +pub fn output(caps: &wgpu::SurfaceCapabilities) -> Option { + pick(caps, std::env::var("HORIZON_HDR_OUTPUT").ok().as_deref()) +} +fn pick(caps: &wgpu::SurfaceCapabilities, only: Option<&str>) -> Option { + [(Output::Pq, "pq"), (Output::ScRgb, "scrgb")] + .into_iter() + .filter(|(_, name)| only.is_none_or(|o| o == *name)) + .map(|(output, _)| output) + .find(|o| caps.color_spaces(o.format()).contains(o.space())) } struct Targets { @@ -25,6 +58,7 @@ pub struct Hdr { layout: wgpu::BindGroupLayout, pipeline: wgpu::RenderPipeline, params: wgpu::Buffer, + pub output: Output, /// The frame's format: what every other pipeline draws in. format: wgpu::TextureFormat, targets: Option, @@ -36,7 +70,7 @@ pub struct Hdr { } impl Hdr { - pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, output: Output) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon HDR"), source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()), @@ -90,7 +124,7 @@ impl Hdr { entry_point: Some("fs_hdr"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { - format: FORMAT, + format: output.format(), blend: None, write_mask: wgpu::ColorWrites::ALL, })], @@ -100,7 +134,7 @@ impl Hdr { }); let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Horizon HDR parameters"), - size: 16, + size: 32, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -108,6 +142,7 @@ impl Hdr { layout, pipeline, params, + output, format, targets: None, debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"), @@ -198,6 +233,10 @@ impl Hdr { (self.peak / paper).max(1.0), f32::from(u8::from(world)), f32::from(u8::from(self.debug)), + f32::from(u8::from(self.output == Output::Pq)), + 0.0, + 0.0, + 0.0, ]; queue.write_buffer(&self.params, 0, bytemuck::cast_slice(¶ms)); let view = target.create_view(&Default::default()); @@ -220,3 +259,37 @@ impl Hdr { pass.draw(0..3, 0..1); } } + +#[cfg(test)] +mod tests { + use super::{Output, pick}; + use wgpu::{SurfaceColorSpaces as S, TextureFormat as F}; + + fn caps(offered: &[(F, S)]) -> wgpu::SurfaceCapabilities { + wgpu::SurfaceCapabilities { + format_capabilities: offered + .iter() + .map(|&(format, color_spaces)| wgpu::SurfaceFormatCapabilities { + format, + color_spaces, + }) + .collect(), + ..Default::default() + } + } + + #[test] + fn hdr10_first_then_scrgb() { + let both = caps(&[ + (F::Bgra8UnormSrgb, S::SRGB), + (F::Rgb10a2Unorm, S::BT2100_PQ | S::BT2100_HLG), + (F::Rgba16Float, S::EXTENDED_SRGB_LINEAR), + ]); + assert_eq!(pick(&both, None), Some(Output::Pq)); + assert_eq!(pick(&both, Some("scrgb")), Some(Output::ScRgb)); + let scrgb = caps(&[(F::Rgba16Float, S::EXTENDED_SRGB_LINEAR)]); + assert_eq!(pick(&scrgb, None), Some(Output::ScRgb)); + assert_eq!(pick(&scrgb, Some("pq")), None); + assert_eq!(pick(&caps(&[(F::Bgra8UnormSrgb, S::SRGB)]), None), None); + } +} diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 4f6f04bc0..7a2f5e225 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -255,7 +255,7 @@ pub struct Graphics { pub resolution_scale: u32, /// FXAA over the world. pub fxaa: bool, - /// HDR output (scRGB), where the display path offers it. + /// HDR output (HDR10, or scRGB), where the display path offers it. pub hdr: bool, /// HDR paper white (where SDR white sits), in nits. pub hdr_paper_white: u32, diff --git a/crates/horizon-client/src/hdr.wgsl b/crates/horizon-client/src/hdr.wgsl index bf6c27cca..8f6c25d12 100644 --- a/crates/horizon-client/src/hdr.wgsl +++ b/crates/horizon-client/src/hdr.wgsl @@ -1,6 +1,6 @@ // Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma -// space, decoded to linear light at the paper white and written to the scRGB -// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the +// space, decoded to linear light at the paper white and written to the swapchain: +// HDR10 (BT.2020, PQ) or scRGB (1.0 = 80 nits). Bright pixels of light sources that still show the // world as it was before the hand and HUD are expanded towards the peak. @group(0) @binding(0) var frame: texture_2d; @group(0) @binding(1) var world: texture_2d; @@ -14,6 +14,8 @@ struct Params { world: f32, // 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1). debug: f32, + // 1 for an HDR10 swapchain, 0 for scRGB. + pq: f32, }; @group(0) @binding(2) var params: Params; @@ -40,6 +42,19 @@ fn shows_world(c: vec3, w: vec3) -> bool { return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03)); } +// Linear BT.709 to BT.2020 (ITU-R BT.2087), columns first. +const BT709_TO_BT2020 = mat3x3( + vec3(0.6274, 0.0691, 0.0164), + vec3(0.3293, 0.9195, 0.0880), + vec3(0.0433, 0.0114, 0.8956), +); + +// SMPTE ST 2084: nits (up to 10000) to the PQ signal. +fn pq(nits: vec3) -> vec3 { + let y = pow(clamp(nits / 10000.0, vec3(0.0), vec3(1.0)), vec3(0.1593017578125)); + return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), vec3(78.84375)); +} + @vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); return vec4(p * 2.0 - 1.0, 0.0, 1.0); @@ -65,5 +80,9 @@ fn shows_world(c: vec3, w: vec3) -> bool { } } } - return vec4(light * params.paper, 1.0); + let scrgb = light * params.paper; + if params.pq > 0.5 { + return vec4(pq(BT709_TO_BT2020 * scrgb * 80.0), 1.0); + } + return vec4(scrgb, 1.0); } diff --git a/docs/graphics.md b/docs/graphics.md index dcba29773..79c969d90 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -29,7 +29,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi **Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are. -**HDR** (Display, off by default) presents to an scRGB swapchain (`Rgba16Float`, extended linear sRGB) on displays and compositors that offer it. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain. +**HDR** (Display, off by default) presents to an HDR10 swapchain (`Rgb10a2Unorm`, BT.2020 with the PQ curve) or, where only that is offered, an scRGB one (`Rgba16Float`, extended linear sRGB), on displays and compositors that offer either; `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only one. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain. Which settings each screen shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); `graphics_style.rs` draws them. From 2a98f584dfaf78561ffde4643b4e20fc8fe1d9a7 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 22:40:12 +0600 Subject: [PATCH 04/65] Send cushion breaking particles to nearby multiplayer clients Co-Authored-By: Codex --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/cushions.rs | 24 +++--- crates/horizon-client/src/game/lan.rs | 29 ++++++++ tests/test_cushion_particles.py | 87 ++++++++++++++++++++++ tools/lan_e2e.py | 6 ++ 5 files changed, 135 insertions(+), 13 deletions(-) create mode 100644 tests/test_cushion_particles.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..f05be393a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1584,6 +1584,7 @@ struct Game<'a> { guest_use: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_cushion_breaks: Vec<(horizon_world::registry::BlockStateId, [f64; 3])>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, @@ -12477,6 +12478,7 @@ impl<'a> Game<'a> { forced_hit: None, guest_use: None, lan_events: Vec::new(), + lan_cushion_breaks: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), lan_critical_hits: Vec::new(), diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs index 0847321d6..30af72104 100644 --- a/crates/horizon-client/src/game/cushions.rs +++ b/crates/horizon-client/src/game/cushions.rs @@ -348,11 +348,15 @@ impl Game<'_> { let Some(state) = self.pack.assets.registry.default_state(&name) else { return; }; - let at = [ - c.position.x.floor() as i32, - c.position.y.floor() as i32, - c.position.z.floor() as i32, - ]; + let p = c.position; + // Entity.getY(2/3) is relative to the cushion's quarter-block height. + let particle_at = [p.x, p.y + 0.25 * (2.0 / 3.0), p.z]; + // Guest actions temporarily take self.lan; flush once the hub is back. + // Queue before resolving a sprite: a dedicated server has no renderer. + if self.audio.capture.is_some() { + self.lan_cushion_breaks.push((state, particle_at)); + } + let at = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; let Some((sprite, tint)) = self.particle_sprite(state, at) else { return; }; @@ -361,14 +365,8 @@ impl Game<'_> { sprite, tint, ); - let p = c.position; - self.particles.send_particles( - &options, - [p.x, p.y + 0.666_666_7, p.z], - [0.25, 0.0625, 0.25], - 0.05, - 10, - ); + self.particles + .send_particles(&options, particle_at, [0.25, 0.0625, 0.25], 0.05, 10); } /// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 63aea7e9f..75500ba79 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -21,6 +21,7 @@ use horizon_core::geometry::Vec3; use horizon_protocol::{ crypto::offline_uuid, entity_data::{Value, serializer}, + packets::play::{self, Clientbound as C}, }; use std::{ collections::HashMap, @@ -665,6 +666,7 @@ impl Game<'_> { self.audio.capture = None; self.lan_events.clear(); self.lan_critical_hits.clear(); + self.lan_cushion_breaks.clear(); self.streaming.extra.clear(); if announce { self.system_message(Text::translate( @@ -1229,6 +1231,33 @@ impl Game<'_> { /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { let critical_hits = std::mem::take(&mut self.lan_critical_hits); + for (state, at) in std::mem::take(&mut self.lan_cushion_breaks) { + if let Some(id) = host + .hub + .registry_id("minecraft:particle_type", "minecraft:block") + { + host.hub.broadcast_near( + at, + 32.0, + &C::LevelParticles(play::LevelParticles { + particle: horizon_protocol::entity_data::Particle { + id, + data: Some(horizon_protocol::entity_data::ParticleData::State( + state.0 as i32, + )), + }, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.25, 0.0625, 0.25], + max_speed: [0.05; 3], + count: 10, + randomization: 0, + }), + None, + ); + } + } for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { if kind == 2001 { host.broken diff --git a/tests/test_cushion_particles.py b/tests/test_cushion_particles.py new file mode 100644 index 000000000..adfbf2e00 --- /dev/null +++ b/tests/test_cushion_particles.py @@ -0,0 +1,87 @@ +"""Cushion particles must reach clients even when the server has no sprite atlas.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class CushionParticlesTests(unittest.TestCase): + def test_headless_server_records_break_effect_before_sprite_lookup(self): + source = (ROOT / "crates/horizon-client/src/game/cushions.rs").read_text() + start = source.index(" fn cushion_break_particles(") + end = source.index(" /// `BlockAttachedEntity.tick`", start) + fixture = r''' +#![allow(dead_code)] +#[derive(Clone, Copy)] +struct Vec3 { x: f64, y: f64, z: f64 } +struct Cushion { position: Vec3 } +impl Cushion { fn color_name(&self) -> &str { "blue" } } +struct Registry; +impl Registry { + fn default_state(&self, name: &str) -> Option { + assert_eq!(name, "minecraft:blue_wool"); Some(123) + } +} +struct Assets { registry: Registry } +struct Pack { assets: Assets } +struct Audio { capture: Option<()> } +mod horizon_client { pub mod particles { + pub enum ParticleType { Block } + pub struct ParticleOptions; + impl ParticleOptions { + pub fn block(_: ParticleType, _: String, _: u32) -> Self { Self } + } +} } +#[derive(Default)] +struct Particles { count: u32 } +impl Particles { + fn send_particles(&mut self, _: &horizon_client::particles::ParticleOptions, + at: [f64; 3], spread: [f64; 3], speed: f64, count: u32) { + assert!((at[1] - (10.0 + 1.0/6.0)).abs() < 1e-12); + assert_eq!(spread, [0.25, 0.0625, 0.25]); + assert_eq!(speed, 0.05); assert_eq!(count, 10); self.count += count; + } +} +struct Game { + pack: Pack, audio: Audio, particles: Particles, headless: bool, + lan_cushion_breaks: Vec<(u32, [f64; 3])>, +} +impl Game { + fn particle_sprite(&self, _: u32, _: [i32; 3]) -> Option<(String, u32)> { + (!self.headless).then(|| ("block/blue_wool".into(), 0xffffff)) + } +METHOD +} +fn main() { + let cushion = Cushion { position: Vec3 { x: 1.5, y: 10.0, z: 2.5 } }; + for headless in [true, false] { + for serving in [true, false] { + let mut game = Game { + pack: Pack { assets: Assets { registry: Registry } }, + audio: Audio { capture: serving.then_some(()) }, + particles: Particles::default(), headless, lan_cushion_breaks: vec![], + }; + game.cushion_break_particles(&cushion); + assert_eq!(game.lan_cushion_breaks.len(), usize::from(serving)); + if serving { + let (state, at) = game.lan_cushion_breaks[0]; + assert_eq!(state, 123); + assert_eq!([at[0], at[2]], [1.5, 2.5]); + assert!((at[1] - (10.0 + 1.0/6.0)).abs() < 1e-12); + } + assert_eq!(game.particles.count, if headless { 0 } else { 10 }); + } + } +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="cushion-particles-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c508a67d6..6847f8322 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -7235,9 +7235,15 @@ def check_cushions(host, guest, out): assert player('status').get('riding') is None, seen player('command', command='gamemode creative') player.raw('look-at', at[0], at[1] + .125, at[2]) + before = {g.name: g('status').get('particles', {}).get('block', 0) for g in (host, guest)} player.raw('mouse', 'left', 'click') player.wait(10) assert not cushions(host) and not cushions(player), seen + seen[label]['break_particles'] = { + g.name: g('status').get('particles', {}).get('block', 0) - before[g.name] + for g in (host, guest) + } + assert all(n == 10 for n in seen[label]['break_particles'].values()), seen return seen From b37528f5d6e1f87ff59fdf40763c9ae3ce9f9cc1 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 17:51:54 +0100 Subject: [PATCH 05/65] Pause menu: server links ClientboundServerLinksPacket (configuration and play) decoded and kept, the pause menu gains its "Server Links..." button when a server sends links, opening the server_links dialog screen: scrollable link buttons, ConfirmLinkScreen on click (chatLinks/chatLinksPrompt honoured), and the custom-screens warning with its disconnect. A dedicated server sends its `bug-report-link` property as the BUG_REPORT link, like vanilla. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 32 ++ crates/horizon-client/src/game/agent.rs | 3 + crates/horizon-client/src/game/control.rs | 3 + crates/horizon-client/src/game/dedicated.rs | 16 + crates/horizon-client/src/game/packs.rs | 4 + crates/horizon-client/src/game/remote.rs | 9 + crates/horizon-client/src/game/screens.rs | 91 +++- .../horizon-client/src/game/server_links.rs | 487 ++++++++++++++++++ crates/horizon-client/src/lan/conn.rs | 10 + crates/horizon-client/src/lan/mod.rs | 5 + crates/horizon-client/src/net.rs | 9 + crates/horizon-client/src/options_ui.rs | 5 + crates/horizon-client/src/settings.rs | 4 + .../src/packets/configuration.rs | 61 +++ crates/horizon-protocol/src/packets/play.rs | 5 +- 15 files changed, 726 insertions(+), 18 deletions(-) create mode 100644 crates/horizon-client/src/game/server_links.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..ca9e7110a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -150,6 +150,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_links; mod server_mods; mod server_packs; mod server_travel; @@ -490,6 +491,12 @@ enum Screen { Friends, /// CommandBlockEditScreen (game/command_blocks.rs). CommandBlock, + /// ServerLinksDialogScreen: a server's links (game/server_links.rs). + ServerLinks, + /// ConfirmLinkScreen for a server link (game/server_links.rs). + ConfirmLink, + /// DialogScreen.WarningScreen: the note about custom screens. + DialogWarning, /// WinScreen: the end poem and the credits (game/win.rs). Win, /// A `ui` mod's own screen, or its settings page from Options > Mods @@ -1641,6 +1648,8 @@ struct Game<'a> { restore_player_state: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, + /// The Server Links screens' state (game/server_links.rs). + links_ui: server_links::LinksUi, camera_type: perspective::CameraType, fangs: fangs::FangState, /// The local player as a model (third person, the inventory). @@ -4765,6 +4774,9 @@ impl Game<'_> { | Screen::Advancements | Screen::WorldOptions | Screen::Friends + | Screen::ServerLinks + | Screen::ConfirmLink + | Screen::DialogWarning | Screen::CommandBlock ) || self.book.is_some() || self.win_screen_pauses()) @@ -5248,6 +5260,9 @@ impl Game<'_> { Screen::Advancements => self.draw_advancements(&mut batch), Screen::WorldOptions => self.draw_world_options(&mut batch), Screen::Friends => self.draw_friends_screen(&mut batch), + Screen::ServerLinks => self.draw_server_links(&mut batch), + Screen::ConfirmLink => self.draw_confirm_link(&mut batch), + Screen::DialogWarning => self.draw_dialog_warning(&mut batch), Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); @@ -10786,6 +10801,10 @@ impl Game<'_> { Screen::GameModeSwitcher => self.close_gamemode_switcher(false), Screen::Dead => {} Screen::Stats | Screen::Friends => self.screen = Screen::Paused, + Screen::ServerLinks => self.screen = Screen::Paused, + // ConfirmScreen.keyPressed: Escape answers no; both return to + // the Server Links screen they came from. + Screen::ConfirmLink | Screen::DialogWarning => self.screen = Screen::ServerLinks, Screen::Advancements => self.close_advancements(), Screen::WorldOptions => self.world_options_escape(), Screen::CommandBlock => self.close_command_block(), @@ -11465,6 +11484,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::WorldOptions && d != 0.0 { self.world_options_scroll(d); } + if self.screen == Screen::ServerLinks && d != 0.0 { + self.server_links_scroll(d); + } if self.screen == Screen::Advancements { self.advancements_scroll(scaled(raw_x) as f32, d); } @@ -11655,6 +11677,15 @@ impl ApplicationHandler for Game<'_> { Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } + Screen::ServerLinks if pressed && button == MouseButton::Left => { + self.server_links_click()? + } + Screen::ConfirmLink if pressed && button == MouseButton::Left => { + self.confirm_link_click() + } + Screen::DialogWarning if pressed && button == MouseButton::Left => { + self.dialog_warning_click()? + } Screen::WorldOptions if button == MouseButton::Left => { self.world_options_release() } @@ -12511,6 +12542,7 @@ impl<'a> Game<'a> { restore_player_state: true, stats_ui: Default::default(), adv_ui: Default::default(), + links_ui: Default::default(), camera_type: Default::default(), fangs: Default::default(), player_model: None, diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index fa9dbf3c6..0b82ac0b8 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -419,6 +419,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 3202b23f4..6c910ab8a 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -875,6 +875,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..10e10cd31 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -618,6 +618,22 @@ impl Game<'_> { log_ips: props.log_ips, }), resource_pack: props.resource_pack.clone(), + // DedicatedServer.serverLinks: `bug-report-link` as the only link + // (ServerLinks.KnownLinkType.BUG_REPORT is id 0). + server_links: if props.bug_report_link.is_empty() { + Vec::new() + } else if super::server_links::valid_untrusted_uri(&props.bug_report_link) { + vec![horizon_protocol::packets::configuration::ServerLink { + kind: horizon_protocol::packets::configuration::ServerLinkKind::Known(0), + link: props.bug_report_link.clone(), + }] + } else { + log( + "WARN", + &format!("Failed to parse bug link {}", props.bug_report_link), + ); + Vec::new() + }, }; let config = HubConfig { default_game_mode: game_mode, diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..e5026cd17 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -34,6 +34,10 @@ pub fn open_folder(dir: &Path) { log::warn!("Horizon: could not open {}: {e}", dir.display()); } } +/// `Util.getPlatform().openUri`: the system browser on the link. +pub fn open_uri(uri: &str) { + open_folder(Path::new(uri)); +} /// The resource root to load from, given the vanilla root, the selection and /// a server's packs, which go on top (`Pack.Position.TOP`, fixed). pub fn startup_root( diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3ef87c201..6e770aaeb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -212,6 +212,9 @@ pub(super) struct Remote { /// `ClientboundTransferPacket`'s target: when the connection ends the /// game connects here, the stored cookies carried over (`TransferState`). transfer: Option, + /// `ClientCommonPacketListenerImpl.serverLinks`: the links "Server + /// Links..." in the pause menu lists (only `http`/`https` URIs kept). + pub(super) server_links: Vec, } /// The time a frame spends on chunk packets before it leaves the rest of @@ -486,6 +489,7 @@ impl Game<'_> { chunk_center: (0, 0), backlog: VecDeque::new(), backlog_since: None, + server_links: Vec::new(), transfer: None, }); // The level's TickRateManager follows the server's ticking packets. @@ -862,6 +866,11 @@ impl Game<'_> { } Event::PackPush(p) => self.handle_pack_push(p), Event::PackPop(id) => self.handle_pack_pop(id), + Event::ServerLinks(links) => { + if let Some(r) = self.remote.as_mut() { + r.server_links = super::server_links::trusted(links); + } + } Event::ShowDialog(dialog) => self.show_dialog(&dialog), Event::ClearDialog => self.clear_dialog(), Event::DecodeError(e) => { diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index f8885f83a..750895adb 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -19,6 +19,9 @@ impl Screen { | Self::Advancements | Self::WorldOptions | Self::Friends + | Self::ServerLinks + | Self::ConfirmLink + | Self::DialogWarning | Self::Mod => true, Self::Playing | Self::GameModeSwitcher @@ -35,20 +38,35 @@ impl Screen { } /// PauseScreen buttons: (x, y, width, label key, action id, active). +/// `links`: the `minecraft:server_links` dialog's button, which the +/// `pause_screen_additions` tag (empty in vanilla) falls back to when the +/// server sent links — a full-width row that pushes the last two rows down. /// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen -fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { +fn pause_buttons( + w: f32, + h: f32, + remote: bool, + links: bool, +) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { // GridLayout of two 98px columns (padding 4), aligned at (0.5, 0.25). - let (grid_w, grid_h) = (212.0, 166.0); + let (grid_w, grid_h) = (212.0, 166.0 + if links { 24.0 } else { 0.0 }); let x0 = ((w - grid_w) * 0.5).floor(); let y0 = ((h - grid_h) * 0.25).floor(); - vec![ + let down = if links { 24.0 } else { 0.0 }; + let mut v = vec![ (x0 + 4.0, y0 + 50.0, 204.0, "menu.returnToGame", 0, true), (x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 4, true), (x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 3, true), - (x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true), + ]; + if links { + // CommonDialogData.computeExternalTitle of Dialogs.SERVER_LINKS. + v.push((x0 + 4.0, y0 + 122.0, 204.0, "menu.server_links", 11, true)); + } + v.extend([ + (x0 + 4.0, y0 + 122.0 + down, 98.0, "menu.options", 1, true), ( x0 + 110.0, - y0 + 122.0, + y0 + 122.0 + down, 98.0, "options.worldOptions.button", 9, @@ -56,7 +74,7 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s ), ( x0 + 4.0, - y0 + 146.0, + y0 + 146.0 + down, 204.0, if remote { "menu.disconnect" @@ -66,16 +84,17 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s 2, true, ), - ] + ]); + v } /// The icon row: report bugs, feedback, friends, player reporting. /// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's /// Play with Friends; the others stay inactive. const FRIENDS_ICON: usize = 2; -fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { +fn pause_icons(w: f32, h: f32, links: bool) -> [(f32, f32, &'static str); 4] { let x0 = ((w - 212.0) * 0.5).floor() + 60.0; - let y = ((h - 166.0) * 0.25).floor() + 98.0; + let y = ((h - 166.0 - if links { 24.0 } else { 0.0 }) * 0.25).floor() + 98.0; [ (x0, y, "gui/sprites/pause_menu/bug"), (x0 + 24.0, y, "gui/sprites/pause_menu/social_interactions"), @@ -120,7 +139,9 @@ impl Game<'_> { u32::MAX, true, ); - for (x, y, bw, key, _, active) in pause_buttons(w, h, self.external_server()) { + let links = !self.server_links().is_empty(); + let mut tooltip = None; + for (x, y, bw, key, id, active) in pause_buttons(w, h, self.external_server(), links) { let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); ui::button( batch, @@ -133,9 +154,12 @@ impl Game<'_> { active, hover, ); + // PauseScreen's customAdditions button: CUSTOM_OPTIONS_TOOLTIP. + if id == 11 && hover { + tooltip = Some(Text::translate("menu.custom_options.tooltip", &[])); + } } - let mut tooltip = None; - for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() { + for (i, (x, y, sprite)) in pause_icons(w, h, links).into_iter().enumerate() { let active = i == FRIENDS_ICON && friends; let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0); // The icon has no label: name it for controller focus and the @@ -168,7 +192,13 @@ impl Game<'_> { } // SpriteIconButton.withTootip: the label as a tooltip. if let Some(tip) = tooltip { - ui::tooltip(batch, atlas, &[tip], self.cursor); + let lines: Vec = atlas + .font + .split_lines(&tip, batch.width) + .into_iter() + .map(|(line, _)| line) + .collect(); + ui::tooltip(batch, atlas, &lines, self.cursor); } } pub(super) fn pause_click(&mut self) -> Result<()> { @@ -180,8 +210,9 @@ impl Game<'_> { let b = HudBatch::new(size); (b.width, b.height) }; - let friends = pause_icons(w, h)[FRIENDS_ICON]; - let hit = pause_buttons(w, h, self.external_server()) + let links = !self.server_links().is_empty(); + let friends = pause_icons(w, h, links)[FRIENDS_ICON]; + let hit = pause_buttons(w, h, self.external_server(), links) .into_iter() .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)) .map(|b| b.4) @@ -200,6 +231,11 @@ impl Game<'_> { Some(4) => self.open_advancements(true), Some(9) => self.open_world_options(), Some(10) => self.screen = Screen::Friends, + // DialogConnectionAccess.openDialog(Dialogs.SERVER_LINKS). + Some(11) => { + self.links_ui.scroll = 0.0; + self.screen = Screen::ServerLinks; + } Some(2) => self.close_world()?, _ => {} } @@ -357,7 +393,7 @@ impl Game<'_> { #[cfg(test)] mod tests { - use super::{Screen, pause_buttons}; + use super::{Screen, pause_buttons, pause_icons}; #[test] fn menu_blur_matches_vanilla_screen_backgrounds() { @@ -390,11 +426,32 @@ mod tests { #[test] fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() { for (remote, label) in [(false, "menu.returnToMenu"), (true, "menu.disconnect")] { - let buttons = pause_buttons(427.0, 240.0, remote); + let buttons = pause_buttons(427.0, 240.0, remote, false); let quit = buttons.iter().find(|b| b.4 == 2).unwrap(); assert_eq!(quit.3, label); assert!(quit.5); assert!(buttons.iter().any(|b| b.4 == 9 && b.5)); } } + + #[test] + fn server_links_adds_a_full_width_row_above_options() { + let with = pause_buttons(427.0, 240.0, true, true); + let without = pause_buttons(427.0, 240.0, true, false); + let links = with.iter().find(|b| b.4 == 11).unwrap(); + assert_eq!(links.2, 204.0); + assert_eq!(links.3, "menu.server_links"); + assert!(links.5); + // The icon row sits above it; Options and Disconnect move down 24. + let icons = pause_icons(427.0, 240.0, true); + let y0_icons = ((240.0f32 - 190.0) * 0.25).floor() + 98.0; + assert_eq!(icons[0].1, y0_icons); + assert!(links.1 > icons[0].1); + for b in &with { + if b.4 == 1 || b.4 == 9 || b.4 == 2 { + let same = without.iter().find(|o| o.4 == b.4).unwrap(); + assert_eq!(b.1, same.1 + 24.0 - 6.0, "{}", b.3); + } + } + } } diff --git a/crates/horizon-client/src/game/server_links.rs b/crates/horizon-client/src/game/server_links.rs new file mode 100644 index 000000000..85fda71d6 --- /dev/null +++ b/crates/horizon-client/src/game/server_links.rs @@ -0,0 +1,487 @@ +//! `ServerLinksDialogScreen`: the pause menu's "Server Links..." button opens +//! the `minecraft:server_links` dialog (the `pause_screen_additions` tag's +//! fallback when a server sent ClientboundServerLinksPacket): a scrollable +//! list of the server's links, each opened through `ConfirmLinkScreen` +//! (Screen.clickUrlAction), and the `dialog/warning_button`'s +//! DialogScreen.WarningScreen ("Note about custom screens"). +//! https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/dialog/ServerLinksDialogScreen +use super::{Game, Screen, packs::open_uri}; +use horizon_client::{Result, clipboard::Clipboard, hud::HudBatch, text::Text, ui}; +use horizon_protocol::packets::configuration::{ServerLink, ServerLinkKind}; + +/// HeaderAndFooterLayout's header and footer heights; the content wants to +/// start 30 pixels under the header (its `CONTENTS_MARGIN_TOP`). +const HEADER: f32 = 33.0; +const FOOTER: f32 = 33.0; +const CONTENT_TOP: f32 = HEADER + 30.0; +/// `server_links.json`: `columns` 1, `button_width` 310, `exit_action`'s 200. +const LINK_WIDTH: f32 = 310.0; +/// packControlsIntoColumns: rowSpacing 2 under the 20-pixel buttons. +const ROW: f32 = 22.0; +/// ScrollableLayout's BOTH reserve (scrollbarSpacing 4 + SCROLLBAR_WIDTH 6). +const SCROLL_RESERVE: f32 = 10.0; +/// DialogScreen's `dialog/warning_button` ImageButton. +const WARNING_BUTTON: f32 = 20.0; + +/// The ServerLinks screen's state: ScrollableLayout's scroll and the link +/// ConfirmLinkScreen is asking about (`Screen::ConfirmLink`). +#[derive(Default)] +pub(super) struct LinksUi { + pub scroll: f32, + pub confirm: Option, +} + +/// `Util.parseAndValidateUntrustedUri`: an absolute `http`/`https` URI +/// (java.net.URI's scheme then the allowlist; whitespace-free). +pub(super) fn valid_untrusted_uri(uri: &str) -> bool { + let Some(colon) = uri.find(':') else { + return false; + }; + let scheme = &uri[..colon]; + let mut chars = scheme.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + { + return false; + } + if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") { + return false; + } + !uri.chars().any(|c| c.is_control() || c == ' ') +} +/// `ClientCommonPacketListenerImpl.handleServerLinks`: keep only the links +/// that validate, warning about the dropped ones. +pub(super) fn trusted(links: Vec) -> Vec { + links + .into_iter() + .filter(|l| { + let ok = valid_untrusted_uri(&l.link); + if !ok { + log::warn!("Horizon: server sent an invalid link: {}", l.link); + } + ok + }) + .collect() +} +/// `ServerLinks.Entry.displayName`: `known_server_link.` for a known +/// type (ByIdMap.ZERO reads unknown ids as `report_bug`), the component else. +fn link_label(link: &ServerLink) -> Text { + const KNOWN: [&str; 10] = [ + "report_bug", + "community_guidelines", + "support", + "status", + "feedback", + "community", + "website", + "forums", + "news", + "announcements", + ]; + match &link.kind { + ServerLinkKind::Known(id) => Text::translate( + &format!( + "known_server_link.{}", + KNOWN.get(*id as usize).copied().unwrap_or(KNOWN[0]) + ), + &[], + ), + ServerLinkKind::Custom(tag) => { + horizon_client::scoreboard::comp_text(&horizon_client::scoreboard::tag_to_json(tag)) + } + } +} + +/// The scrolled column of link buttons: content height and, for a list that +/// fits, the `HeaderAndFooterLayout` contents frame's top. +fn list_height(n: usize) -> f32 { + n as f32 * ROW - 2.0 +} +fn list_top(h: f32, n: usize) -> f32 { + CONTENT_TOP.min(h - FOOTER - list_height(n).min(h - HEADER - FOOTER)) +} +fn scroll_limit(h: f32, n: usize) -> f32 { + (list_height(n) - (h - HEADER - FOOTER)).max(0.0) +} + +/// `ServerLinksScreen`'s buttons as (x, y) over the scrolled content, and the +/// footer `Back` button's corner. `top` includes the scroll. +fn link_buttons(w: f32, top: f32, n: usize) -> Vec<(f32, f32)> { + let x = ((w - LINK_WIDTH - 2.0 * SCROLL_RESERVE) / 2.0 + SCROLL_RESERVE).floor(); + (0..n).map(|i| (x, top + i as f32 * ROW)).collect() +} +/// The warning button beside the title (DialogScreen's title row: 10 pixels +/// apart), clamped onto the screen (makeSureWarningButtonIsInBounds). +fn warning_button(w: f32, h: f32, title_width: f32) -> (f32, f32) { + let x = ((w - title_width - 30.0) / 2.0).floor() + title_width + 10.0; + let y = ((HEADER - WARNING_BUTTON) / 2.0).floor(); + if x < 0.0 || y < 0.0 || x > w - WARNING_BUTTON || y > h - WARNING_BUTTON { + (0.0f32.max(w - 40.0), 5.0f32.min(h)) + } else { + (x, y) + } +} +fn back_button(w: f32, h: f32) -> (f32, f32) { + ( + ((w - 200.0) / 2.0).floor(), + h - FOOTER + ((FOOTER - 20.0) / 2.0).floor(), + ) +} + +impl Game<'_> { + /// `connection.serverLinks()`: the links the open server sent (empty for + /// a world without a connection or one that sent none). + pub(super) fn server_links(&self) -> &[ServerLink] { + self.remote + .as_ref() + .map_or(&[], |r| r.server_links.as_slice()) + } + /// DialogScreen over the pause menu: `menu.server_links.title`, the + /// scrollable link buttons and `gui.back` in the footer. + pub(super) fn draw_server_links(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let links = self.server_links().to_vec(); + self.links_ui.scroll = self + .links_ui + .scroll + .clamp(0.0, scroll_limit(h, links.len())); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + // The title row: the title, then 10 pixels on the warning button. + let title = Text::translate("menu.server_links.title", &[]); + let tw = atlas.font.width_text(&title); + let tx = ((w - tw - 30.0) / 2.0).floor(); + batch.text_styled(atlas, &title, tx, 12.0, u32::MAX, true); + let (wx, wy) = warning_button(w, h, tw); + let wh = ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON); + horizon_client::widgets::record( + "menu.custom_screen_info.tooltip", + [wx, wy, WARNING_BUTTON, WARNING_BUTTON], + true, + ); + batch.sprite_scaled( + atlas, + if wh { + "gui/sprites/dialog/warning_button_highlighted" + } else { + "gui/sprites/dialog/warning_button" + }, + wx, + wy, + WARNING_BUTTON, + WARNING_BUTTON, + u32::MAX, + ); + let first = batch.vertices.len(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + for (link, (x, y)) in links.iter().zip(link_buttons(w, top, links.len())) { + let hover = inside && ui::hovered(self.cursor, x, y, LINK_WIDTH, 20.0); + ui::button( + batch, + atlas, + x, + y, + LINK_WIDTH, + 20.0, + &link_label(link), + true, + hover, + ); + } + batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); + ui::scrollbar( + batch, + atlas, + (w / 2.0).floor() + 155.0 + 4.0, + HEADER, + h - FOOTER, + list_height(links.len()), + self.links_ui.scroll.trunc(), + ); + let (bx, by) = back_button(w, h); + let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); + ui::button( + batch, + atlas, + bx, + by, + 200.0, + 20.0, + &Text::translate("gui.back", &[]), + true, + hover, + ); + if wh { + ui::tooltip( + batch, + atlas, + &[Text::translate("menu.custom_screen_info.tooltip", &[])], + self.cursor, + ); + } + } + /// A click on `Screen::ServerLinks`: a link, the warning button or Back. + pub(super) fn server_links_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let links = self.server_links().to_vec(); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + if inside + && let Some(i) = link_buttons(w, top, links.len()) + .iter() + .position(|(x, y)| ui::hovered(self.cursor, *x, *y, LINK_WIDTH, 20.0)) + { + self.audio.play_button_click(); + self.click_link(&links[i].link); + return Ok(()); + } + let title = Text::translate("menu.server_links.title", &[]); + let tw = self.gui.atlas.font.width_text(&title); + let (wx, wy) = warning_button(w, h, tw); + if ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON) { + self.audio.play_button_click(); + self.screen = Screen::DialogWarning; + return Ok(()); + } + let (bx, by) = back_button(w, h); + if ui::hovered(self.cursor, bx, by, 200.0, 20.0) { + self.audio.play_button_click(); + self.screen = Screen::Paused; + } + Ok(()) + } + /// `Screen.clickUrlAction`: "Web Links" off ignores the click; "Prompt on + /// Links" asks with ConfirmLinkScreen, else the browser opens directly. + fn click_link(&mut self, url: &str) { + if !self.settings.chat_links { + return; + } + if self.settings.chat_links_prompt { + self.links_ui.confirm = Some(url.to_owned()); + self.screen = Screen::ConfirmLink; + } else { + open_uri(url); + } + } + /// `ScrollableLayout`'s mouse wheel over the links. + pub(super) fn server_links_scroll(&mut self, delta: f32) { + let (_, h) = self.gui_size(); + self.links_ui.scroll = (self.links_ui.scroll - delta * 10.0) + .clamp(0.0, scroll_limit(h, self.server_links().len())); + } + /// `ConfirmLinkScreen` (untrusted): "Are you sure you want to open the + /// following website?", the link, the red warning, and Yes / Copy Link to + /// Clipboard / No. + pub(super) fn draw_confirm_link(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(atlas, (w, h), &url); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let labels = ["gui.yes", "gui.copy_link_to_clipboard", "gui.no"]; + for ((x, y), key) in layout.buttons.iter().zip(labels) { + let hover = ui::hovered(self.cursor, *x, *y, 100.0, 20.0); + ui::button( + batch, + atlas, + *x, + *y, + 100.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// ConfirmLinkScreen's answer: yes opens the browser, the middle button + /// copies the link, no closes; all return to Server Links. + pub(super) fn confirm_link_click(&mut self) { + let (w, h) = self.gui_size(); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(&self.gui.atlas, (w, h), &url); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 100.0, 20.0) { + continue; + } + self.audio.play_button_click(); + match i { + 0 => open_uri(&url), + 1 => { + self.clipboard.set(&url); + } + _ => {} + } + self.screen = Screen::ServerLinks; + return; + } + } + /// `DialogScreen.WarningScreen`: the custom-screens note, a disconnect + /// button ("Custom screen rejected" is the shown reason) and Back. + pub(super) fn draw_dialog_warning(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let layout = dialog_warning_layout(atlas, (w, h)); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let quit = if self.external_server() { + "menu.disconnect" + } else { + "menu.returnToMenu" + }; + for ((x, y), key) in layout.buttons.into_iter().zip([quit, "gui.back"]) { + let hover = ui::hovered(self.cursor, x, y, 150.0, 20.0); + ui::button( + batch, + atlas, + x, + y, + 150.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// WarningScreen's answer: disconnect, or back to Server Links. + pub(super) fn dialog_warning_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let layout = dialog_warning_layout(&self.gui.atlas, (w, h)); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 150.0, 20.0) { + continue; + } + self.audio.play_button_click(); + if i == 0 { + // DialogConnectionAccess.disconnect: leave with the custom + // screens' reason. + let reason = self.translate( + "menu.custom_screen_info.disconnect", + "Custom screen rejected", + ); + self.leave_server(Some(reason))?; + } else { + self.screen = Screen::ServerLinks; + } + return Ok(()); + } + Ok(()) + } +} + +/// A confirm screen's laid-out text (title, message, extra warning lines) and +/// button corners; the whole column centred (ConfirmScreen.init). +struct ConfirmLayout { + lines: Vec<(Text, f32, f32)>, + buttons: Vec<(f32, f32)>, +} +/// `ConfirmScreen.init`: title, message wrapped to `width - 50` (15 rows at +/// most), the extra lines, then a button row `spacing` 4 with `paddingTop` 16. +fn confirm_layout( + font: &horizon_client::font::Font, + (w, h): (f32, f32), + title: &Text, + message: &Text, + extra: &[Text], + button_widths: &[f32], +) -> ConfirmLayout { + let message: Vec = font + .split_lines(message, w - 50.0) + .into_iter() + .take(15) + .map(|(line, _)| line) + .collect(); + // LinearLayout vertical spacing 8; the button row's children pad 16 on top. + let extra_h = 17.0 * extra.len() as f32; + let mh = 9.0 * message.len() as f32; + let total = 9.0 + 8.0 + mh + extra_h + 8.0 + 16.0 + 20.0; + let mut y = ((h - total) / 2.0).trunc(); + let mut lines = Vec::new(); + let mut push = |line: &Text, at: f32| { + let lw = font.width_text(line); + lines.push((line.clone(), ((w - lw) / 2.0).trunc(), at)); + }; + push(title, y); + y += 17.0; + for line in &message { + push(line, y); + y += 9.0; + } + for line in extra { + y += 8.0; + push(line, y); + y += 9.0; + } + let row_w: f32 = button_widths.iter().sum::() + 4.0 * (button_widths.len() - 1) as f32; + let by = y + 8.0 + 16.0; + let mut bx = ((w - row_w) / 2.0).trunc(); + let buttons = button_widths + .iter() + .map(|bw| { + let p = (bx, by); + bx += bw + 4.0; + p + }) + .collect(); + ConfirmLayout { lines, buttons } +} +fn confirm_link_layout( + atlas: &horizon_client::hud::HudAtlas, + size: (f32, f32), + url: &str, +) -> ConfirmLayout { + // ConfirmLinkScreen (untrusted): `chat.link.confirm`, the link as the + // message, `chat.link.warning` in its red (0xFFCCCC). + confirm_layout( + &atlas.font, + size, + &Text::translate("chat.link.confirm", &[]), + &Text::literal(url.to_owned()), + &[Text::translate("chat.link.warning", &[]).with_color(0xFFCCCC)], + &[100.0; 3], + ) +} +fn dialog_warning_layout(atlas: &horizon_client::hud::HudAtlas, size: (f32, f32)) -> ConfirmLayout { + confirm_layout( + &atlas.font, + size, + &Text::translate("menu.custom_screen_info.title", &[]), + &Text::translate("menu.custom_screen_info.contents", &[]), + &[], + &[150.0; 2], + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn untrusted_uris_are_http_or_https_with_a_scheme() { + for ok in [ + "https://example.net/x", + "http://example.net", + "HTTPS://EXAMPLE.NET", + ] { + assert!(valid_untrusted_uri(ok), "{ok}"); + } + for bad in [ + "example.net/no-scheme", + "ftp://example.net", + "file:///etc/passwd", + "javascript:alert(1)", + "https://exa mple.net", + "://example.net", + "", + ] { + assert!(!valid_untrusted_uri(bad), "{bad}"); + } + } +} diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index f2dcf701d..99b70e065 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -791,6 +791,16 @@ fn login_and_configure( }, }), )?; + // ServerConfigurationPacketListenerImpl.startConfiguration: links, only + // when there are any (MinecraftServer.serverLinks is empty elsewhere). + if !shared.config.server_links.is_empty() { + send( + c, + cfg::Clientbound::ServerLinks(cfg::ServerLinks { + links: shared.config.server_links.clone(), + }), + )?; + } send( c, cfg::Clientbound::UpdateEnabledFeatures(cfg::UpdateEnabledFeatures { diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 3e9b93cac..34c465ffa 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -142,6 +142,10 @@ pub struct NetConfig { /// server.properties `resource-pack`: offered to every player during /// configuration (a dedicated server's; MinecraftServer.getServerResourcePack). pub resource_pack: Option, + /// MinecraftServer.serverLinks (a dedicated server's `bug-report-link`): + /// sent in configuration when non-empty + /// (ServerConfigurationPacketListenerImpl.startConfiguration). + pub server_links: Vec, } impl NetConfig { /// MinecraftServer.enforceSecureProfile. @@ -168,6 +172,7 @@ impl NetConfig { online: None, log: None, resource_pack: None, + server_links: Vec::new(), } } } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 34daaf85c..93364ed91 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -68,6 +68,9 @@ pub enum Event { host: String, port: i32, }, + /// `ClientboundServerLinksPacket`: the links the pause menu's "Server + /// Links..." lists (ClientCommonPacketListenerImpl.handleServerLinks). + ServerLinks(Vec), /// The connection ended. `from_server`: the server gave the reason (or /// the connection was refused for good), rather than the connection /// failing (auto-reconnect retries only failures and shutdowns). @@ -565,6 +568,9 @@ fn receive_play( play::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + play::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } // ClientCommonPacketListenerImpl.handleTransfer: the connection // ends and the game connects to the other address. play::Clientbound::Transfer(p) => { @@ -644,6 +650,9 @@ fn configure( cfg::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + cfg::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } cfg::Clientbound::Transfer(p) => { let _ = send.send(Event::Transfer { host: p.host, diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..63c6165eb 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -56,6 +56,7 @@ pub enum Opt { ChatVisibility, ChatColors, ChatLinks, + ChatLinksPrompt, ChatOpacity, TextBackgroundOpacity, ChatScale, @@ -237,6 +238,7 @@ impl Opt { Opt::ChatVisibility => "options.chat.visibility", Opt::ChatColors => "options.chat.color", Opt::ChatLinks => "options.chat.links", + Opt::ChatLinksPrompt => "options.chat.links.prompt", Opt::ChatOpacity => "options.chat.opacity", Opt::TextBackgroundOpacity => "options.accessibility.text_background_opacity", Opt::ChatScale => "options.chat.scale", @@ -574,6 +576,7 @@ impl Opt { ][usize::from(s.chat_visibility.min(2))]), Opt::ChatColors => on_off(s.chat_colors), Opt::ChatLinks => on_off(s.chat_links), + Opt::ChatLinksPrompt => on_off(s.chat_links_prompt), Opt::AutoSuggestions => on_off(s.auto_suggestions), Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), @@ -743,6 +746,7 @@ impl Opt { Opt::ChatVisibility => s.chat_visibility = next(s.chat_visibility, 3), Opt::ChatColors => s.chat_colors = !s.chat_colors, Opt::ChatLinks => s.chat_links = !s.chat_links, + Opt::ChatLinksPrompt => s.chat_links_prompt = !s.chat_links_prompt, Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions, Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, @@ -1487,6 +1491,7 @@ impl OptionsUi { Opt::ChatVisibility, Opt::ChatColors, Opt::ChatLinks, + Opt::ChatLinksPrompt, Opt::ChatOpacity, Opt::TextBackgroundOpacity, Opt::ChatScale, diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..c64cfcb33 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -149,6 +149,7 @@ pub struct Settings { pub chat_visibility: u8, pub chat_colors: bool, pub chat_links: bool, + pub chat_links_prompt: bool, pub chat_opacity: f32, pub text_background_opacity: f32, pub chat_scale: f32, @@ -234,6 +235,7 @@ impl Default for Settings { chat_visibility: 0, chat_colors: true, chat_links: true, + chat_links_prompt: true, chat_opacity: 1.0, text_background_opacity: 0.5, chat_scale: 1.0, @@ -427,6 +429,7 @@ impl Settings { chat_visibility: f.int("chatVisibility") as u8, chat_colors: f.bool("chatColors"), chat_links: f.bool("chatLinks"), + chat_links_prompt: f.bool("chatLinksPrompt"), chat_opacity: f.double("chatOpacity") as f32, text_background_opacity: f.double("textBackgroundOpacity") as f32, chat_scale: f.double("chatScale") as f32, @@ -510,6 +513,7 @@ impl Settings { put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility)); put_b(&mut f, "chatColors", self.chat_colors); put_b(&mut f, "chatLinks", self.chat_links); + put_b(&mut f, "chatLinksPrompt", self.chat_links_prompt); put_f(&mut f, "chatOpacity", self.chat_opacity); put_f( &mut f, diff --git a/crates/horizon-protocol/src/packets/configuration.rs b/crates/horizon-protocol/src/packets/configuration.rs index ced56dacf..22a8a1456 100644 --- a/crates/horizon-protocol/src/packets/configuration.rs +++ b/crates/horizon-protocol/src/packets/configuration.rs @@ -45,6 +45,54 @@ packet!( packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str }); packet!(SelectKnownPacks { packs: Vec => List }); packet!(CodeOfConduct { text: String => Str }); + +/// ServerLinks.UntrustedEntry's `type` (Either): a +/// known link's id, or a custom label component. +#[derive(Clone, Debug, PartialEq)] +pub enum ServerLinkKind { + /// ServerLinks.KnownLinkType by id (ByIdMap: unknown ids read as 0). + Known(i32), + /// A custom label (TRUSTED_CONTEXT_FREE_STREAM_CODEC: a component in NBT). + Custom(Tag), +} +/// ServerLinks.UntrustedEntry: the label and the unchecked link string (the +/// client keeps only `http`/`https` URIs, Util.parseAndValidateUntrustedUri). +#[derive(Clone, Debug, PartialEq)] +pub struct ServerLink { + pub kind: ServerLinkKind, + pub link: String, +} +impl Codec for ServerLink { + fn read(r: &mut Reader) -> Result { + let kind = if Bool::read(r)? { + ServerLinkKind::Known(VarInt::read(r)?) + } else { + ServerLinkKind::Custom(Nbt::read(r)?) + }; + Ok(Self { + kind, + link: Str::read(r)?, + }) + } + fn write(v: &Self, w: &mut Writer) { + match &v.kind { + ServerLinkKind::Known(id) => { + Bool::write(&true, w); + VarInt::write(id, w); + } + ServerLinkKind::Custom(tag) => { + Bool::write(&false, w); + Nbt::write(tag, w); + } + } + Str::write(&v.link, w); + } +} +packet!( + /// ClientboundServerLinksPacket (a common packet: configuration and play). + /// Links the pause menu's "Server Links..." screen lists. + ServerLinks { links: Vec => List } +); packet!( /// ClientboundShowDialogPacket.CONTEXT_FREE_STREAM_CODEC: the dialog /// itself (`Dialog.DIRECT_CODEC` as NBT). @@ -89,6 +137,7 @@ packet_enum!(Clientbound, crate::ids::configuration::clientbound { UpdateTags(UpdateTags) = UPDATE_TAGS, SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, ClearDialog(Empty) = CLEAR_DIALOG, + ServerLinks(ServerLinks) = SERVER_LINKS, ShowDialog(ShowDialog) = SHOW_DIALOG, CodeOfConduct(CodeOfConduct) = CODE_OF_CONDUCT, }); @@ -236,6 +285,18 @@ mod tests { Clientbound::CodeOfConduct(CodeOfConduct { text: "Be nice".into(), }), + Clientbound::ServerLinks(ServerLinks { + links: vec![ + ServerLink { + kind: ServerLinkKind::Known(0), + link: "https://bugs.example.net".into(), + }, + ServerLink { + kind: ServerLinkKind::Custom(crate::text::literal("Custom link")), + link: "https://example.net".into(), + }, + ], + }), Clientbound::ShowDialog(ShowDialog { dialog: Tag::compound([("type", Tag::String("minecraft:notice".into()))]), }), diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bc09a84..a21171693 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -15,7 +15,7 @@ use crate::{ configuration::{ ClientInformation, CookieRequest, CookieResponse, CustomClickAction, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, - StoreCookie, Transfer, UpdateTags, + ServerLinks, StoreCookie, Transfer, UpdateTags, }, login::Property, }, @@ -1903,6 +1903,9 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { StopSound(StopSound) = STOP_SOUND, StartConfiguration(Empty) = START_CONFIGURATION, StoreCookie(StoreCookie) = STORE_COOKIE, + // A common packet: the same `configuration::ServerLinks` the + // configuration phase sends. + ServerLinks(ServerLinks) = SERVER_LINKS, SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, TabList(TabList) = TAB_LIST, From 8526305faa2a15aa0b3f737ad5b0c4ea5d0e9bc2 Mon Sep 17 00:00:00 2001 From: Senjin Date: Mon, 26 Oct 2026 18:04:54 +0100 Subject: [PATCH 06/65] HDR: mark only the sun's and moon's discs, not their whole quads The celestial pass wrote alpha 0 over each quad, so HDR output lifted a square of bright daytime sky around the sun. It now draws premultiplied (one, one), which looks the same, and its alpha is how much a texel adds; the blend takes that off the frame's alpha, so only the discs shine. The dim End sky, drawn by the same pass, stays unmarked. fs_celestial keeps its own blend for lightning and additive entities. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity.wgsl | 17 +++++++++++++++-- crates/horizon-client/src/gfx.rs | 13 +++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..93c2a4105 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -208,9 +208,22 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } +fn celestial_color(in: Out) -> vec4 { + return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; +} @fragment fn fs_celestial(in: Out) -> @location(0) vec4 { - let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; - return color; + return celestial_color(in); +} + +// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light, +// premultiplied for an additive (one, one) blend, and as alpha how much of it +// the texel adds, which the blend takes off the frame's alpha. HDR output +// (hdr.wgsl) lifts only where that left it low: the sun's and moon's discs, not +// the dark rest of their quads or the dim End sky. +@fragment fn fs_sky_celestial(in: Out) -> @location(0) vec4 { + let color = celestial_color(in); + let added = color.rgb * color.a; + return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b)))); } // RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 904370c04..c18f2cb6c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1939,22 +1939,23 @@ impl Renderer { multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &entity_shader, - entry_point: Some("fs_celestial"), + entry_point: Some("fs_sky_celestial"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), - // RenderPipelines.CELESTIAL: additive (src alpha, one). The - // alpha goes to 0: HDR output (hdr.wgsl) lets the sun and - // moon shine; nothing else reads the frame's alpha. + // RenderPipelines.CELESTIAL: additive (src alpha, one), with + // the colour premultiplied in fs_sky_celestial. Its alpha is + // how much a texel adds: HDR output (hdr.wgsl) lets the sun's + // and moon's discs shine; nothing else reads the frame's alpha. blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, + src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Zero, - dst_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, }), From de141bb7cb6ad3260a9dff083fc7ad35dd2cf8cc Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:11:51 +0000 Subject: [PATCH 07/65] Fix recipe book settings persistence on the server Send open/filter changes to the authoritative player's recipe book and cover packet settings plus save/reopen in both single-player modes. Co-Authored-By: OpenCode GPT-6.1 Sol --- .../examples/probe/recipe_book_fixture.rs | 23 ++++++- crates/horizon-client/src/game/agent.rs | 3 + crates/horizon-client/src/game/recipe_book.rs | 18 +++++ crates/horizon-client/src/lan/hub.rs | 10 +++ crates/horizon-client/tests/lan_bot.rs | 69 +++++++++++++++++++ crates/horizon-protocol/src/packets/play.rs | 1 + .../horizon-protocol/src/packets/recipes.rs | 27 ++++++++ .../parity/VanillaRecipeBookOracle.java | 21 +++++- tools/lan_e2e.py | 59 ++++++++++++++++ tools/test_recipe_book_parity.py | 11 ++- 10 files changed, 236 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/examples/probe/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs index ce2afe624..2dda3b109 100644 --- a/crates/horizon-client/examples/probe/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -5,6 +5,10 @@ //! //! usage: recipe_book_fixture RESOURCES CASES OUTPUT use horizon_client::recipe_book::{BookType, RecipeIndex, Settings}; +use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::recipes::RecipeBookChangeSettings, +}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::BTreeSet, fs, path::Path}; @@ -93,8 +97,23 @@ pub fn main() -> horizon_client::Result<()> { _ => BookType::Smoker, } .index(); - book.open[i] = op["open"].as_bool().unwrap_or(false); - book.filtering[i] = op["filtering"].as_bool().unwrap_or(false); + let packet = RecipeBookChangeSettings { + book_type: i as i32, + open: op["open"].as_bool().unwrap_or(false), + filtering: op["filtering"].as_bool().unwrap_or(false), + }; + let mut wire = Writer::new(); + RecipeBookChangeSettings::write(&packet, &mut wire); + extra = format!( + " packet={}", + wire.data + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ); + let decoded = RecipeBookChangeSettings::read(&mut Reader::new(&wire.data))?; + book.open[decoded.book_type as usize] = decoded.open; + book.filtering[decoded.book_type as usize] = decoded.filtering; } "save" => { let tag = book.write(); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0d2d218ab..1433e92e8 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -686,9 +686,12 @@ impl Game<'_> { // the recipe buttons of the page, page arrows, filter and tabs. let book = self.recipe_book_targets(); if !book.is_empty() { + let (open, filtering) = self.recipe_book_flags().unwrap_or_default(); v["recipe_book"] = json!({ "targets": book.iter().map(|t| t.rect).collect::>(), "known": self.recipe_book_known(), + "open": open, + "filtering": filtering, }); } v["slot_ids"] = json!( diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 96e12d79b..bf0d1c370 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -590,6 +590,7 @@ impl Game<'_> { if inside(cursor, bx, by, 20.0, 18.0) { let open = !self.book_open(book_type); self.level.recipe_book.open[book_type.index()] = open; + self.send_book_settings(book_type); if !open { self.recipe_ui.overlay = None; } @@ -675,6 +676,7 @@ impl Game<'_> { if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; + self.send_book_settings(book_type); self.recipe_ui.page = 0; self.audio .play("minecraft:ui.button.click", None, 0.25, 1.0); @@ -695,6 +697,22 @@ impl Game<'_> { } false } + /// `RecipeBookComponent.sendUpdateSettings`: the server owns the saved book. + fn send_book_settings(&self, book_type: BookType) { + self.send( + horizon_protocol::packets::play::Serverbound::RecipeBookChangeSettings( + horizon_protocol::packets::recipes::RecipeBookChangeSettings { + book_type: book_type.index() as i32, + open: self.book_open(book_type), + filtering: self.book_filtering(book_type), + }, + ), + ); + } + pub(super) fn recipe_book_flags(&self) -> Option<(bool, bool)> { + let book = self.active_book()?; + Some((self.book_open(book), self.book_filtering(book))) + } /// How many displays the client's book holds. pub(super) fn recipe_book_known(&self) -> usize { self.recipe_ui.client.displays().len() diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b462536b9..dc0dbe89d 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1930,6 +1930,7 @@ impl Hub { | S::PlayerLoaded(_) | S::ChunkBatchReceived(_) | S::ClientInformation(_) + | S::RecipeBookChangeSettings(_) | S::ClientTickEnd(_) | S::KeepAlive(_) => false, S::MovePlayerPos(p) => self.moved_far(i, [p.x, p.y, p.z]), @@ -1996,6 +1997,15 @@ impl Hub { g.max_unacknowledged = 10; } S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, + // ServerGamePacketListenerImpl.handleRecipeBookChangeSettingsPacket. + S::RecipeBookChangeSettings(p) => { + if let Some(book) = crate::recipe_book::BookType::ALL.get(p.book_type as usize) + { + let settings = &mut self.guests[i].recipe_book; + settings.open[book.index()] = p.open; + settings.filtering[book.index()] = p.filtering; + } + } S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 34e8265a1..81ec192f5 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -278,6 +278,75 @@ fn run( handle.join().unwrap().unwrap() } +#[test] +fn recipe_settings_packets_update_only_the_players_book_and_survive_save() { + let Some(resources) = resources() else { + return; + }; + let mut s = server(&resources); + let port = s.hub.lan.port; + let _bot = run(&mut s, move || connect(port, "RecipeSettings", true)); + let deadline = Instant::now() + Duration::from_secs(5); + while s.hub.guests.is_empty() { + s.tick(&[]); + assert!(Instant::now() < deadline, "guest did not join"); + thread::yield_now(); + } + for book in 0..4 { + for flags in 0..4 { + let open = flags & 1 != 0; + let filtering = flags & 2 != 0; + let before = s.hub.guests[0].recipe_book.clone(); + // Vanilla's wire payload: RecipeBookType VarInt, open, filtering. + let packet = S::decode( + horizon_protocol::ids::play::serverbound::RECIPE_BOOK_CHANGE_SETTINGS, + &[book, u8::from(open), u8::from(filtering)], + ) + .unwrap(); + s.hub.guests[0].inbox.push_back(packet); + s.tick(&[]); + let settings = &s.hub.guests[0].recipe_book; + for i in 0..4 { + assert_eq!( + settings.open[i], + if i == usize::from(book) { + open + } else { + before.open[i] + } + ); + assert_eq!( + settings.filtering[i], + if i == usize::from(book) { + filtering + } else { + before.filtering[i] + } + ); + } + let mut saved = horizon_client::save::Level::default(); + horizon_client::lan::playerdata::store(&s.hub.guests[0], &mut saved); + let mut reopened = horizon_client::save::Level::default(); + reopened.read_player(&saved.player_tag()); + assert_eq!(reopened.recipe_book.open, settings.open); + assert_eq!(reopened.recipe_book.filtering, settings.filtering); + } + } + for book_type in [-1, 4] { + let mut wire = horizon_protocol::buf::Writer::new(); + wire.varint(book_type); + wire.bool(true); + wire.bool(true); + assert!( + S::decode( + horizon_protocol::ids::play::serverbound::RECIPE_BOOK_CHANGE_SETTINGS, + &wire.data, + ) + .is_err() + ); + } +} + #[test] fn sprint_commands_survive_keyboard_input_changes() { let Some(resources) = resources() else { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 67373cf4b..1c20ed36c 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2219,6 +2219,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ChatCommandSigned(ChatCommandSigned) = CHAT_COMMAND_SIGNED, ChatSessionUpdate(ChatSessionUpdate) = CHAT_SESSION_UPDATE, PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE, + RecipeBookChangeSettings(super::recipes::RecipeBookChangeSettings) = RECIPE_BOOK_CHANGE_SETTINGS, ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, ClientCommand(ClientCommand) = CLIENT_COMMAND, ClientInformation(ClientInformation) = CLIENT_INFORMATION, diff --git a/crates/horizon-protocol/src/packets/recipes.rs b/crates/horizon-protocol/src/packets/recipes.rs index c289b8943..dcbe5ffa0 100644 --- a/crates/horizon-protocol/src/packets/recipes.rs +++ b/crates/horizon-protocol/src/packets/recipes.rs @@ -500,6 +500,33 @@ impl Codec for RecipeBookSettings { } } +/// ServerboundRecipeBookChangeSettingsPacket: the active book's open and +/// filtering flags, with its `RecipeBookType` ordinal as a VarInt. +#[derive(Clone, Debug, PartialEq)] +pub struct RecipeBookChangeSettings { + pub book_type: i32, + pub open: bool, + pub filtering: bool, +} +impl Codec for RecipeBookChangeSettings { + fn read(r: &mut Reader) -> Result { + let book_type = r.varint()?; + if !(0..4).contains(&book_type) { + return Err(crate::Error::new("invalid recipe book type")); + } + Ok(Self { + book_type, + open: r.bool()?, + filtering: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.book_type); + w.bool(v.open); + w.bool(v.filtering); + } +} + /// ClientboundPlaceGhostRecipePacket: the recipe to show faded in a menu /// whose items were missing. #[derive(Clone, Debug, PartialEq)] diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java index 60640010b..2cf9d7d48 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java @@ -1,12 +1,15 @@ package dev.horizonlab.parity; import com.google.gson.*; +import io.netty.buffer.Unpooled; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.*; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerboundRecipeBookChangeSettingsPacket; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerPlayer; @@ -102,8 +105,22 @@ public final class VanillaRecipeBookOracle { count = kind.equals("give") ? book.addRecipes(holders, player) : book.removeRecipes(holders, player); } case "seen" -> book.removeHighlight(key(op.get("id").getAsString())); - case "set" -> book.setBookSetting(RecipeBookType.valueOf(op.get("type").getAsString()), - op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean()); + case "set" -> { + var packet = new ServerboundRecipeBookChangeSettingsPacket( + RecipeBookType.valueOf(op.get("type").getAsString()), + op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean()); + var buf = new FriendlyByteBuf(Unpooled.buffer()); + try { + ServerboundRecipeBookChangeSettingsPacket.STREAM_CODEC.encode(buf, packet); + byte[] wire = new byte[buf.readableBytes()]; + buf.getBytes(buf.readerIndex(), wire); + extra = " packet=" + HexFormat.of().formatHex(wire); + var decoded = ServerboundRecipeBookChangeSettingsPacket.STREAM_CODEC.decode(buf); + book.setBookSetting(decoded.getBookType(), decoded.isOpen(), decoded.isFiltering()); + } finally { + buf.release(); + } + } case "save" -> { saved = (CompoundTag) ServerRecipeBook.Packed.CODEC.encodeStart(NbtOps.INSTANCE, book.pack()).getOrThrow(); extra = compound(saved); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0ec7218d8..1866a6ee3 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -5877,6 +5877,65 @@ CHECKS += ['recipe_removal'] CHECK_FNS.update(recipe_removal=check_recipe_removal) +def check_recipe_settings(host, guest, out): + """RecipeBookComponent sends both settings to the server; each player's + own book keeps them when the authoritative world saves and reopens (#2290).""" + def inventory(game): + back_to_game(game) + game.raw('key', 'e', 'tap') + game.wait(5) + return game('screen')['recipe_book'] + + def flags(book): + return {'open': book['open'], 'filtering': book['filtering']} + + def set_flags(game, opened, filtering): + book = inventory(game) + if not book['open']: + game.raw('click-at', *centre(book['targets'][0])) + game.wait(5) + book = game('screen')['recipe_book'] + if book['filtering'] != filtering: + target = next(t for t in book['targets'] if t[2:] == [26.0, 16.0]) + game.raw('click-at', *centre(target)) + game.wait(5) + if not opened: + book = game('screen')['recipe_book'] + game.raw('click-at', *centre(book['targets'][0])) + game.wait(5) + actual = flags(game('screen')['recipe_book']) + assert actual == {'open': opened, 'filtering': filtering}, f'{game.name}: {actual}' + game.shot(out, 'recipe-settings-before') + back_to_game(game) + return actual + + # Deliberately different settings ensure neither player's book overwrites the other's. + before = {host.name: set_flags(host, True, True), + guest.name: set_flags(guest, False, True)} + host.wait(20) + guest.raw('disconnect') + host.raw('pause') + host.raw('click-button', 'Save and Quit to Title') + host.raw('wait-for', 'screen', 'title', '--timeout', 120) + host.raw('open', 'Lan') + host('wait_ready', seconds=400) + port = host.raw('lan', 'open', 0, 'commands')['port'] + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + after = {} + for game in (host, guest): + after[game.name] = flags(inventory(game)) + game.shot(out, 'recipe-settings-reopened') + back_to_game(game) + assert after == before, f'saved recipe settings reset: before={before}, after={after}' + return {'before': before, 'reopened': after} + + +CHECKS += ['recipe_settings'] +CHECK_FNS.update(recipe_settings=check_recipe_settings) + + def check_shulker_bullets(host, guest, out): """ShulkerAttackGoal's bullets reach ClientPacketListener.handleAddEntity, then the existing projectile renderer and interpolation, with distinct ids from the server's entity counter.""" diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py index c25f180ac..291adeb86 100644 --- a/tools/test_recipe_book_parity.py +++ b/tools/test_recipe_book_parity.py @@ -5,8 +5,9 @@ Each case runs a sequence of operations on a fresh book: awarding recipes (advancement rewards, /recipe give, crafting; special recipes are never learnt, and the count is the displays added), taking them back, the client having seen a highlighted recipe, the open and filter settings of the four -book types, and saving and loading the player's recipeBook compound (with -unknown ids dropped, and a compound missing a list ignored). The Java oracle +book types (through the serverbound settings packet's codec), and saving and +loading the player's recipeBook compound (with unknown ids dropped, and a +compound missing a list ignored). The Java oracle (VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; examples/probe/recipe_book_fixture drives horizon_client::recipe_book. After each operation the count, the known and highlighted recipes, the settings and @@ -35,6 +36,12 @@ def main(): ids = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')) rng = random.Random(args.seed) cases = [] + # Every book and flag combination crosses the wire, then survives a save/load. + for book_type in TYPES: + for opened in (False, True): + for filtering in (False, True): + cases.append({'ops': [{'op': 'set', 'type': book_type, 'open': opened, + 'filtering': filtering}, {'op': 'save'}, {'op': 'load'}]}) for _ in range(args.cases): ops, known = [], set() for _ in range(rng.randrange(1, 12)): From 004ad993d9e77d8262094afea01b2351b1bf3403 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:16:15 +0000 Subject: [PATCH 08/65] Reject boarding a horse with an existing mob passenger Fixes #1759 Co-Authored-By: OpenAI Codex GPT-6.1 Sol --- crates/horizon-client/src/game/mounts.rs | 11 ++++++ tools/lan_e2e.py | 47 +++++++++++++++++++++++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa4bbc209..7da98135f 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -175,6 +175,17 @@ impl Game<'_> { return true; } // doPlayerRide + // Entity.canAddPassenger: ordinary horses have one seat. Camels + // override that capacity; equipment and feeding above are separate. + if !matches!(species, Species::Camel | Species::CamelHusk) + && self.mobs.iter().any(|passenger| { + passenger.extra.mount == Some(self.mobs[index].id) + && !passenger.removed + && passenger.alive() + }) + { + return false; + } let m = &mut self.mobs[index]; m.extra.flag = false; m.extra.counter = 0; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c508a67d6..f179a201c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -299,7 +299,7 @@ CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'si 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', - 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', + 'lightning', 'riding', 'occupied_horse', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater', 'fireworks'] @@ -4199,6 +4199,49 @@ def check_riding(host, guest, out): return result +def check_occupied_horse(host, guest, out): + """#1759: a mob passenger fills a zombie horse's seat, for both real players.""" + spots = apart(host, guest) + result = {} + tag = 'occupied_horse' + host('command', command='time set midnight') + for label, player in (('host', host), ('guest', guest)): + x, y, z = spots[label] + at = (x + 0.5, y, z + 2.5) + player('command', command='gamemode creative') + player('command', command='clear @s') + result[label] = {} + for occupied in (True, False): + passengers = ',Passengers:[{id:"minecraft:zombie",NoAI:1b,PersistenceRequired:1b}]' if occupied else '' + try: + player('command', command=f'summon minecraft:zombie_horse {at[0]} {y} {at[2]} ' + f'{{Tame:1b,NoAI:1b,NoGravity:1b,Tags:["{tag}"]{passengers}}}') + player.wait(5) + horse = next(m for m in player.raw('mobs', 16)['near'] + if m['kind'] == 'minecraft:zombie_horse' and m['health'] > 0 + and math.dist(m['pos'], at) < 0.1) + if occupied: + # Assert the setup too: a missing passenger would make this a false positive. + passengers_nbt = player('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') + assert 'minecraft:zombie' in json.dumps(passengers_nbt), passengers_nbt + player.raw('look-at', at[0], y + 0.8, at[2]) + player.raw('mouse', 'right', 'click') + player.wait(10) + riding = player('status').get('riding') + expected = None if occupied else horse['id'] + assert riding == expected, f'{label}: occupied={occupied}, riding={riding}, expected={expected}' + result[label]['occupied' if occupied else 'free'] = riding + player.shot(out, f'occupied-horse-{label}-{occupied}') + if not occupied: + hold(player, 'shift', 5) + finally: + player('command', command=f'kill @e[tag={tag}]') + player('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..6]') + player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0') + player.wait(25) + return result + + # Mount inventories: (kind, summon NBT, what goes in by shift-click and the menu slot it lands # in: 700 the saddle, 701 the body armour or carpet, 710 the chest's first slot). MOUNT_MENUS = [ @@ -4688,7 +4731,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, - 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'lightning': check_lightning, 'riding': check_riding, 'occupied_horse': check_occupied_horse, 'mounts': check_mounts, 'worldspawn': check_world_spawn, 'beds': check_beds, 'shield': check_shield, 'deathmining': check_death_mining, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, From 442d52a038aa50a715e5517d59f3a1d78ec075e6 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:19:04 +0000 Subject: [PATCH 09/65] Release notes: preserve wrapped known issues Co-Authored-By: OpenCode agentrouter/gpt-6.1-sol --- tests/test_release_train.py | 28 ++++++++++++++++++++++++++-- tools/release_train.py | 12 +++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 56064fa42..58fc591b1 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -219,10 +219,34 @@ class ReleaseTrainTests(unittest.TestCase): def test_known_issues_are_the_bullets_of_the_file(self): with tempfile.TemporaryDirectory() as temp: path = Path(temp, "known-issues.md") - path.write_text("# Known issues\n\nSome text.\n\n- One.\n- Two, with **bold**.\n continued\n") - self.assertEqual(train.known_issues(path), ["- One.", "- Two, with **bold**."]) + path.write_text("# Known issues\n\nSome text.\n\n- One.\n- Two, with **bold**. \n" + " continued with `code`\n\tand a [link](https://example.com). \n- Three.\n") + self.assertEqual(train.known_issues(path), + ["- One.", "- Two, with **bold**. continued with `code` and a [link](https://example.com).", + "- Three."]) self.assertEqual(train.known_issues(Path(temp, "missing.md")), []) + def test_known_issues_do_not_include_unrelated_text(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp, "known-issues.md") + for separator in ["\n", " \n", "# Heading\n", "Some text.\n"]: + with self.subTest(separator=separator): + path.write_text(" Intro.\n- One.\n continued.\n" + separator + " Not an issue.\n- Two.\n") + self.assertEqual(train.known_issues(path), ["- One. continued.", "- Two."]) + path.write_text("# Known issues\n\nNo issues.\n") + self.assertEqual(train.known_issues(path), []) + path.write_text("") + self.assertEqual(train.known_issues(path), []) + + def test_notes_keep_the_wrapped_shaderpacks_issue(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp, "known-issues.md") + path.write_text("- Shader packs have been removed for now. Packs in your\n" + " `shaderpacks` folder are left where they are.\n") + _, body = train.notes("game", "v0.2.70", [pr(1)], train.known_issues(path)) + self.assertIn("### Known issues\n- Shader packs have been removed for now. Packs in your " + "`shaderpacks` folder are left where they are.\n", body) + if __name__ == "__main__": unittest.main() diff --git a/tools/release_train.py b/tools/release_train.py index 48d4d46cf..1e4fa5a19 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -347,7 +347,17 @@ def bullet(pr): def known_issues(path=ROOT / "docs" / "known-issues.md"): if not path.exists(): return [] - return [line.rstrip() for line in path.read_text().splitlines() if line.startswith("- ")] + issues = [] + in_bullet = False + for line in path.read_text().splitlines(): + if line.startswith("- "): + issues.append(line.rstrip()) + in_bullet = True + elif in_bullet and line.startswith((" ", "\t")) and line.strip(): + issues[-1] += " " + line.strip() + else: + in_bullet = False + return issues def line_intro(kind, version, previous): From f661443fa993eb4d26649cb6b7c9c67d76cd683e Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:22:50 +0000 Subject: [PATCH 10/65] Read LAN passenger fixture output through the host Co-Authored-By: OpenAI Codex GPT-6.1 Sol --- tools/lan_e2e.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f179a201c..f16e6312b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4222,7 +4222,7 @@ def check_occupied_horse(host, guest, out): and math.dist(m['pos'], at) < 0.1) if occupied: # Assert the setup too: a missing passenger would make this a false positive. - passengers_nbt = player('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') + passengers_nbt = host('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') assert 'minecraft:zombie' in json.dumps(passengers_nbt), passengers_nbt player.raw('look-at', at[0], y + 0.8, at[2]) player.raw('mouse', 'right', 'click') From 2c8b933be483bcf6d44437fb0763facfee707095 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 18:30:53 +0100 Subject: [PATCH 11/65] Apply vanilla's view scale to entity render distance Entity.shouldRenderAtSqrDistance scales the bounding box's mean edge by 64 * viewScale, and LevelExtractor sets viewScale to the entity distance option times clamp(renderDistance / 8, 1, 2.5). Horizon used the option alone, so above render distance 8 entities vanished sooner than vanilla: a chicken at 32 blocks instead of 48 at the default 12. RemotePlayer's box also counts ten times. Fixes #2273 Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/boats.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 13 ++++++++++--- crates/horizon-client/src/game/cushions.rs | 3 +-- crates/horizon-client/src/game/entity_culling.rs | 16 +++++++++++++--- crates/horizon-client/src/game/frames.rs | 5 +++-- crates/horizon-client/src/game/minecarts.rs | 5 ++--- crates/horizon-client/src/game/paintings.rs | 3 +-- crates/horizon-client/src/game/text_displays.rs | 3 ++- crates/horizon-client/src/game/tnt.rs | 2 +- crates/horizon-client/src/game/trident.rs | 2 +- 10 files changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 06dfab22d..7e80f6f58 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -862,7 +862,7 @@ impl Game<'_> { let a = alpha as f32; let range = super::entity_culling::default_range( glam::DVec3::new(WIDTH, HEIGHT, WIDTH), - self.settings.entity_distance, + self.view_scale(), ); for b in &self.boats { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index a2ed7fd66..f8c28732a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3032,7 +3032,7 @@ impl Game<'_> { pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); - let scale = f64::from(self.settings.entity_distance); + let scale = self.view_scale(); for mob in &self.mobs { let entity_start = out.len(); // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. @@ -3041,9 +3041,16 @@ impl Game<'_> { } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's - // mean edge, scaled by the entity distance option. + // mean edge, scaled by the view scale. RemotePlayer's box counts + // ten times. let (w, h, _) = mob.dims(); - let range = (w + h + w) / 3.0 * 64.0 * scale; + let edge = (w + h + w) / 3.0 + * if &*mob.kind.id == "minecraft:player" { + 10.0 + } else { + 1.0 + }; + let range = edge * 64.0 * scale; if d.length_squared() >= range * range { continue; } diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs index 0847321d6..216e2cc1b 100644 --- a/crates/horizon-client/src/game/cushions.rs +++ b/crates/horizon-client/src/game/cushions.rs @@ -455,8 +455,7 @@ impl Game<'_> { glam::DVec3::new(lo.x, lo.y, lo.z), glam::DVec3::new(hi.x, hi.y, hi.z), ); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 66fbaa3e4..4377b2f8d 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -60,12 +60,22 @@ impl Game<'_> { } } +impl Game<'_> { + /// Entity.setViewScale (LevelExtractor.extractVisibleEntities): the entity + /// distance option times the render distance's boost — 1 at 8 chunks, 2.5 + /// at 20 or more (`streaming.radius` is the effective render distance). + pub(super) fn view_scale(&self) -> f64 { + (f64::from(self.streaming.radius) / 8.0).clamp(1.0, 2.5) + * f64::from(self.settings.entity_distance) + } +} + /// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding -/// box's mean edge, scaled by the entity distance option. -pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 { +/// box's mean edge, scaled by the view scale. +pub(super) fn default_range(size: glam::DVec3, view_scale: f64) -> f64 { let edge = (size.x + size.y + size.z) / 3.0; let edge = if edge.is_nan() { 1.0 } else { edge }; - edge * 64.0 * f64::from(view_scale) + edge * 64.0 * view_scale } impl Game<'_> { diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index d08c5f283..b4e6bb158 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -311,8 +311,9 @@ impl Game<'_> { let sprites = &self.gui.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); - // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%. - let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance); + // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at a view scale + // of 1. + let range = 16.0 * 64.0 * self.view_scale(); for f in &self.item_frames { let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..781dd6b7c 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1340,9 +1340,8 @@ impl Game<'_> { return; }; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean - // edge, scaled by the entity distance option. - let range = - (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance); + // edge, scaled by the view scale. + let range = (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * self.view_scale(); for c in &self.carts { let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 321e59f7d..1b839f5b0 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -267,8 +267,7 @@ impl Game<'_> { // measured from the box's centre (HangingEntity's position). let (lo, hi) = p.bounds(); let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/text_displays.rs b/crates/horizon-client/src/game/text_displays.rs index 45bd64fa7..587db3382 100644 --- a/crates/horizon-client/src/game/text_displays.rs +++ b/crates/horizon-client/src/game/text_displays.rs @@ -164,11 +164,12 @@ impl Game<'_> { } else { [self.yaw, self.pitch] }; + let scale = self.view_scale(); for display in self.text_displays.values_mut() { display.last_progress = display.progress(partial as f32); let d = display.shown.blend(&display.from, display.last_progress); let position = display.previous.lerp(display.position, partial); - let range = f64::from(d.view_range) * 64.0 * f64::from(self.settings.entity_distance); + let range = f64::from(d.view_range) * 64.0 * scale; if position.distance_squared(camera) >= range * range || d.text.is_empty() { continue; } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 6bd2ae956..177e3bf80 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -252,7 +252,7 @@ impl Game<'_> { } let range = super::entity_culling::default_range( glam::DVec3::splat(PrimedTnt::SIZE), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tnts { // EntityRenderer.shouldRender. diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index c31094596..cfb8d807c 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -419,7 +419,7 @@ impl Game<'_> { let range = 10.0 * super::entity_culling::default_range( glam::DVec3::splat(2.0 * HALF), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tridents { // EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5. From 76d748caf8b5d5a5e8e5446c0533d862197f3cf3 Mon Sep 17 00:00:00 2001 From: Pavel Mikhailovin Date: Mon, 26 Oct 2026 20:43:35 +0300 Subject: [PATCH 12/65] Server books: positional page indicator and component-list pages The page indicator only replaced bare %s, but 26.3's en_us template is "Page %1$s of %2$s"; it now goes through format_java like other translations (BookViewScreen.getPageNumberMessage). Pages sent as a component list (Hypixel through ViaVersion) were dropped by item_data::read_text, which only took a string or a compound, so the book opened blank. ComponentSerialization.CODEC also takes a list. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/books.rs | 9 ++++--- crates/horizon-client/src/item_data.rs | 35 ++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 2f38dffd9..b09803e49 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -1009,9 +1009,12 @@ impl Game<'_> { } }; let indicator = |batch: &mut HudBatch, page: usize, count: usize| { - let text = tr("book.pageIndicator", "Page %s of %s") - .replacen("%s", &(page + 1).to_string(), 1) - .replacen("%s", &count.max(1).to_string(), 1); + // BookViewScreen.getPageNumberMessage: 26.3's en_us template is + // positional ("Page %1$s of %2$s"). + let text = horizon_protocol::text::format_java( + &tr("book.pageIndicator", "Page %1$s of %2$s"), + &[(page + 1).to_string(), count.max(1).to_string()], + ); let tw = HudBatch::text_width(atlas, &text); batch.text(atlas, &text, left + 148.0 - tw, top + 16.0, BLACK, false); }; diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index ac624e85b..3d4fb11e5 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -305,7 +305,9 @@ fn read_text(t: &Tag) -> Option { // A component's root `text` may be empty with the visible words in // `extra` (every legacy display name ViaVersion produces looks like // this), so flatten the whole component instead of reading one key. - Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()), + // ComponentSerialization.CODEC also takes a list (its first element + // styling the rest), as servers behind ViaVersion send book pages. + Tag::Compound(_) | Tag::List(_) => Some(crate::entity_nbt::name_text(t).plain()), _ => None, } } @@ -899,6 +901,37 @@ mod tests { ); } + #[test] + fn written_book_pages_may_be_component_lists() { + // A page as Hypixel sends it through ViaVersion: a list, not a compound. + let page = Tag::List(vec![ + Tag::compound([("text", Tag::String("".into()))]), + Tag::compound([("text", Tag::String("Please read ".into()))]), + Tag::compound([("text", Tag::String("the rules".into()))]), + ]); + let book = Tag::compound([ + ( + "title", + Tag::compound([("raw", Tag::String("Rules".into()))]), + ), + ("author", Tag::String("Server".into())), + ( + "pages", + Tag::List(vec![ + page, + Tag::compound([("raw", Tag::String("Two".into()))]), + ]), + ), + ]); + let components = Tag::compound([("minecraft:written_book_content", book)]); + let (_, extra) = decode_components(Some(&components)); + let pages = extra.and_then(|d| d.written.clone()).map(|w| w.pages); + assert_eq!( + pages, + Some(vec!["Please read the rules".to_owned(), "Two".to_owned()]) + ); + } + #[test] fn banner_layers_and_shield_base_round_trip() { let mut stack = ItemStack::new("minecraft:shield", 1); From 7f5e3384b375c822d634f00a020f13f4992263f1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:07:11 +0100 Subject: [PATCH 13/65] Play mining hit sounds once, from the server's destroy level events The server now sends level events 2019 and 2020 every tick a player digs (ServerPlayerGameMode.tick), and clients handle them like LevelEventHandler: a crack on the face, plus the hit sound for 2020. A remote client plays only the first hit itself and no longer adds its own sound every fourth tick, so the hit was heard twice, out of phase, for every block. --- crates/horizon-client/src/game.rs | 45 ++++++++++++------- crates/horizon-client/src/game/lan.rs | 5 ++- .../src/game/level_particles.rs | 24 ++++++++++ crates/horizon-client/src/game/remote.rs | 17 ++----- 4 files changed, 60 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8448f0837..a0bc6c339 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2844,6 +2844,16 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + // LevelEventHandler 2019 and 2020: the crack on a face of the + // block being mined, with its hit sound for 2020. + LevelEvent::LevelEvent { + id: id @ (2019 | 2020), + pos, + data, + } => { + let face = horizon_core::geometry::Direction::ALL[data.clamp(0, 5) as usize]; + self.breaking_block_effects([pos.x, pos.y, pos.z], face.normal(), id == 2020); + } LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } @@ -4042,6 +4052,17 @@ impl Game<'_> { _ => {} } } + /// `ServerPlayerGameMode.tick` while a player digs: level event 2020 every + /// fourth tick since the START (the hit sound), else 2019 (the crack only), + /// for everyone around, the digger included (`levelEvent(null, ...)`). + fn destroy_progress_event(&mut self, pos: [i32; 3], face: [i32; 3], ticks: u32) { + let id = if ticks.is_multiple_of(4) { 2020 } else { 2019 }; + let direction = horizon_core::geometry::Direction::ALL + .iter() + .position(|d| d.normal() == face) + .unwrap_or(1); + self.level_event_at(id, pos, direction as i32); + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; @@ -4085,6 +4106,11 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let facts = self.res.facts().get(state); if facts.hardness < 0.0 { + // The server still counts its destroy ticks on an unbreakable block. + let m = self.mining.as_mut().ok_or("mining")?; + m.ticks += 1; + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); return Ok(()); } // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. @@ -4115,26 +4141,15 @@ impl Game<'_> { } else { speed / facts.hardness / if harvest { 30.0 } else { 100.0 } }; - let hit_sound = facts.sounds.clone(); self.swing_arm(); let m = self.mining.as_mut().ok_or("mining")?; m.progress += progress; m.ticks += 1; - let crack = (m.pos, hit.face); - if m.ticks % 4 == 1 { - let c = [ - f64::from(m.pos[0]) + 0.5, - f64::from(m.pos[1]) + 0.5, - f64::from(m.pos[2]) + 0.5, - ]; - self.audio.play( - &hit_sound.hit, - Some(c), - (hit_sound.volume + 1.0) / 8.0, - hit_sound.pitch * 0.5, - ); + // An instant break at START sends no destroy events. + if m.progress < 1.0 || m.ticks > 1 { + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); } - self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..3a172073d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1188,8 +1188,9 @@ impl Game<'_> { horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { // The acting guest does not predict the egg's teleport // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + // (these levelEvent calls name no excluded player), nor + // the digger's own crack and hit sound (2019, 2020). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 2019 | 2020) { None } else { self.lan_acting diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..69fbcfc2e 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -134,6 +134,30 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `ClientLevel.addBreakingBlockEffects`: the block's hit sound (only for + /// `play_sound`) and one crumb on the face being mined; nothing for air. + pub(super) fn breaking_block_effects( + &mut self, + pos: [i32; 3], + face: [i32; 3], + play_sound: bool, + ) { + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().is_air(state) { + return; + } + if play_sound { + let sounds = self.res.facts().get(state).sounds.clone(); + // Each guest plays it from the level event itself. + self.audio.play_unshared( + &sounds.hit, + Some(pos.map(|v| f64::from(v) + 0.5)), + (sounds.volume + 1.0) / 8.0, + sounds.pitch * 0.5, + ); + } + self.crack_particle(pos, face, state); + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..1cc659cc0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3866,6 +3866,9 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); } + // startDestroyBlock plays the first hit and crack itself; the + // server's level events 2019 and 2020 do the rest. + self.breaking_block_effects(hit.pos, hit.face, true); self.mining = Some(Mining { pos: hit.pos, progress: 0.0, @@ -3878,20 +3881,6 @@ impl Game<'_> { }; let done = done + progress; let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; - if ticks % 4 == 1 { - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - &facts.sounds.hit, - Some(c), - (facts.sounds.volume + 1.0) / 8.0, - facts.sounds.pitch * 0.5, - ); - } - self.crack_particle(pos, hit.face, state); if done >= 1.0 { let seq = self.next_sequence(); self.predict_break(pos, state, seq); From 0c127ec1d9285a225d0cee0f29755b8f8fcaff8b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:23:34 +0100 Subject: [PATCH 14/65] Stub breaking_block_effects in the remote mining test fixture --- tests/test_remote_mining.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 9feb255fa..4c77f989d 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -90,6 +90,7 @@ impl Game { fn predict_break(&mut self, pos: [i32; 3], _: u32, _: i32) { self.world.broken.push(pos); } fn send(&mut self, S::PlayerAction(packet): S) { self.packets.push(packet); } fn crack_particle(&mut self, _: [i32; 3], _: u8, _: u32) {} + fn breaking_block_effects(&mut self, _: [i32; 3], _: u8, _: bool) {} METHOD } fn main() { From 766bfbcdfa6d602518e0fe70657092c54f63b692 Mon Sep 17 00:00:00 2001 From: mahirsn Date: Mon, 26 Oct 2026 21:13:00 +0300 Subject: [PATCH 15/65] fix(client): answer the server's held slot like vanilla ClientboundSetHeldSlotPacket only changes the selected hotbar slot (and ignores slots outside the hotbar), so the next tick sends ServerboundSetCarriedItemPacket as vanilla does. Each login starts again from slot 0, as handleLogin's new MultiPlayerGameMode and LocalPlayer do. --- crates/horizon-client/src/game/remote.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..d53420db9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1619,7 +1619,11 @@ impl Game<'_> { } C::Login(p) => { self.level.hardcore = p.hardcore; + // handleLogin makes a new MultiPlayerGameMode (carried index 0) and a + // new LocalPlayer (slot 0). + self.selected = 0; if let Some(r) = self.remote.as_mut() { + r.carried = Some(0); r.online_mode = p.online_mode; r.entity_id = p.player_id; r.view_distance = p.chunk_radius; @@ -2295,10 +2299,11 @@ impl Game<'_> { } self.apply_remote_abilities(); } + // ClientPacketListener.handleSetHeldSlot: a hotbar slot only, and the + // carried index stays, so the next tick answers with SetCarriedItem. C::SetHeldSlot(p) => { - self.selected = p.slot.clamp(0, 8) as usize; - if let Some(r) = self.remote.as_mut() { - r.carried = Some(self.selected); + if (0..9).contains(&p.slot) { + self.selected = p.slot as usize; } } C::ContainerSetContent(p) => { From ae3737b1c279efb2acb3092f04d6711820c2de61 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:34:08 +0100 Subject: [PATCH 16/65] Mod API: render.set-far-terrain, and the official Far View mod A mod can now turn on the game's distant terrain (LOD) with render.set-far-terrain: a distance of 64 to 1024 chunks and Far Detail's Reduced. The game builds and draws the tiles as it does for the LOD Distance setting, which wins while it is on. One far terrain shows at a time, the first loaded mod's. API level 4. mods/official/far-view is the official mod on it: Distance (256 chunks by default) and Far detail on its settings page, kept in its storage. --- Cargo.lock | 7 ++ Cargo.toml | 2 +- crates/horizon-client/src/game.rs | 34 +++++-- crates/horizon-client/src/game/mod_input.rs | 18 ++++ crates/horizon-client/src/graphics.rs | 16 ++-- crates/horizon-mod-sdk/wit/horizon.wit | 17 ++++ crates/horizon-mods/src/api_level.rs | 5 +- crates/horizon-mods/src/runtime.rs | 25 +++++- crates/horizon-mods/tests/sandbox.rs | 17 +++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 10 +++ docs/api/mods-reference.md | 8 ++ docs/api/stability.md | 7 +- docs/graphics.md | 2 +- docs/mods.md | 5 +- mods/official/far-view/Cargo.toml | 16 ++++ mods/official/far-view/horizon-mod.toml | 9 ++ mods/official/far-view/src/lib.rs | 89 +++++++++++++++++++ 17 files changed, 261 insertions(+), 26 deletions(-) create mode 100644 mods/official/far-view/Cargo.toml create mode 100644 mods/official/far-view/horizon-mod.toml create mode 100644 mods/official/far-view/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 809df3a5a..a17262571 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -923,6 +923,13 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "far-view" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "fdeflate" version = "0.3.7" diff --git a/Cargo.toml b/Cargo.toml index 59bfe5e33..a669fb489 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-hdr", "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", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "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", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/far-view", "mods/official/minimap", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d00c7710c..1e4e93d3b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11208,11 +11208,28 @@ impl Game<'_> { } Ok(()) } - /// LOD Distance as far terrain uses it (`Graphics::lod_distance_on`). + /// LOD Distance and Far Detail Reduced as chosen: the player's LOD + /// Distance when it is on, else a mod's far terrain + /// (`render.set-far-terrain`). + fn far_terrain_choice(&self) -> (u32, bool) { + let g = &self.settings.horizon; + let reduced = g.far_detail == horizon_client::graphics::FarDetail::Reduced; + if g.lod_distance > 0 { + return (g.lod_distance, reduced); + } + match self.mod_far_terrain() { + Some(f) => (f.distance, reduced || f.reduced), + None => (0, reduced), + } + } + /// LOD Distance as far terrain uses it (`graphics::lod_distance_capped`). fn lod_distance(&self) -> u32 { + let (distance, _) = self.far_terrain_choice(); match &self.renderer { - Some(renderer) => self.settings.horizon.lod_distance_on(&renderer.info), - None => self.settings.horizon.lod_distance.min(1024), + Some(renderer) => { + horizon_client::graphics::lod_distance_capped(distance, &renderer.info) + } + None => distance.min(1024), } } /// Only enabled LOD worlds extend the renderer's range, never simulation. @@ -11233,7 +11250,7 @@ impl Game<'_> { } } fn prepare_lod(&mut self) { - let enabled = self.settings.horizon.lod_distance > 0 + let enabled = self.far_terrain_choice().0 > 0 && self.renderer.is_some() && self.player.is_some() && self.title.is_none() @@ -11330,6 +11347,7 @@ impl Game<'_> { { log::warn!("Horizon: failed to save unloaded chunks: {e}"); } + let (far_distance, far_reduced) = self.far_terrain_choice(); if let Some(renderer) = self.renderer.as_mut() { let g = &self.settings.horizon; let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0; @@ -11383,12 +11401,10 @@ impl Game<'_> { } renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z))); if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { - let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info); + let lod_distance = + horizon_client::graphics::lod_distance_capped(far_distance, &renderer.info); lod.set_near_loading(self.streaming.busy()); - lod.set_reduced_detail( - self.settings.horizon.far_detail - == horizon_client::graphics::FarDetail::Reduced, - ); + lod.set_reduced_detail(far_reduced); // The covered columns change only with the complete ones and // the render area: rebuilt then, not every frame. let at = ( diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 10faf6a81..467ea1cc0 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -31,6 +31,9 @@ impl Game<'_> { pub(super) fn mod_minimap(&self) -> Option { None } + pub(super) fn mod_far_terrain(&self) -> Option { + None + } } /// A mod's zoom (`render.set-zoom`), clamped by the runtime. @@ -51,6 +54,13 @@ pub(super) struct ModMinimap { pub(super) round: bool, } +/// A mod's far terrain (`render.set-far-terrain`), clamped by the runtime. +#[derive(Clone, Copy)] +pub(super) struct ModFarTerrain { + pub(super) distance: u32, + pub(super) reduced: bool, +} + #[cfg(feature = "mods")] impl Game<'_> { /// The main hand's stack as `input` shows it; none when it is empty. @@ -178,4 +188,12 @@ impl Game<'_> { round: m.round, }) } + /// The far terrain the first mod drawing one asks for. + pub(super) fn mod_far_terrain(&self) -> Option { + let f = self.mods.mods.far_terrain()?; + Some(ModFarTerrain { + distance: f.distance, + reduced: f.reduced, + }) + } } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 4f6f04bc0..edef7c3bc 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -216,15 +216,19 @@ pub const INTEGRATED_LOD_DISTANCE: u32 = 128; pub fn lod_capped(info: &wgpu::AdapterInfo) -> bool { info.device_type == wgpu::DeviceType::IntegratedGpu && !info.name.starts_with("Apple") } +/// A LOD distance as far terrain uses it on this adapter. +pub fn lod_distance_capped(distance: u32, info: &wgpu::AdapterInfo) -> u32 { + let distance = distance.min(1024); + if lod_capped(info) { + distance.min(INTEGRATED_LOD_DISTANCE) + } else { + distance + } +} impl Graphics { /// `lod_distance` as far terrain uses it on this adapter. pub fn lod_distance_on(&self, info: &wgpu::AdapterInfo) -> u32 { - let distance = self.lod_distance.min(1024); - if lod_capped(info) { - distance.min(INTEGRATED_LOD_DISTANCE) - } else { - distance - } + lod_distance_capped(self.lod_distance, info) } } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index d9bb9f5c2..9c9fc1574 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -412,6 +412,23 @@ interface render { /// own frame budget; hidden, they are dropped. One map shows at a time: /// the first loaded mod's. set-minimap: func(minimap: option); + record far-terrain { + /// How far the distant terrain reaches, in chunks: 64 to 1024. On + /// integrated graphics other than Apple's the game caps it lower. + distance: u32, + /// Coarser far tiles, as the Far Detail setting's Reduced: 2 to 4 ms + /// less GPU time per frame on integrated graphics. + reduced: bool, + } + /// Draws the world beyond the render distance as distant terrain, out to + /// `distance` chunks, until the next call (none ends it). The game builds + /// it on its own workers, from the chunks already loaded or saved and, + /// where nobody has been, from the world's generator; the simulation + /// distance doesn't change. Only worlds whose generator the game has + /// (single player and a LAN world you host) show it. The player's own LOD + /// Distance setting, when on, wins. One far terrain shows at a time: the + /// first loaded mod's. + set-far-terrain: func(far-terrain: option); } /// What the game calls. Only the hooks `init` asks for are ever called. diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index bf87d0cfa..a20a413c5 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 3; +pub const LEVEL: u32 = 4; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 34] = [ +pub const FUNCTIONS: [(&str, u32); 35] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -48,6 +48,7 @@ pub const FUNCTIONS: [(&str, u32); 34] = [ ("players.broadcast", 1), ("game.raycast", 2), ("command.run-quiet", 3), + ("render.set-far-terrain", 4), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ce48f2317..ead43a8f2 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -73,9 +73,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, Minimap as ModMinimap, - Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, TextShape, - Zoom as ModZoom, + Corner as RenderCorner, FarTerrain as ModFarTerrain, 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}; @@ -297,6 +297,8 @@ struct State { zoom: Option, /// Capability `render`'s minimap, when the mod shows one. minimap: Option, + /// Capability `render`'s far terrain, when the mod draws one. + far_terrain: Option, input: InputState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, @@ -460,6 +462,7 @@ impl Mods { corner: None, zoom: None, minimap: None, + far_terrain: None, input: InputState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, @@ -924,6 +927,12 @@ impl Mods { .iter() .find_map(|e| e.run.as_ref()?.store.data().minimap) } + /// The far terrain the first running mod draws (capability `render`). + pub fn far_terrain(&self) -> Option { + self.entries + .iter() + .find_map(|e| e.run.as_ref()?.store.data().far_terrain) + } fn inputs(&self) -> impl Iterator { self.entries .iter() @@ -1292,6 +1301,8 @@ 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); +/// `set-far-terrain`'s distance in chunks, as the LOD Distance setting's. +const FAR_TERRAIN_DISTANCE: (u32, u32) = (64, 1024); /// A mod's corner panel: shapes in a `width` × `height` box the game /// places in `corner`, stacked with the other overlays. @@ -1381,6 +1392,14 @@ impl render::Host for State { ..m }); } + fn set_far_terrain(&mut self, far_terrain: Option) { + self.far_terrain = far_terrain.map(|f| ModFarTerrain { + distance: f + .distance + .clamp(FAR_TERRAIN_DISTANCE.0, FAR_TERRAIN_DISTANCE.1), + ..f + }); + } fn frame_stats(&mut self) -> FrameRate { let (fps, min, low) = self.snapshot.frame; FrameRate { fps, min, low } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index c6b835f10..701968781 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -252,7 +252,7 @@ experimental = ["ui", "render", "input"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest shows a minimap (`render.set-minimap`). + // The UI guest draws far terrain (`render.set-far-terrain`). assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); } @@ -722,6 +722,21 @@ fn render_minimap_is_clamped_and_hidden() { assert_eq!(map(&mut mods, "off"), None); } +#[test] +fn render_far_terrain_is_clamped_and_ended() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let far = |mods: &mut Mods, args: &str| { + assert!(mods.command(&format!("far_terrain {args}"))); + mods.far_terrain().map(|f| (f.distance, f.reduced)) + }; + assert!(mods.far_terrain().is_none()); + assert_eq!(far(&mut mods, "256 1"), Some((256, true))); + // The distance is clamped to LOD Distance's 64 to 1024 chunks. + assert_eq!(far(&mut mods, "8 0"), Some((64, false))); + assert_eq!(far(&mut mods, "99999 0"), Some((1024, false))); + assert_eq!(far(&mut mods, "off"), None); +} + /// `game.raycast`: the view's hit the game worked out, up to the distance /// asked for; the game works it out only while a mod imports the call. #[test] diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 74fb64350..f3ab0f6af 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -99,6 +99,7 @@ impl Mod for Guest { "input_wheel", "zoom", "minimap", + "far_terrain", "raycast", "quiet", "quiet_many", @@ -222,6 +223,15 @@ impl Mod for Guest { }); render::set_minimap(map); } + // `far_terrain off`, or `far_terrain DISTANCE REDUCED`. + "far_terrain" => { + let words: Vec<&str> = args.split(' ').collect(); + let far = (args != "off").then(|| render::FarTerrain { + distance: words.first().and_then(|w| w.parse().ok()).unwrap_or(0), + reduced: words.get(1) == Some(&"1"), + }); + render::set_far_terrain(far); + } "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), "quiet_many" => { let n: usize = args.parse().unwrap_or(0); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index c44f27576..c9409b7e4 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -426,6 +426,13 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `rotate` | `bool` | 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. | | `round` | `bool` | Round, the corners left clear; otherwise square. | +### record `far-terrain` + +| Field | Type | | +| --- | --- | --- | +| `distance` | `u32` | How far the distant terrain reaches, in chunks: 64 to 1024. On integrated graphics other than Apple's the game caps it lower. | +| `reduced` | `bool` | Coarser far tiles, as the Far Detail setting's Reduced: 2 to 4 ms less GPU time per frame on integrated graphics. | + | Function | Signature | What it does | | --- | --- | --- | | `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | @@ -437,6 +444,7 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `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. | +| `set-far-terrain` | `func(far-terrain: option)` | Draws the world beyond the render distance as distant terrain, out to `distance` chunks, until the next call (none ends it). The game builds it on its own workers, from the chunks already loaded or saved and, where nobody has been, from the world's generator; the simulation distance doesn't change. Only worlds whose generator the game has (single player and a LAN world you host) show it. The player's own LOD Distance setting, when on, wins. One far terrain shows at a time: the first loaded mod's. | ## `events` diff --git a/docs/api/stability.md b/docs/api/stability.md index df2c1aeb3..f65bafa55 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 `render.set-far-terrain`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: @@ -134,3 +134,8 @@ Deprecations and breaking changes are in bold. The release notes of the game rel 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. +- **`render.set-far-terrain`** turns on the game's own distant terrain, not one a mod builds: sampling the generator + and meshing thousands of far tiles runs on the game's workers within its frame and upload budgets, which no hook + call could match. The mod picks the distance (64 to 1024 chunks, capped lower on integrated graphics as LOD Distance + is) and Far Detail's Reduced. The player's own LOD Distance, when on, wins; one far terrain shows at a time, the + first loaded mod's. diff --git a/docs/graphics.md b/docs/graphics.md index dcba29773..bebd8a7f6 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -47,7 +47,7 @@ Coverage and detail improve progressively; a large selected radius does not mean Ordinary Overworld atmospheric fog extends with the selected LOD distance. Fog Off disables distance haze at large ranges too; fluid, darkness and boss fog retain their limits. -The setting is stored as `lodDistance` in `horizon-graphics.txt`; `0` disables it. Existing `renderDistance` in `options.txt` keeps its normal meaning for full chunks. +The setting is stored as `lodDistance` in `horizon-graphics.txt`; `0` disables it. The official Far View mod (`mods/official/far-view`, [mods.md](mods.md)) turns the same distant terrain on from the mod browser, with its own distance and detail; the setting, when on, wins. Existing `renderDistance` in `options.txt` keeps its normal meaning for full chunks. Not implemented: anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless). diff --git a/docs/mods.md b/docs/mods.md index a68b6d123..3e4fcc53c 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | -| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap | +| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap; Far View (`far-view`), distant terrain | | Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model | | 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 | @@ -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. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | | `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); `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"]` | +| `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); `set-far-terrain(far-terrain)`: the world past the render distance as distant terrain, out to 64 to 1024 chunks, built by the game's own workers (the player's LOD Distance, when on, wins; 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 | @@ -569,6 +569,7 @@ so the same rustc and `Cargo.lock` give the same file. | 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`) | +| Far View | `far_view` | Graphics > LOD Distance and Far Detail | `distance` (chunks): `64`, `128`, `256` (default), `512`, `1024`; `detail`: `full` (default), `reduced`. The game builds and draws the distant terrain (`render.set-far-terrain`); the player's LOD Distance, when on, wins | ## Versions and compatibility diff --git a/mods/official/far-view/Cargo.toml b/mods/official/far-view/Cargo.toml new file mode 100644 index 000000000..965ee0bb4 --- /dev/null +++ b/mods/official/far-view/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "far-view" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official far view: distant terrain past the render distance." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/far-view/horizon-mod.toml b/mods/official/far-view/horizon-mod.toml new file mode 100644 index 000000000..5070f897c --- /dev/null +++ b/mods/official/far-view/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "far_view" +name = "Far View" +version = "1.0.0" +description = "See much farther: the world past your render distance drawn as simplified distant terrain, out to 1024 chunks, without loading or simulating more chunks." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["render", "ui", "storage"] +experimental = ["render", "ui"] diff --git a/mods/official/far-view/src/lib.rs b/mods/official/far-view/src/lib.rs new file mode 100644 index 000000000..e5b92e590 --- /dev/null +++ b/mods/official/far-view/src/lib.rs @@ -0,0 +1,89 @@ +//! Horizon's official far view: the world past the render distance drawn as +//! distant terrain (`render.set-far-terrain`; the game builds the tiles on +//! its own workers). Its settings page picks how far it reaches and the far +//! tiles' detail, kept in the mod's storage (`distance`, `detail`). The +//! player's own LOD Distance setting, when on, wins over the mod. +use horizon_mod_sdk::{ + Mod, Registration, + render::{self, FarTerrain}, + storage, + ui::{self, ButtonWidget, Widget}, +}; + +/// Distances in chunks, as LOD Distance offers them. +const DISTANCES: [u32; 5] = [64, 128, 256, 512, 1024]; +/// Settings page buttons. +const DISTANCE_BUTTON: u32 = 1; +const DETAIL_BUTTON: u32 = 2; + +/// An index into [`DISTANCES`] and Far Detail's Reduced. +struct FarView { + distance: usize, + reduced: bool, +} + +impl FarView { + fn show(&self) { + render::set_far_terrain(Some(FarTerrain { + distance: DISTANCES[self.distance], + reduced: self.reduced, + })); + } + fn page(&self) { + let button = |id, label: String| Widget::Button(ButtonWidget { id, label }); + ui::set_settings(&[ + button( + DISTANCE_BUTTON, + format!("Distance: {} chunks", DISTANCES[self.distance]), + ), + button( + DETAIL_BUTTON, + format!( + "Far detail: {}", + if self.reduced { "Reduced" } else { "Full" } + ), + ), + ]); + } + fn save(&self) { + let _ = storage::set("distance", DISTANCES[self.distance].to_string().as_bytes()); + let _ = storage::set("detail", if self.reduced { b"reduced" } else { b"full" }); + } +} + +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 FarView { + fn init() -> Result<(Self, Registration), String> { + // 256 chunks and full detail, as the docs suggest; an unknown value + // keeps the default. + let far = FarView { + distance: stored("distance") + .and_then(|v| DISTANCES.iter().position(|d| d.to_string() == v)) + .unwrap_or(2), + reduced: stored("detail").as_deref() == Some("reduced"), + }; + far.show(); + far.page(); + Ok((far, Registration::new())) + } + fn ui_select(&mut self, id: u32, _row: u32) { + match id { + DISTANCE_BUTTON => self.distance = (self.distance + 1) % DISTANCES.len(), + DETAIL_BUTTON => self.reduced = !self.reduced, + _ => return, + } + self.save(); + self.show(); + self.page(); + } + fn ui_settings_opened(&mut self) { + self.page(); + } +} + +horizon_mod_sdk::export_mod!(FarView); From 6c716f457b7609e96bf6bc1642d0917cb615c1e4 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 21:16:23 +0100 Subject: [PATCH 17/65] Mobs: farm animals and frogs keep their variant; sound variants are saved finalizeSpawn picks the variant of a pig, cow, chicken or frog and the sound variant of a pig, cow, chicken, cat or wolf, but the save wrote neither for these: pigs, cows, chickens and frogs came back temperate after a reload, and every cat and wolf was saved with the classic sounds whatever it rolled. Chickens also lost their egg timer. Every mob with a variant component now saves and loads `variant` through finalize::species_variant_component / variant_index (the cat and wolf code used its own copy). The sound variant is kept as an index into the species' registry (None is the default, classic) and is saved and read back; Chicken also saves `EggLayTime`. Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/finalize_spawn_fixture.rs | 8 +- crates/horizon-client/src/entity_nbt.rs | 125 ++++++++++++++---- crates/horizon-client/src/mobs.rs | 5 +- crates/horizon-client/src/mobs/finalize.rs | 13 +- 4 files changed, 120 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index b1b25e723..067d545a8 100644 --- a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -154,11 +154,11 @@ const MEMORIES: [&str; 7] = [ fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { use Species as S; let s = m.species(); - let named = |reg: &finalize::VariantRegistry, i: u8| { - format!( - "minecraft:{}", + let named = |reg: &finalize::VariantRegistry, i: Option| { + let name = i.map_or("classic", |i| { reg.names.get(i as usize).map_or("?", |n| n.as_str()) - ) + }); + format!("minecraft:{name}") }; let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant)); match s { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 161ca12e9..8926b3bbe 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -225,6 +225,24 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { if is_animal(id) { map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); } + let species = m.species(); + if let Some((_, variant)) = + crate::mobs::finalize::species_variant_component(species, m.extra.variant) + { + map.insert("variant".into(), string(&variant)); + } + if species == crate::mobs::Species::Chicken { + map.insert("EggLayTime".into(), Tag::Int(m.extra.egg_time)); + } + let sounds = crate::mobs::finalize::sound_variants(species); + if !sounds.is_empty() { + let sound = m.extra.sound_variant.and_then(|i| sounds.get(i as usize)); + let sound = sound.copied().unwrap_or("classic"); + map.insert( + "sound_variant".into(), + string(&format!("minecraft:{sound}")), + ); + } match id { "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { @@ -241,10 +259,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::CAT_VARIANTS[(m.extra.variant as usize).min(10)]; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:wolf" => { if let Some(owner) = m.extra.owner { @@ -254,10 +268,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::WOLF_VARIANTS[(m.extra.variant as usize).min(8)].0; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { map.insert( @@ -793,20 +803,27 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.vector[0] = 0.7; } } + if crate::mobs::finalize::species_variant_component(m.species(), 0).is_some() + && let Some(v) = text(tag.get("variant")) + { + m.extra.variant = crate::mobs::finalize::variant_index(m.species(), &v); + } + if m.species() == crate::mobs::Species::Chicken + && let Some(t) = number(tag.get("EggLayTime")) + { + m.extra.egg_time = t as i32; + } + if let Some(v) = text(tag.get("sound_variant")) { + let v = v.trim_start_matches("minecraft:"); + let sounds = crate::mobs::finalize::sound_variants(m.species()); + m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8); + } if m.species() == crate::mobs::Species::Cat { m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); m.extra.tame = m.extra.owner.is_some(); m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::CAT_VARIANTS - .iter() - .position(|n| *n == v) - .unwrap_or(0) as u8; - } } if m.species() == crate::mobs::Species::Wolf { let health = m.health; @@ -817,14 +834,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::WOLF_VARIANTS - .iter() - .position(|(n, _)| *n == v) - .unwrap_or(0) as u8; - } } if matches!( m.species(), @@ -2425,6 +2434,74 @@ mod sheep_nbt_tests { let back = mob_from_nbt(&tag, &types, 2).unwrap(); assert_eq!((back.extra.color, back.extra.sheared), (14, true)); } + + #[test] + fn farm_animals_keep_their_variant_and_sound_variant() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let mut m = Mob::new( + 1, + types["minecraft:pig"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!( + text(tag.get("variant")).as_deref(), + Some("minecraft:temperate") + ); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:classic") + ); + // Spawned in a warm biome with the mini sounds. + (m.extra.variant, m.extra.sound_variant) = (1, Some(2)); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:warm")); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:mini") + ); + let back = mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!((back.extra.variant, back.extra.sound_variant), (1, Some(2))); + let mut hen = Mob::new( + 3, + types["minecraft:chicken"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + (hen.extra.variant, hen.extra.egg_time) = (2, 7795); + let tag = mob_to_nbt(&hen, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:cold")); + let back = mob_from_nbt(&tag, &types, 4).unwrap(); + assert_eq!((back.extra.variant, back.extra.egg_time), (2, 7795)); + // The sound variants are indices into the registries finalizeSpawn draws from. + use crate::mobs::{Species, finalize}; + let registries = finalize::SpawnRegistries::load(&root); + for (species, registry) in [ + (Species::Pig, ®istries.pig_sound), + (Species::Cow, ®istries.cow_sound), + (Species::Chicken, ®istries.chicken_sound), + (Species::Cat, ®istries.cat_sound), + (Species::Wolf, ®istries.wolf_sound), + ] { + assert_eq!( + finalize::sound_variants(species), + registry.names, + "{species:?}" + ); + } + } } #[cfg(test)] diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f4086216d..9933f2a4e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -763,8 +763,9 @@ pub struct Extra { pub drop_chances: Option>, /// `Mob.leftHanded`. pub left_handed: bool, - /// The sound variant: index in the species' `*_sound_variant` registry. - pub sound_variant: u8, + /// The sound variant: index in the species' `*_sound_variant` registry + /// (`finalize::sound_variants`); None is the default, `classic`. + pub sound_variant: Option, /// `Zombie.canBreakDoors`. pub can_break_doors: bool, /// A goat's `IsScreamingGoat` and the horns it lost (left, right). diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 6e5daff1f..ccf4564ca 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1508,7 +1508,7 @@ impl Ctx<'_, L, R> { } fn sound(&mut self, m: &mut Mob, registry: fn(&SpawnRegistries) -> &VariantRegistry) { let r = registry(self.data.registries); - m.extra.sound_variant = r.random(self.random) as u8; + m.extra.sound_variant = Some(r.random(self.random) as u8); } /// `finalizeSpawn` of the mob's class. @@ -2014,6 +2014,17 @@ pub fn species_variant_component(s: Species, variant: u8) -> Option<(&'static st }; Some((component, format!("minecraft:{}", variant_name(s, variant)))) } +/// The `*_sound_variant` registry of a species, in registry order. +pub fn sound_variants(s: Species) -> &'static [&'static str] { + match s { + Species::Pig => &["big", "classic", "mini"], + Species::Cow => &["classic", "moody"], + Species::Chicken => &["classic", "picky"], + Species::Cat => &["classic", "royal"], + Species::Wolf => &["angry", "big", "classic", "cute", "grumpy", "puglin", "sad"], + _ => &[], + } +} /// The registry name of the game's variant index. pub fn variant_name(s: Species, index: u8) -> &'static str { let i = index as usize; From a55c82546773cc719e2e8dd291476c87be1b7686 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 21:46:35 +0100 Subject: [PATCH 18/65] Minecarts save HasTicked and Fire 0 AbstractMinecart saves Entity.firstTick as HasTicked, and a cart's fire stays 0: Entity.move sets it to -getFireImmuneTicks(), which is 0 for everything but players. A mineshaft's chest minecart was saved without HasTicked and with Fire -1; vanilla's generated chunk saves it with HasTicked 1 and Fire 0, and a cart that has ticked with HasTicked 0 and Fire 0. The mineshaft writes both as the proto chunk saves a new cart, and a cart keeps first_tick from its save until its first tick. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/minecarts.rs | 35 +++++++++++++++++++ .../src/worldgen/structure/mineshaft.rs | 3 ++ 2 files changed, 38 insertions(+) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..dcb5421e2 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -90,6 +90,8 @@ pub(super) struct Minecart { /// Chest minecarts: the loot table rolled into `items` on load, saved /// again while the items are still that roll. pub loot: Option, + /// `Entity.firstTick`: not ticked yet (saved as `HasTicked`). + pub first_tick: bool, } pub(super) const WIDTH: f64 = 0.98; pub(super) const HEIGHT: f64 = 0.7; @@ -186,6 +188,7 @@ impl Minecart { fuse: -1, enabled: true, loot: None, + first_tick: true, } } pub fn bounds(&self) -> Aabb { @@ -536,6 +539,7 @@ impl Game<'_> { } /// `AbstractMinecart.tick` for one cart; returns false once it is gone. fn tick_cart(&mut self, c: &mut Minecart, intent: [f64; 2]) -> bool { + c.first_tick = false; c.previous = c.position; c.previous_yaw = c.yaw; c.hurt_time = (c.hurt_time - 1).max(0); @@ -1509,6 +1513,10 @@ impl Minecart { map.insert(JavaString::from(k), v); }; put("FlippedRotation", Tag::Byte(i8::from(self.flipped))); + // AbstractMinecart saves firstTick as HasTicked. A cart never burns: + // Entity.move sets -getFireImmuneTicks(), 0 for all but players. + put("HasTicked", Tag::Byte(i8::from(self.first_tick))); + put("Fire", Tag::Short(0)); match self.kind { CartKind::Chest | CartKind::Hopper => { put("Items", horizon_client::save::encode_items(&self.items)); @@ -1558,6 +1566,7 @@ impl Minecart { _ => 0.0, }; c.flipped = int("FlippedRotation").unwrap_or(0) != 0; + c.first_tick = int("HasTicked").unwrap_or(0) != 0; if kind.slots() > 0 { c.items = horizon_client::save::decode_items(tag.get("Items"), kind.slots()); } @@ -1582,4 +1591,30 @@ mod tests { assert_eq!(display_offset(CartKind::CommandBlock), 6.0); assert_eq!(display_offset(CartKind::Rideable), 6.0); } + + #[test] + fn a_cart_saves_as_never_ticked_until_it_ticks() { + use horizon_world::nbt::Tag; + let generated = Tag::compound([ + ("id", Tag::String("minecraft:chest_minecart".into())), + ( + "Pos", + Tag::List( + [0.5f64, 40.5, 0.5] + .map(|v| Tag::Double(v.to_bits())) + .to_vec(), + ), + ), + ("HasTicked", Tag::Byte(1)), + ("Fire", Tag::Short(0)), + ]); + let mut cart = Minecart::from_nbt(&generated, 1, CartKind::Chest).unwrap(); + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(1))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + cart.first_tick = false; + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(0))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + } } diff --git a/crates/horizon-world/src/worldgen/structure/mineshaft.rs b/crates/horizon-world/src/worldgen/structure/mineshaft.rs index 0c2d32c08..082afd0cd 100644 --- a/crates/horizon-world/src/worldgen/structure/mineshaft.rs +++ b/crates/horizon-world/src/worldgen/structure/mineshaft.rs @@ -616,6 +616,9 @@ impl MineshaftPiece { // A chest minecart with the mineshaft loot table. let seed = c.random.long(); let mut nbt = super::legacy::spawn_nbt("minecraft:chest_minecart", pos, false, false); + // As the proto chunk saves the new cart: not ticked, not burning. + nbt.insert("HasTicked".into(), Tag::Byte(1)); + nbt.insert("Fire".into(), Tag::Short(0)); let p = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, From faeff96cf939e46bfb587ab41ec95ee988240919 Mon Sep 17 00:00:00 2001 From: Murillo Deolino <88172584+Murilinho145SG@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:59:32 -0300 Subject: [PATCH 19/65] Add Wayland launcher window controls Co-Authored-By: Codex --- launcher/src/main.rs | 15 ++- launcher/src/titlebar.rs | 236 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 240 insertions(+), 11 deletions(-) diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 50e62756d..75cf1ddfe 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1369,9 +1369,9 @@ fn megabytes(bytes: u64) -> String { // ----- Pages ------------------------------------------------------------------------------------- impl Launcher { - /// The top bar: the mark and the name over the sidebar (in the title bar on Windows), the - /// pages with their icons, then the account playing and the Settings button. - fn topbar(&mut self, cx: &mut Context) -> Div { + /// The top bar: the mark and name over the sidebar (in the title bar on Windows and Linux + /// client-side decorations), the pages with their icons, then the account and Settings. + fn topbar(&mut self, window: &Window, cx: &mut Context) -> Div { let t = self.theme; let mut nav = div().flex().flex_none().h_full().gap(px(2.)); for (page, label, icon) in Page::ALL { @@ -1508,8 +1508,8 @@ impl Launcher { .bg(t.side) .border_b_2() .border_color(t.outline) - // Where the title bar is drawn here (Windows), it carries the mark and the name. - .when(!titlebar::DRAWN, |bar| { + // Custom title bars carry the mark and name above the sidebar. + .when(!titlebar::draws_brand(window), |bar| { bar.child( div() .flex() @@ -3445,7 +3445,7 @@ impl Render for Launcher { window.focus(&self.root_focus); } let stone = self.art.stone(t.page_rgb, t.dark, window.scale_factor()); - let topbar = self.topbar(cx); + let topbar = self.topbar(window, cx); let sidebar = self.sidebar(cx); let mut root = div() .id("root") @@ -3586,6 +3586,7 @@ impl Render for Launcher { .bg(t.side) .children(titlebar::render(&t, window)) .child(root.flex_1().min_h_0()) + .children(titlebar::resize_handles(window)) } } @@ -3715,6 +3716,8 @@ fn main() { window_bounds: Some(WindowBounds::Windowed(bounds)), window_min_size: Some(size(px(960.), px(600.))), titlebar: Some(titlebar::options()), + #[cfg(target_os = "linux")] + window_decorations: Some(gpui::WindowDecorations::Client), app_id: Some("horizon-launcher".into()), ..Default::default() }, diff --git a/launcher/src/titlebar.rs b/launcher/src/titlebar.rs index a023f7d7d..dbf0f966e 100644 --- a/launcher/src/titlebar.rs +++ b/launcher/src/titlebar.rs @@ -1,12 +1,25 @@ -//! Custom Windows chrome. Other platforms keep their native window decorations; on macOS, -//! `apply_appearance` repaints that chrome (the title bar) to match the chosen look. +//! Window chrome: Windows and Linux client-side decorations are custom drawn; macOS and Linux +//! server-side decorations use the platform's native chrome. use crate::theme::Theme; use gpui::{Div, TitlebarOptions, Window}; use horizon_launcher::backend::Appearance; -/// Whether the launcher draws its own title bar (`render`) rather than the system. +/// Whether Windows uses a transparent native title bar for the launcher's custom chrome. pub const DRAWN: bool = cfg!(target_os = "windows"); +pub fn draws_brand(window: &Window) -> bool { + #[cfg(target_os = "linux")] + return matches!( + window.window_decorations(), + gpui::Decorations::Client { .. } + ); + #[cfg(not(target_os = "linux"))] + { + let _ = window; + DRAWN + } +} + pub fn options() -> TitlebarOptions { TitlebarOptions { title: Some("Horizon".into()), @@ -15,15 +28,228 @@ pub fn options() -> TitlebarOptions { } } -#[cfg(not(target_os = "windows"))] +#[cfg(all(not(target_os = "windows"), not(target_os = "linux")))] pub fn render(_theme: &Theme, _window: &Window) -> Option
{ None } +/// Draw the launcher's Linux title bar when the platform uses client-side decorations. +#[cfg(target_os = "linux")] +pub fn render(theme: &Theme, window: &Window) -> Option
{ + use crate::{blocks, mark}; + use gpui::{div, prelude::*, px, Decorations, FontWeight, MouseButton}; + + if matches!(window.window_decorations(), Decorations::Server) { + return None; + } + + let controls = window.window_controls(); + let drag = div() + .id("window-drag") + .flex() + .flex_1() + .h_full() + .items_center() + .gap(px(8.)) + .px(px(12.)) + .on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move()) + .child(mark(16., theme)) + .child(blocks::pixel(13., FontWeight::MEDIUM).child("Horizon")); + + let mut bar = div() + .flex() + .flex_none() + .items_center() + .h(px(32.)) + .bg(theme.side) + .text_color(theme.muted) + .border_b_1() + .border_color(theme.outline) + .child(drag); + + if controls.minimize { + let color = theme.ink_soft; + let hover = theme.raised; + bar = bar.child( + div() + .id("window-minimize") + .flex() + .flex_none() + .items_center() + .justify_center() + .w(px(46.)) + .h_full() + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .child(div().w(px(10.)).h(px(1.)).bg(color)) + .on_click(|_, window, _| window.minimize_window()), + ); + } + + if controls.maximize { + let color = theme.ink_soft; + let hover = theme.raised; + let maximized = window.is_maximized(); + let square = || { + div() + .absolute() + .size(px(10.)) + .border_1() + .border_color(color) + }; + let icon = div().relative().size(px(14.)); + let icon = if maximized { + icon.child( + div() + .absolute() + .left(px(4.)) + .top_0() + .size(px(10.)) + .border_t_1() + .border_r_1() + .border_color(color), + ) + .child(square().left(px(1.)).top(px(3.))) + } else { + icon.child(square().left(px(2.)).top(px(2.))) + }; + bar = bar.child( + div() + .id("window-maximize") + .flex() + .flex_none() + .items_center() + .justify_center() + .w(px(46.)) + .h_full() + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .child(icon) + .on_click(|_, window, _| window.zoom_window()), + ); + } + + let close_hover = theme.page; + let close_bg = theme.danger; + Some( + bar.child( + div() + .id("window-close") + .group("linux-window-close") + .flex() + .flex_none() + .items_center() + .justify_center() + .w(px(46.)) + .h_full() + .cursor_pointer() + .hover(move |style| style.bg(close_bg).text_color(close_hover)) + .child( + blocks::icon("close", 14., theme.ink_soft) + .group_hover("linux-window-close", move |style| { + style.text_color(close_hover) + }), + ) + .on_click(|_, window, _| window.remove_window()), + ), + ) +} + +#[cfg(target_os = "linux")] +pub fn resize_handles(window: &Window) -> Option
{ + use gpui::{div, prelude::*, px, CursorStyle, Decorations, MouseButton, ResizeEdge}; + + if matches!(window.window_decorations(), Decorations::Server) || window.is_maximized() { + return None; + } + + let handle = |id, edge, cursor| { + div() + .id(id) + .absolute() + .cursor(cursor) + .on_mouse_down(MouseButton::Left, move |_, window, _| { + window.start_window_resize(edge) + }) + }; + + Some( + div() + .absolute() + .size_full() + .child( + handle("resize-left", ResizeEdge::Left, CursorStyle::ResizeLeft) + .left_0() + .top(px(8.)) + .bottom(px(8.)) + .w(px(5.)), + ) + .child( + handle("resize-right", ResizeEdge::Right, CursorStyle::ResizeRight) + .right_0() + .top(px(8.)) + .bottom(px(8.)) + .w(px(5.)), + ) + .child( + handle("resize-bottom", ResizeEdge::Bottom, CursorStyle::ResizeDown) + .bottom_0() + .left(px(8.)) + .right(px(8.)) + .h(px(5.)), + ) + .child( + handle( + "resize-top-left", + ResizeEdge::TopLeft, + CursorStyle::ResizeUpLeftDownRight, + ) + .left_0() + .top_0() + .size(px(8.)), + ) + .child( + handle( + "resize-top-right", + ResizeEdge::TopRight, + CursorStyle::ResizeUpRightDownLeft, + ) + .right_0() + .top_0() + .size(px(8.)), + ) + .child( + handle( + "resize-bottom-left", + ResizeEdge::BottomLeft, + CursorStyle::ResizeUpRightDownLeft, + ) + .left_0() + .bottom_0() + .size(px(8.)), + ) + .child( + handle( + "resize-bottom-right", + ResizeEdge::BottomRight, + CursorStyle::ResizeUpLeftDownRight, + ) + .right_0() + .bottom_0() + .size(px(8.)), + ), + ) +} + +#[cfg(not(target_os = "linux"))] +pub fn resize_handles(_: &Window) -> Option
{ + None +} + /// macOS keeps the window's appearance on the system setting, so a launcher set to Dark still /// draws a light title bar on a light desktop. Pin the NSWindow's appearance to the choice /// instead (`theme::pinned_dark`: `System` clears the pin, handing the chrome back to the -/// system). Elsewhere the chrome is ours (Windows) or the system's (Linux). +/// system). Windows uses custom chrome; Linux draws it only when the compositor requests it. #[cfg(target_os = "macos")] pub fn apply_appearance(window: &Window, choice: Appearance) { use objc2_app_kit::{ From ef0714a99a7926bb218c4901c107c07701420e6e Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:22:24 +0500 Subject: [PATCH 20/65] Lock in the sprint state that outlives the sprint key Sprint is a state, not a held key: LocalPlayer.aiStep starts it with the sprint key and stops it only on a vanilla stop condition, so releasing the key keeps it while forward is held. The server-side overwrite that rewrote the flag from the held keys is gone, so the underwater swim, the sprint jump and the flight speed follow the state on main. This adds the end-to-end regression tests that were missing for those three paths: the swim speed with the key released, the jump impulse with the key released, and the flight speed that follows the sprint state and not the sprint key. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/motion.rs | 186 ++++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 234390e23..d4beee1ea 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -3944,4 +3944,190 @@ mod tests { "{walked} steps over {metres} step-metres" ); } + /// Vanilla sprint is a state, not a held key: `LocalPlayer.aiStep` starts + /// it with the sprint key and stops it only on a vanilla stop condition. + /// Releasing the key while swimming keeps the sprint and its swim speed. + #[test] + fn a_sprint_survives_the_sprint_key_coming_up_while_swimming() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + // The same swim with the sprint key held, and with the key released + // once the sprint has started: the speed must not change. + let mut swims = Vec::new(); + for release in [false, true] { + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + for x in 19..=21 { + for y in 4..=8 { + for z in 19..=31 { + scene.set(x, y, z, water).unwrap(); + } + } + } + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + let mut speed = Vec::new(); + for tick in 0..12 { + // The key comes up on the fourth tick, after the sprint has + // started and the player swims. + let keys = if release && tick >= 4 { + forward + } else { + sprinting + }; + w.controlled_simulation_tick(keys).unwrap(); + speed.push(w.player.velocity.z); + } + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in water" + ); + assert!(w.player.swimming, "a sprinting player in water swims"); + swims.push(speed); + } + assert_eq!( + swims[0], swims[1], + "the swim speed must not drop when the sprint key comes up" + ); + } + + /// Vanilla: `LivingEntity.jumpFromGround` adds its 0.2 forward impulse + /// while the sprint state holds, so a jump taken after the sprint key + /// comes up is still a sprint jump. + #[test] + fn a_sprint_jump_keeps_its_impulse_when_the_sprint_key_comes_up() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + for _ in 0..20 { + w.controlled_simulation_tick(sprinting).unwrap(); + } + assert!(w.player.ground.on_ground, "the player settles on the floor"); + assert!(w.player.sprinting, "the sprint key starts the sprint"); + let running = w.player.velocity.z; + // The sprint key comes up and the player jumps. + w.controlled_simulation_tick(crate::sprint::Keys { + jump: true, + ..forward + }) + .unwrap(); + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in the air" + ); + assert!( + w.player.velocity.z > running + 0.05, + "the sprint jump keeps its forward impulse: {:?} vs {running}", + w.player.velocity + ); + } + + /// Vanilla `Player.getFlyingSpeed`: a flying player moves at the ability + /// speed, doubled while the sprint state holds. The sprint key starts the + /// state; releasing it does not change the speed. + #[test] + fn the_flight_speed_follows_the_sprint_state_not_the_sprint_key() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.player.may_fly = true; + w.player.flying = true; + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + assert_eq!( + w.flying_speed().unwrap(), + 0.05, + "a flying player without a sprint moves at the ability speed" + ); + // The sprint key starts the sprint, and the state doubles the speed. + w.controlled_simulation_tick(sprinting).unwrap(); + assert!(w.player.sprinting, "the sprint key starts the sprint"); + assert_eq!( + w.flying_speed().unwrap(), + 0.1, + "a sprinting player flies at twice the ability speed" + ); + // Releasing the sprint key keeps the state, so the speed stays. + w.controlled_simulation_tick(forward).unwrap(); + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in the air" + ); + assert_eq!( + w.flying_speed().unwrap(), + 0.1, + "the flight speed follows the sprint state, not the sprint key" + ); + } } From 5b5ebfcce3ecbcae6c9a5811c83ac039f867da32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Louis=20Nordb=C3=B8?= <179310784+Louistuis@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:47:57 +0100 Subject: [PATCH 21/65] Walk turtles at their own pace so their feet stop flailing (#1776) Turtles used the default MoveControl, which sets the speed straight to speedModifier * movement speed (0.25 on a stroll). Vanilla gives them TurtleMoveControl: updateSpeed halves the speed every tick on land (never below 0.06), and in water lifts the turtle 0.005 and cuts the speed away from home (0.08) or as a baby (0.06); tick then eases the speed an eighth of the way to the wanted one, faces the wanted point with the body, lifts towards it and never jumps. On land that settles at 0.08375, so a strolling turtle covered about nine times the ground per tick that vanilla's does (the input is speed squared). TurtleModel swings the legs by 8 * walkSpeed at walkPos * 5, so the walk animation fed by that motion spun the feet erratically. This only fixes the move control. Swimming still differs from vanilla: Turtle.travelInWater (moveRelative(0.1F), 0.9 drag, sinking 0.005 without a target unless heading home within 20 blocks of it), TurtlePathNavigation and the turtle goal set are not ported yet; turtles keep the generic fluid travel and goals for now. Vanilla: Turtle$TurtleMoveControl.tick / updateSpeed, Turtle., TurtleModel.setupAnim, LivingEntity.updateWalkAnimation. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/control.rs | 5 +- crates/horizon-client/src/mobs/turtle.rs | 194 +++++++++++++++++++++- 2 files changed, 196 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 3df557362..bc4d8235e 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -6,7 +6,7 @@ use horizon_core::geometry::trig; /// `2.5000003E-7F` widened: the squared distance controls treat as arrived. const ARRIVED: f64 = 2.500_000_3e-7_f32 as f64; /// `1.0E-5F` widened. -const EPSILON: f64 = 1.0e-5_f32 as f64; +pub(super) const EPSILON: f64 = 1.0e-5_f32 as f64; #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Operation { @@ -135,6 +135,9 @@ impl Mob { if self.species() == super::Species::Rabbit { return super::rabbit::move_control(self, w); } + if self.species() == super::Species::Turtle { + return super::turtle::move_control(self); + } let attr_speed = self.movement_speed(); match self.ai.mov.kind { MoveKind::Custom => super::ai::custom_move_control(self, w, events), diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs index 98dd5b558..e56973384 100644 --- a/crates/horizon-client/src/mobs/turtle.rs +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -1,12 +1,17 @@ //! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her //! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand //! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, -//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. Its own +//! `TurtleMoveControl` sets the speed it walks and swims at. Not ported yet: +//! `Turtle.travelInWater` (swimming still uses the generic fluid travel), +//! `TurtlePathNavigation` and the rest of the turtle goal set, so movement in +//! water still differs from vanilla. use super::{ Mob, MobEvent, MobWorld, + control::{EPSILON, Operation, rotlerp}, goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::trig, random::RandomSource}; pub fn register(m: &mut Mob) { let g = &mut m.ai.goals; @@ -49,6 +54,45 @@ fn block_of(m: &Mob) -> [i32; 3] { fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool { w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2])) } +/// `Turtle.TurtleMoveControl.updateSpeed`: slow in water away from home +/// (slower still as a baby), and halved every tick on land, never under 0.06. +fn update_speed(m: &mut Mob) { + if m.fluids.in_water { + m.velocity.y += 0.005; + if !close_to_home(m, 16.0) { + m.set_speed((m.ai.speed / 2.0).max(0.08)); + } + if m.is_baby() { + m.set_speed((m.ai.speed / 3.0).max(0.06)); + } + } else if m.on_ground { + m.set_speed((m.ai.speed / 2.0).max(0.06)); + } +} +/// `Turtle.TurtleMoveControl.tick`: ease the speed an eighth of the way to +/// the wanted one each tick (after `updateSpeed` cut it), face the wanted +/// point and lift towards it; no jumping, and the operation is never reset. +pub fn move_control(m: &mut Mob) { + update_speed(m); + if m.ai.mov.operation != Operation::MoveTo || m.ai.nav.is_done() { + m.set_speed(0.0); + return; + } + let [wx, wy, wz] = m.ai.mov.wanted; + let (xd, yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z); + let dist = (xd * xd + yd * yd + zd * zd).sqrt(); + if dist < EPSILON { + m.set_speed(0.0); + return; + } + let y_rot = trig::atan2_degrees(zd, xd) - 90.0; + m.yaw = rotlerp(m.yaw, y_rot, 90.0); + m.body_yaw = m.yaw; + let wanted = (m.ai.mov.speed_modifier * m.movement_speed()) as f32; + // Mth.lerp(0.125F, getSpeed(), wanted). + m.set_speed(m.ai.speed + 0.125 * (wanted - m.ai.speed)); + m.velocity.y += f64::from(m.ai.speed) * (yd / dist) * 0.1; +} /// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 { @@ -207,3 +251,149 @@ impl Goal for GoHome { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::mobs::{ + Species, + path::{Path, PathNode, PathType}, + }; + use horizon_core::geometry::Vec3; + use std::sync::Arc; + + /// A turtle (movement speed 0.25) strolling (`speedModifier` 1.0) to a + /// point ten blocks ahead along a path it has not finished. + fn strolling_turtle() -> Mob { + let mut kind = crate::mobs::sensor_scan_tests::kind(); + let k = Arc::make_mut(&mut kind); + k.id = "minecraft:turtle".into(); + k.species = Species::Turtle; + k.speed = 0.25; + k.step_height = 1.0; + let mut m = Mob::new(1, kind, Vec3::ZERO, 0.0); + m.on_ground = true; + let node = PathNode { + x: 0, + y: 0, + z: 10, + kind: PathType::Walkable, + }; + m.ai.nav.path = Some(Path { + nodes: vec![node], + next: 0, + target: [0, 0, 10], + dist_to_target: 0.0, + reached: true, + }); + m.ai.mov.set_wanted(0.0, 0.0, 10.0, 1.0); + m + } + fn speeds(m: &mut Mob, ticks: usize) -> Vec { + (0..ticks) + .map(|_| { + move_control(m); + assert_eq!(m.ai.zza, m.ai.speed, "setSpeed sets the forward input"); + m.ai.speed + }) + .collect() + } + + #[test] + fn walks_on_land_at_a_third_of_its_movement_speed() { + // TurtleMoveControl.tick on the ground: updateSpeed makes it + // max(speed / 2, 0.06) = 0.06, then Mth.lerp(0.125F, 0.06, 0.25), + // every tick. The default MoveControl walked it at the full 0.25, so + // the walk animation (and TurtleModel's 8 * walkSpeed leg swing) ran + // about nine times too fast (#1776). + let mut m = strolling_turtle(); + let land = 0.06_f32 + 0.125 * (0.25 - 0.06_f32); + assert_eq!(speeds(&mut m, 40), vec![land; 40]); + // Facing the wanted point, the body with it; it never jumps. + assert_eq!(m.body_yaw, m.yaw); + assert!(crate::mobs::living::wrap(m.yaw).abs() < 1.0e-3); + assert!(!m.ai.jump); + assert_eq!(m.ai.mov.operation, Operation::MoveTo); + assert_eq!(m.velocity.y, 0.0); + } + + #[test] + fn water_speed_is_cut_away_from_home_and_for_babies() { + // updateSpeed in water near home: no cut, the lerp climbs towards + // 0.25, and it lifts the turtle 0.005 a tick. (Only the control's + // speed: Turtle.travelInWater is not ported.) + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + let s = speeds(&mut m, 60); + assert_eq!(s[0], 0.125 * 0.25); + assert!(s.windows(2).all(|w| w[1] > w[0]) && s[59] > 0.24 && s[59] < 0.25); + assert!((m.velocity.y - 60.0 * 0.005).abs() < 1.0e-9); + // More than 16 blocks from home: max(speed / 2, 0.08) first. + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + m.extra.home = Some([0, 0, 40]); + let far = 0.08_f32 + 0.125 * (0.25 - 0.08_f32); + assert_eq!(speeds(&mut m, 20), vec![far; 20]); + // A baby: max(speed / 3, 0.06). + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + m.extra.age = -24000; + let young = 0.06_f32 + 0.125 * (0.25 - 0.06_f32); + assert_eq!(speeds(&mut m, 20), vec![young; 20]); + } + + #[test] + fn stops_when_the_path_is_done_or_the_point_reached() { + let mut m = strolling_turtle(); + m.ai.nav.stop(); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(0.0, 0.0, 0.0, 1.0); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + // updateSpeed runs before the early return: a stopped turtle in + // water is still lifted 0.005, path done or not moving at all. + let mut m = strolling_turtle(); + m.fluids.in_water = true; + m.ai.nav.stop(); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + assert_eq!(m.velocity.y, 0.005); + let mut m = strolling_turtle(); + m.fluids.in_water = true; + m.ai.mov.operation = Operation::Wait; + assert_eq!(speeds(&mut m, 1), vec![0.0]); + assert_eq!(m.velocity.y, 0.005); + } + + #[test] + fn lifts_towards_a_point_above_by_the_slope_of_the_way_there() { + // setDeltaMovement(... + getSpeed() * (dy / dist) * 0.1): two up, + // three across and ten ahead. + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(3.0, 2.0, 10.0, 1.0); + let speed = speeds(&mut m, 1)[0]; + let dist = (3.0_f64 * 3.0 + 2.0 * 2.0 + 10.0 * 10.0).sqrt(); + assert_eq!(m.velocity.y, f64::from(speed) * (2.0 / dist) * 0.1); + assert!(m.velocity.y > 0.0); + } + + #[test] + fn turns_at_most_ninety_degrees_a_tick_and_wraps_into_a_turn() { + // rotlerp(yRot, target, 90): from 150 towards about -16.7 it turns + // the full 90 to 60, then reaches the target, kept in [0, 360] as + // about 343.3; the body follows the yaw each tick. + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(3.0, 0.0, 10.0, 1.0); + m.yaw = 150.0; + m.body_yaw = 150.0; + let target = trig::atan2_degrees(10.0, 3.0) - 90.0; + assert!((-17.0..-16.0).contains(&target)); + move_control(&mut m); + assert_eq!((m.yaw, m.body_yaw), (60.0, 60.0)); + move_control(&mut m); + assert_eq!(m.yaw, 60.0 + (target - 60.0) + 360.0); + assert_eq!(m.body_yaw, m.yaw); + } +} From 8909e0510c4700295514c83c5f61cbd5695d9db7 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:55:39 +0500 Subject: [PATCH 22/65] commands: selectors find the End crystals and the Ender Dragon Horizon's command targets enumerated the ordinary entity collections only, so `@e[type=end_crystal]` and `@e[type=ender_dragon]` matched nothing: the End crystals and the dragon live in their own lists, and neither carried an entity id a command could name. The crystals and the dragon now take an id from the entity counter when they are created, as EndCrystal's and EnderDragon's constructors do; the selector offers them as candidates; `/data get entity` reads them and `/kill` removes them the way `Entity.kill` does. `/summon minecraft:end_crystal` creates one, as vanilla does. Fixes #1531 Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/game/commands.rs | 49 +++++++++++++++++++ .../horizon-client/src/game/commands/data.rs | 10 ++++ crates/horizon-client/src/game/dragon.rs | 24 ++++++++- crates/horizon-client/src/game/persist.rs | 20 +++++++- crates/horizon-client/src/game/scoreboard.rs | 6 ++- tools/command_exec_corpus.py | 11 +++++ 6 files changed, 115 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..bb8ae68d6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -53,6 +53,10 @@ pub(super) enum Target { /// An entity of a type Horizon does not simulate (markers, displays, /// interactions...): kept as its saved data at a position. Other(u32), + /// An End crystal, by its entity id (`minecraft:end_crystal`). + Crystal(u32), + /// The Ender Dragon, by its entity id (`minecraft:ender_dragon`). + Dragon(u32), } /// An entity of a type Horizon does not simulate: its compound lives in the /// entity memory (`persist.raw`), its position and rotation here. @@ -385,6 +389,16 @@ impl Game<'_> { .iter() .find(|o| o.id == id) .map(|o| [o.position.x, o.position.y, o.position.z]), + Target::Crystal(id) => self + .crystals + .iter() + .find(|c| c.id == id) + .map(|c| [c.position.x, c.position.y, c.position.z]), + Target::Dragon(id) => self + .dragon + .as_ref() + .filter(|d| d.id == id) + .map(|d| [d.position.x, d.position.y, d.position.z]), } } pub(super) fn target_type(&self, t: Target) -> String { @@ -428,6 +442,8 @@ impl Game<'_> { .iter() .find(|o| o.id == id) .map_or_else(String::new, |o| o.kind.clone()), + Target::Crystal(_) => "minecraft:end_crystal".into(), + Target::Dragon(_) => "minecraft:ender_dragon".into(), } } /// The name of the player the game acts for: a guest's own while their @@ -552,6 +568,12 @@ impl Game<'_> { candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); + // The End crystals and the dragon (EndCrystal and EnderDragon + // are entities of their own). + candidates.extend(self.crystals.iter().map(|c| Target::Crystal(c.id))); + if let Some(d) = &self.dragon { + candidates.push(Target::Dragon(d.id)); + } } let level = self.experience.level; let creative = self.creative; @@ -1199,6 +1221,17 @@ impl Game<'_> { } } } + Target::Crystal(id) => { + if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) { + c.position = v; + } + } + Target::Dragon(id) => { + if let Some(d) = self.dragon.as_mut().filter(|d| d.id == id) { + d.position = v; + d.previous = v; + } + } // Wall-mounted entities do not move. Target::Frame(_) | Target::Painting(_) => {} } @@ -1594,6 +1627,8 @@ impl Game<'_> { Target::Boat(id) => self.boats.retain(|b| b.id != id), Target::Cart(id) => self.carts.retain(|c| c.id != id), Target::Other(id) => self.others.retain(|o| o.id != id), + Target::Crystal(id) => self.kill_crystal(id), + Target::Dragon(id) => self.kill_dragon(id), } } fn cmd_kill(&mut self, ctx: &Context) -> R { @@ -1706,6 +1741,20 @@ impl Game<'_> { self.spawn_bolt(pos, false); name = Text::translate("entity.minecraft.lightning_bolt", &[]); } + "end_crystal" => { + // EndCrystal's constructor takes an id from the entity + // counter, and the crystal is shown with its base. + self.next_entity += 1; + self.crystals.push(super::dragon::Crystal { + id: self.next_entity, + position: Vec3::new(pos[0], pos[1], pos[2]), + show_bottom: true, + time: self.world.random.next_int_bound(100_000).unwrap_or(0), + beam: None, + invulnerable: false, + }); + name = Text::translate("entity.minecraft.end_crystal", &[]); + } k if super::minecarts::CartKind::from_id(&kind).is_some() => { let cart_kind = super::minecarts::CartKind::from_id(&kind) .unwrap_or(super::minecarts::CartKind::Rideable); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index ac16c5e7c..3964f73a1 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -129,6 +129,16 @@ impl Game<'_> { entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None) .or_else(|| entity_nbt::fireball_to_nbt(p, random_uuid(), owner, None))? } + Target::Crystal(id) => { + let c = self.crystals.iter().find(|c| c.id == id)?; + let (uuid, raw) = self.persist_anon("minecraft:end_crystal", c.position); + c.to_nbt(uuid.unwrap_or_else(random_uuid), raw) + } + Target::Dragon(id) => { + let d = self.dragon.as_ref().filter(|d| d.id == id)?; + let (uuid, raw) = self.persist_anon("minecraft:ender_dragon", d.position); + d.to_nbt(uuid.unwrap_or_else(random_uuid), raw) + } }) } /// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..7e1c90ac7 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -828,8 +828,10 @@ impl Game<'_> { continue; } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + // EndCrystal's constructor takes an id from the entity counter. + self.next_entity += 1; self.crystals.push(Crystal { - id: 0, + id: self.next_entity, position: at, show_bottom: true, time, @@ -2830,8 +2832,11 @@ impl Game<'_> { return false; } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + // EndCrystal's constructor takes an id from the entity counter, so + // the crystal is an entity a command can name (`@e[type=end_crystal]`). + self.next_entity += 1; self.crystals.push(Crystal { - id: 0, + id: self.next_entity, position: Vec3::new(x + 0.5, y, z + 0.5), show_bottom: false, time, @@ -2848,6 +2853,21 @@ impl Game<'_> { self.swing_arm(); true } + /// `EndCrystal.kill` (`/kill`): the crystal is removed, without a blast + /// (`Entity.kill` does not hurt it). + pub(super) fn kill_crystal(&mut self, id: u32) { + if let Some(i) = self.crystals.iter().position(|c| c.id == id) { + self.destroy_crystal(i, None, CrystalDamage::Explosion); + } + } + /// `EnderDragon.kill` (`/kill`): `Entity.kill` removes the entity, it + /// does not hurt it (the dragon flies its death flight when its health + /// runs out). + pub(super) fn kill_dragon(&mut self, id: u32) { + if self.dragon.as_ref().is_some_and(|d| d.id == id) { + self.dragon = None; + } + } /// Any entity touching `room` (`Level.getEntities(null, box)`). fn entity_in(&self, room: Aabb) -> bool { let touches = |lo: Vec3, hi: Vec3| { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b5e650e70..7b5a741b9 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -290,14 +290,22 @@ impl Game<'_> { "minecraft:ender_dragon" => { let seed = self.world.random.next_long(); if self.dragon.is_none() - && let Some(d) = super::dragon::Dragon::from_nbt(&tag, seed) + && let Some(mut d) = super::dragon::Dragon::from_nbt(&tag, seed) { + // EnderDragon's constructor takes its id and its + // parts' from the entity counter. + d.id = self.next_entity + 1; + self.next_entity += 9; self.dragon = Some(d); } } "minecraft:end_crystal" => { let time = self.world.random.next_int_bound(100_000).unwrap_or(0); - if let Some(c) = super::dragon::Crystal::from_nbt(&tag, time) { + if let Some(mut c) = super::dragon::Crystal::from_nbt(&tag, time) { + // EndCrystal's constructor takes an id from the + // entity counter. + self.next_entity += 1; + c.id = self.next_entity; self.crystals.push(c); } } @@ -531,6 +539,14 @@ impl Game<'_> { self.persist.uuids.remove(&id); self.persist.raw.remove(&id); } + /// The compound an entity without a Horizon entity ID was loaded with + /// (the crystals and the dragon), found again by type and position. + pub(super) fn persist_anon(&self, kind: &str, p: Vec3) -> (Option<[i32; 4]>, Option<&Tag>) { + self.persist + .anon + .get(&anon_key(kind, p)) + .map_or((None, None), |(_, uuid, raw)| (*uuid, Some(raw))) + } /// The compound an entity was loaded with (and commands have edited). pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 81c03e288..005446ed1 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -180,7 +180,11 @@ impl Game<'_> { | Target::Cart(id) | Target::Other(id) => self.persist.raw.get(&id), Target::Player => self.level.player_extra.as_ref(), - Target::Guest(_) | Target::Orb(_) | Target::Projectile(_) => None, + Target::Guest(_) + | Target::Orb(_) + | Target::Projectile(_) + | Target::Crystal(_) + | Target::Dragon(_) => None, }; match raw.and_then(|r| r.get("Tags")) { Some(Tag::List(l)) => l diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index d8f925ef0..1d346e002 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -327,6 +327,17 @@ def entities(): cmd('/data get entity @e[tag=attr,limit=1] Health'), cmd('/attribute @e[tag=attr,limit=1] minecraft:attack_damage base get'), cmd('/kill @e[tag=attr]'), + # An End crystal is an entity of its own: a type selector finds it, + # reads it and kills it (#1531). + cmd('/summon minecraft:end_crystal 4.5 210 8.5'), + cmd('/execute if entity @e[type=minecraft:end_crystal]'), + cmd('/data get entity @e[type=minecraft:end_crystal,limit=1] Pos'), + cmd('/kill @e[type=minecraft:end_crystal]'), + cmd('/execute if entity @e[type=minecraft:end_crystal]'), + cmd('/summon minecraft:ender_dragon 4.5 210 8.5'), + cmd('/execute if entity @e[type=minecraft:ender_dragon]'), + cmd('/data get entity @e[type=minecraft:ender_dragon,limit=1] Pos'), + cmd('/kill @e[type=minecraft:ender_dragon]'), *setup('/kill @e[type=minecraft:armor_stand]'), {'op': 'tick', 'n': 25}, cmd('/execute if entity @e[tag=h]'), From 64cd55cf74d7ae27b67bc69b737a98f53274a59d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Louis=20Nordb=C3=B8?= <179310784+Louistuis@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:14:00 +0100 Subject: [PATCH 23/65] Finish a use on the server's USE_ITEM_COMPLETE, and eat on the client too On a server client (single player's server thread, LAN guests, dedicated servers) the window ended a consumable's use on its own timer and never ate the food: its FoodData waited for the server's next ClientboundSetHealth. With the button still held, the next startUseItem found the food bar below 20 and began another bite, so the eating animation went on after the bar was full (#2471). Vanilla's client never completes a use by itself: LivingEntity.updateUsingItem completes it only on the server, and ServerPlayer.completeUsingItem first sends the player entity event 9 (USE_ITEM_COMPLETE). Player.handleEntityEvent(9) then runs completeUsingItem on the client, where Consumable.onConsume calls the FoodProperties listener on both sides: the client's FoodData eats at once. - The server sends event 9 to the acting guest when a consumable, a potion or a spyglass use completes. Like the guest's packets, the events are queued during their turn (kept across nested turns) and sent with their entity id. - The client keeps using until that event, then shows the last crumbs, eats the food (the next ClientboundSetHealth replaces it) and starts the item's use_cooldown, which ItemStack.use only starts at once for an item with no use time. - What vanilla's client checks so that a use can't outlive the server's: MultiPlayerGameMode.useItem passes on an item cooling down (chorus fruit held through its cooldown), LivingEntity.updatingUsingItem stops when the hand no longer holds the item the use began with (ItemStack.isSameItem), a respawn is a new player with no use, and Consumable.startConsuming starts none for a consumable with no use time. - ItemCooldowns tick where Player.tick ticks them: after LivingEntity.tick's use on the server and after Minecraft.handleKeybinds on the client. Both sides ticked them first, so a guest's entry ended a tick later on the server than on their client, whose held retry was refused and never ended. lan_e2e's new eat_full check eats melon slices up to a full bar with the button still held: before, a new bite had started (use ticks 26, 2, 9, 15); now nothing is in use. Held on two chorus fruits, both are eaten across the cooldown. consume-release holds its completed use a little longer, as the use now ends with the server's event. Fixes #2471 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 6 + crates/horizon-client/src/game/consume.rs | 10 ++ crates/horizon-client/src/game/lan_actions.rs | 49 +++++--- crates/horizon-client/src/game/potions.rs | 1 + crates/horizon-client/src/game/remote.rs | 113 ++++++++++++++---- tools/lan_e2e.py | 66 +++++++++- 6 files changed, 205 insertions(+), 40 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index db49087b2..43f68f228 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1681,6 +1681,9 @@ struct Game<'a> { /// The acting guest's cooldowns, as (item, ticks): their packet needs the /// hub's item registry, which the guest's turn does not hold. guest_cooldowns: Vec<(Arc, i32)>, + /// The acting guest's own entity events (`ServerPlayer.connection.send`), + /// sent with their entity id, which the guest's turn does not hold. + guest_entity_events: Vec, /// `broadcastToAdmins` lines a guest's command queued, sent once it /// returns: the line, whether operators get it and whether the console /// logs it. @@ -4078,6 +4081,7 @@ impl Game<'_> { if &*stack.item == "minecraft:spyglass" { // SpyglassItem.USE_DURATION, then finishUsingItem. if ticks + 1 >= 1200 { + self.send_use_item_complete(); self.stop_spyglass(); self.using = None; } else { @@ -4099,6 +4103,7 @@ impl Game<'_> { } if ticks >= duration { self.using = None; + self.send_use_item_complete(); // ItemStack.finishUsingItem's applyAfterUseComponentSideEffects. self.apply_use_cooldown(&stack); self.finish_consuming(&info, consumable, &stack); @@ -12893,6 +12898,7 @@ impl<'a> Game<'a> { lan_acting: None, guest_packets: Vec::new(), guest_cooldowns: Vec::new(), + guest_entity_events: Vec::new(), lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index 93d919911..dc187d207 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -19,7 +19,17 @@ use std::convert::Infallible; type ItemConsumable = Consumable; +/// `EntityEvent.USE_ITEM_COMPLETE`: the server finished the player's use. +pub(super) const USE_ITEM_COMPLETE_EVENT: i8 = 9; + impl Game<'_> { + /// `ServerPlayer.completeUsingItem`: the player's own client is told + /// first, and completes the use itself (eating the food there too). + pub(super) fn send_use_item_complete(&mut self) { + if self.lan_acting.is_some() { + self.guest_entity_events.push(USE_ITEM_COMPLETE_EVENT); + } + } /// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`. pub(super) fn emit_consume( &mut self, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index dc1e74f0b..ba5ed75cd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -165,6 +165,8 @@ pub(super) struct GuestSwap { acting: (Option, Option, Option), /// The packets queued for that guest. packets: Vec, + /// The entity events queued for that guest. + entity_events: Vec, /// The host's count of swings started, kept while the guest acts. swings: u32, /// How many projectiles there were: those added since are the guest's. @@ -389,6 +391,7 @@ impl Game<'_> { self.lan_acting_uuid.replace(g.uuid), ); let packets = std::mem::take(&mut self.guest_packets); + let entity_events = std::mem::take(&mut self.guest_entity_events); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); let modifiers = std::mem::replace( @@ -449,6 +452,7 @@ impl Game<'_> { death_cause, acting, packets, + entity_events, swings, projectiles, modifiers, @@ -508,6 +512,7 @@ impl Game<'_> { combat, acting, packets, + entity_events, swings, projectiles, modifiers, @@ -529,6 +534,17 @@ impl Game<'_> { for packet in std::mem::replace(&mut self.guest_packets, packets) { host.hub.send_to(conn, &packet); } + // ServerPlayer.connection.send: the guest's own entity events. + let entity_id = host.hub.guests[i].entity_id; + for event in std::mem::replace(&mut self.guest_entity_events, entity_events) { + host.hub.send_to( + conn, + &C::EntityEvent(play::EntityEvent { + id: entity_id, + event, + }), + ); + } // ServerItemCooldowns.onCooldownStarted: the guest's own cooldown. for (group, duration) in std::mem::take(&mut self.guest_cooldowns) { host.hub.send_to( @@ -1910,21 +1926,8 @@ impl Game<'_> { continue; } let play = host.play.entry(conn).or_default(); - // 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); + // ServerGamePacketListenerImpl.tick's dropSpamThrottler. 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() { - host.hub.send_to( - conn, - &C::Cooldown(play::Cooldown { - group: group.to_string(), - duration: 0, - }), - ); - } let digging = play.digging; let using = play.using.is_some(); let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100; @@ -1961,6 +1964,24 @@ impl Game<'_> { play.digging = None; } } + // Player.tick's ItemCooldowns.tick, once a tick for each player + // (the shield an axe disabled, a thrown pearl), after + // LivingEntity.tick's use: an entry a finished use starts has 20 + // ticks left when the next tick's packets are handled, as the + // guest's own client counts. + let play = host.play.entry(conn).or_default(); + play.shield_cooldown = play.shield_cooldown.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() { + host.hub.send_to( + conn, + &C::Cooldown(play::Cooldown { + group: group.to_string(), + duration: 0, + }), + ); + } // Player.tick: a different main-hand item resets the attack // strength, and detectEquipmentUpdates gives the guest its modifiers. let g = &host.hub.guests[gi]; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 2ccfd4116..7f30e21c2 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -300,6 +300,7 @@ impl Game<'_> { return true; } self.using = None; + self.send_use_item_complete(); self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player); if ominous { self.drink_ominous_bottle(slot, stack); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..50bf6d4f3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -117,6 +117,8 @@ pub(super) struct Remote { joined: bool, status: String, pub(super) entity_id: i32, + /// The item the player's use began with (`LivingEntity.useItem`). + pub(super) use_item: Option>, dimension: DimensionType, /// What chunk packets decode with (the dimension's height and sky, the /// biome registry); replaced whenever one of them changes. @@ -428,6 +430,7 @@ impl Game<'_> { joined: false, status: "Connecting to the server...".into(), entity_id: 0, + use_item: None, dimension: DimensionType::vanilla("minecraft:overworld"), chunk_format: Arc::new(ChunkFormat::new( &DimensionType::vanilla("minecraft:overworld"), @@ -1639,8 +1642,10 @@ impl Game<'_> { self.send(S::ClientInformation(info)); } C::Respawn(p) => { - // A new player, without effects: the server sends them again. + // A new player, without effects (the server sends them + // again) and with no item in use. self.potions.effects.clear(); + self.using = None; self.enter_remote_dimension(&p.spawn, true); self.screen = Screen::Playing; if let Some(r) = self.remote.as_mut() { @@ -2138,6 +2143,11 @@ impl Game<'_> { if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + if p.event == super::consume::USE_ITEM_COMPLETE_EVENT + && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) + { + self.remote_complete_using(); + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -3135,12 +3145,6 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; self.track_experience_display(); - // Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s - // for a server's client (multiplayer and the default single player), - // so the entries advance here or the slot stays shaded until the - // server says the entry ended. `onCooldownEnded` is the plain - // ItemCooldowns' no-op on a client. - self.cooldowns.tick(); // Options.broadcastOptions: a changed render distance or Chat option // is sent again. let view = client_view_distance(self.settings.render_distance); @@ -3174,6 +3178,14 @@ impl Game<'_> { // Window callbacks only queue clicks, so an interaction cannot leak // between CLIENT_TICK_END and a later pong. self.remote_handle_input(); + // Player.tick's ItemCooldowns.tick, in ClientLevel.tickEntities after + // handleKeybinds: this path replaces `tick_world`'s for a server's + // client (multiplayer and the default single player), so the entries + // advance here or the slot stays shaded until the server says the + // entry ended. `onCooldownEnded` is the plain ItemCooldowns' no-op on + // a client. Ticking it after the keybinds keeps a held use from + // trying again a tick before the server's entry ends. + self.cooldowns.tick(); // ClientLevel.tick: the border's size change. self.border.tick(); self.player_border(); @@ -4295,10 +4307,19 @@ impl Game<'_> { let Some(info) = self.res.items().get(&held.item).cloned() else { return false; }; - // MultiPlayerGameMode.useItem runs the use here too (inside - // startPrediction): the `use_cooldown` component starts its entry, and - // the server's ClientboundCooldownPacket confirms it. - self.apply_use_cooldown(&held); + // MultiPlayerGameMode.useItem's prediction: an item cooling down + // passes (its packet still goes). + let group = horizon_client::cooldowns::group(&held, info.use_cooldown.as_ref()); + if self.cooldowns.is_on_cooldown(&group) { + return false; + } + // It runs the use here too: ItemStack.use starts the `use_cooldown` + // of an item with no use time, and the server's + // ClientboundCooldownPacket confirms it; one held in use starts it at + // finishUsingItem (remote_complete_using). + if !info.consumable.as_ref().is_some_and(|c| c.ticks() > 0) { + self.apply_use_cooldown(&held); + } // Food starts being eaten (Consumable.startConsuming), a book and // quill opens. self.with_hand(hand, |g| g.start_eating(&info)); @@ -4373,14 +4394,25 @@ impl Game<'_> { self.remote_use_item(Hand::Off); } /// `LivingEntity.updatingUsingItem` on a server client: an item held in - /// use (`held_until_released`), and a - /// consumable's eating animation and its crumbs. The server eats it and - /// sends the stack, the hunger and the sounds. + /// use (`held_until_released`), and a consumable's eating animation and + /// its crumbs until the server's USE_ITEM_COMPLETE. The server sends the + /// stack, its hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // The use stops when the hand no longer holds the item it began with + // (ItemStack.isSameItem). + let item = stack.as_ref().map(|s| Arc::clone(&s.item)); + if let Some(r) = self.remote.as_mut() { + if ticks == 0 { + r.use_item = item; + } else if r.use_item != item { + self.using = None; + return; + } + } // Another hotbar slot picked: LivingEntity.updatingUsingItem sees a // different stack in the hand. The off hand keeps its item. let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT; @@ -4405,20 +4437,51 @@ impl Game<'_> { self.using = None; return; } - // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. - let duration = consumable.ticks().max(0) as u32; - let remaining = duration - ticks.min(duration); - if consumable.particles && consumable.should_emit(remaining as i32) { + // Consumable.startConsuming eats one with no use time at once, without + // a use (nor a USE_ITEM_COMPLETE). + if consumable.ticks() <= 0 { + self.using = None; + return; + } + // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. The + // countdown goes on past zero (LivingEntity.updateUsingItem completes + // only on the server) until the server's USE_ITEM_COMPLETE. + let remaining = consumable.ticks() - ticks as i32; + if consumable.particles && consumable.should_emit(remaining) { self.eat_particles(&stack, 5); } - if ticks + 1 >= duration { - self.using = None; - if consumable.particles { - self.eat_particles(&stack, 16); - } - } else { - self.using = Some((slot, ticks + 1)); + self.using = Some((slot, ticks + 1)); + } + /// `Player.handleEntityEvent(9)`: `completeUsingItem` on the client. A consumable's last crumbs, and FoodProperties.onConsume, + /// which runs on the client too (Consumable.onConsume calls its + /// ConsumableListeners on both sides): the client's FoodData eats at once, + /// so a held right click finds `Player.canEat` false instead of starting + /// another bite before the server's ClientboundSetHealth arrives. + fn remote_complete_using(&mut self) { + let Some((slot, _)) = self.using.take() else { + return; + }; + let Some(stack) = self.stack_in(slot).cloned() else { + return; + }; + let Some(info) = self.res.items().get(&stack.item).cloned() else { + return; + }; + if info.consumable.as_ref().is_some_and(|c| c.particles) { + self.eat_particles(&stack, 16); } + if let Some((nutrition, saturation)) = info.food + && let Some(r) = self.remote.as_mut() + { + // FoodData.eat(nutrition, saturation), as finish_consuming does; + // the next ClientboundSetHealth replaces it. + let (_, food, sat) = &mut r.health; + *food = (*food + nutrition as i32).clamp(0, 20); + *sat = (*sat + saturation).clamp(0.0, *food as f32); + self.apply_remote_health(); + } + // ItemStack.finishUsingItem's applyAfterUseComponentSideEffects. + self.apply_use_cooldown(&stack); } /// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick. pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 03e0e888f..329a11707 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -114,6 +114,10 @@ address. The script then checks, from both sides, what a guest's game used to ge use to completion still consumes the item (#1293). - eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the player it draws, and no longer once the bread is eaten (#803); +- eat_full: holding right click with melon slices until the food bar is full: the guest's own + client eats each slice when the server says it is done (entity event 9, + USE_ITEM_COMPLETE), so no other bite starts; held on chorus fruit, both fruits are + eaten across its cooldown (#2471). - xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the guest their points (not the host). - objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the @@ -5214,6 +5218,64 @@ CHECKS += ['helduse'] CHECK_FNS.update(helduse=check_held_use) +def check_eat_full(host, guest, out): + """Holding right click past a full food bar starts no other bite; chorus fruit's cooldown + doesn't leave the use stuck (#2471).""" + guest('command', command='gamemode survival') + guest('command', command='clear @s') + # Full health: natural regeneration at 18 food or more would eat into the bar. + guest('command', command='effect give @s minecraft:instant_health 1 10') + guest('command', command='effect give @s minecraft:hunger 60 127') + for _ in range(400): + if remote(guest)['food'] <= 17: + break + guest.wait(1) + guest('command', command='effect clear @s') + guest('command', command='give @s minecraft:melon_slice 16') + guest.wait(5) + guest.raw('select', 'minecraft:melon_slice') + hungry = remote(guest)['food'] + # A slice (2 food) takes 32 ticks (1.6 s): the button stays down well past the slices that fill + # the bar, with room for a slow server. + slices = -(-(20 - hungry) // 2) + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', slices * 4.0 + 6.0)) + hold.start() + deadline = time.monotonic() + slices * 4.0 + 2.0 + while remote(guest)['food'] < 20 and time.monotonic() < deadline: + time.sleep(0.1) + # The bar is full and the button is still down: nothing is in use over the next 20 ticks + # (sleeps, as `wait` is refused while the held use-item runs). + using = [] + for _ in range(4): + time.sleep(0.25) + using.append(guest('state').get('using')) + guest.shot(out, 'eat-full') + hold.join() + guest.wait(10) + full = {'hungry': hungry, 'fed': remote(guest)['food'], 'using': using, + 'eaten': 16 - guest('inventory')['counts'].get('minecraft:melon_slice', 0), 'needed': slices} + assert hungry < 20, f'the guest is not hungry: {full}' + assert full['fed'] == 20 and full['eaten'] == slices, f'the bar did not fill: {full}' + assert using == [None] * 4, f'another bite started with a full food bar: {full}' + + # Chorus fruit can always be eaten, then its group cools down for 20 ticks: the client waits + # it out (MultiPlayerGameMode.useItem) and eats the second fruit with the button still held. + guest('command', command='clear @s') + guest('command', command='give @s minecraft:chorus_fruit 2') + guest.wait(5) + guest.raw('select', 'minecraft:chorus_fruit') + guest.raw('use-item', '--hold', 7.0) + guest.wait(10) + chorus = {'left': guest('inventory')['counts'].get('minecraft:chorus_fruit', 0), + 'using': guest('state').get('using')} + assert chorus == {'left': 0, 'using': None}, f'the held use did not eat both chorus fruits: {chorus}' + return {'full': full, 'chorus': chorus} + + +CHECKS += ['eat_full'] +CHECK_FNS.update(eat_full=check_eat_full) + + def check_consume_release(host, guest, out): """#1293: releasing a consumable in either hand cancels it on client and server, while holding it to completion applies its effects and remainder (Consumable.onConsume).""" @@ -5258,8 +5320,10 @@ def check_consume_release(host, guest, out): assert effects == before, f'{case} applied consumption effects after release: {cancelled}' game.shot(out, f'consume-release-{hand}-{item}') # A sustained press must still consume normally, including the milk's empty bucket. + # The use ends with the server's USE_ITEM_COMPLETE, 32 server ticks after its + # UseItem: room for a busy server before letting go. game.raw('mouse', 'right', 'down') - game.wait(40) + game.wait(50) game.raw('mouse', 'right', 'up') game.wait(10) inventory = game('inventory') From 67b6e75c0b4361c9aa2fb04ea020410cf0fe5167 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:01:42 +0500 Subject: [PATCH 24/65] The container screen's press state does not survive the screen AbstractContainerScreen keeps `isQuickCrafting` and the drag it belongs to on the screen, so every screen starts with its own state. Horizon keeps both on `Game`, and #2052 only dropped them when the pointer was grabbed again, so a press whose release never arrived (the pointer left the window) kept the drag running on the next screen: `Clicks::press` answers `None` for every later press, so the Shift quick move and the clicks on the inventory went dead. The press state now goes with the pointer: `Game::capture` drops it whichever way the pointer changes hands (a screen opens or closes, the window loses focus), and `Clicks::cancel_drag` names the drop. Fixes #1737 Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/container_screen.rs | 43 +++++++++++++++++++ crates/horizon-client/src/game.rs | 21 +++++---- crates/horizon-client/src/menu.rs | 27 ++++++++++++ 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs index 77c7ad8aa..a7b1794c5 100644 --- a/crates/horizon-client/src/container_screen.rs +++ b/crates/horizon-client/src/container_screen.rs @@ -124,6 +124,18 @@ impl Clicks { self.skip_next_release = true; } + /// The screen that takes the pointer over starts with its own state: + /// `AbstractContainerScreen` holds `isQuickCrafting` and the drag it + /// belongs to on the screen, so a screen that opens (or closes) drops + /// them. A press whose release never arrived -- the pointer left the + /// window -- would otherwise keep the drag running, and `press` answers + /// `None` for every later press, so the quick move and the clicks go + /// dead on every screen after it. + pub fn cancel_drag(&mut self) { + self.quick_crafting = None; + self.skip_next_release = false; + } + /// `mouseClicked` (no double click): the `slotClicked` input it sends on /// `target`, if any. A press holding a stack starts a quick craft drag /// instead. `cloning` is `keyPickItem` with infinite materials. @@ -301,4 +313,35 @@ mod tests { Some(Input::Pickup) ); } + + /// #1737: a press whose release never arrives (the pointer left the + /// window) leaves `isQuickCrafting` set, and `press` answers `None` for + /// every later press, so the Shift quick move and the clicks on the + /// inventory go dead. The drag belongs to the screen that has it + /// (`AbstractContainerScreen` holds `isQuickCrafting`), so the screen + /// that takes the pointer over drops it and the quick move works again. + #[test] + fn a_lost_release_does_not_wedge_the_quick_move() { + let mut clicks = Clicks::default(); + let slot = Target::::Slot(3); + // Pressed with a stack carried: a quick craft drag starts, and its + // release never arrives. + assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None); + assert!(clicks.quick_crafting().is_some()); + // The stuck drag swallows the next press: the Shift quick move stops + // working and the inventory stops answering. + assert_eq!(clicks.press(&slot, Button::Right, true, true, false), None); + // The screen that takes the pointer over starts with its own state. + clicks.cancel_drag(); + assert!(clicks.quick_crafting().is_none()); + // The quick move works again. + assert_eq!( + clicks.press(&slot, Button::Right, true, true, false), + Some(Input::QuickMove) + ); + assert_eq!( + clicks.press(&slot, Button::Left, true, false, false), + Some(Input::Pickup) + ); + } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 807a1d2cf..60c857785 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4941,10 +4941,13 @@ impl Game<'_> { if capture && !self.focused { return; } - if capture { - // The inventory's screens are behind us: no drag survives them. - self.reset_inventory_clicks(); - } else { + // The container screen's press state belongs to the screen: a screen + // that takes the pointer over starts with its own state, as + // `AbstractContainerScreen` does, so a press whose release never + // arrived (the pointer left the window) cannot wedge the next + // screen's quick move and clicks. + self.reset_inventory_clicks(); + if !capture { self.stop_mining(); } // The real pointer takes over from an agent's. @@ -5788,12 +5791,14 @@ impl Game<'_> { } } /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it - /// belongs to on the screen; Horizon keeps them on the game, so they are - /// dropped when a screen closes. A press whose release never reaches the - /// screen (the pointer left the window, or the screen closed first) would + /// belongs to on the screen. Horizon keeps both on `Game` (`inv_clicks`, + /// `inv_drag`, `last_inv_click`), so they are dropped when the pointer + /// changes hands: a screen that opens or closes starts with its own + /// state, and a press whose release never reached the screen -- the + /// pointer left the window, or the screen closed first -- would /// otherwise leave every later press on every later screen swallowed. pub(super) fn reset_inventory_clicks(&mut self) { - self.inv_clicks = Default::default(); + self.inv_clicks.cancel_drag(); self.inv_drag = None; self.last_inv_click = None; } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 3b2b8fd31..56c8a3b55 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3211,4 +3211,31 @@ pub(crate) mod tests { assert_eq!(menu.slot(0), stack("dirt", 1).as_ref()); }); } + + /// #1737: a Shift+Right-Click quick move in a chest (a double chest's + /// 54 slots) moves the stack and leaves the menu's state clean, so the + /// next quick move still moves its stack and the inventory still + /// answers. + #[test] + fn a_chest_quick_move_keeps_the_next_one_working() { + with_menu(Kind::Chest(6), |env, menu| { + menu.creative = false; + // The hotbar holds two stacks; the chest is empty. + menu.set_slot(env, 81, stack("cobblestone", 64)); + menu.set_slot(env, 82, stack("dirt", 32)); + // Shift+Right-Click on the hotbar: the stack goes into the chest. + menu.click(env, 81, 1, Input::QuickMove).unwrap(); + assert_eq!(menu.slot(81), None); + assert_eq!(menu.slot(0).map(|s| s.count), Some(64)); + // Nothing is left on the cursor and no quick craft is running. + assert_eq!(menu.carried, None); + assert_eq!(menu.quick_status, 0); + // The next quick move still works. + menu.click(env, 82, 1, Input::QuickMove).unwrap(); + assert_eq!(menu.slot(82), None); + assert_eq!(menu.slot(1).map(|s| s.count), Some(32)); + assert_eq!(menu.carried, None); + assert_eq!(menu.quick_status, 0); + }); + } } From 4e82a62489205c0ba7182c37baa47b142c916c8c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 00:01:54 +0100 Subject: [PATCH 25/65] Vexes hold their sword at the small size Java uses --- crates/horizon-client/src/mobs/render.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..8b316d8ba 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1235,6 +1235,15 @@ fn hand_base( 0.0 }; let mut t = part_matrix(model, base, poses, arm, offset)?; + if m.species() == Species::Vex { + // `VexModel.translateToHand`: the held item is drawn at 0.55 scale. + t *= glam::Mat4::from_scale(glam::Vec3::splat(0.55)); + t *= glam::Mat4::from_translation(glam::Vec3::new( + if left { -0.046_875 } else { 0.046_875 }, + -0.156_25, + 0.078_125, + )); + } let (ox, oy, oz) = if m.is_baby() { (0.0, 1.0, -4.5) } else { From 7ae20a5b294ebc8891ae8faabc42496c187356d3 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:07:36 +0500 Subject: [PATCH 26/65] A potion from the creative inventory keeps its contents in the hotbar #1832 reported that a potion taken from the creative inventory and put in the hotbar turned into the uncraftable potion. The hand-over keeps the stack as it is on `main` (#1796 and #1874), so this adds the test that keeps it that way: the item tab's stack is the real one, the creative screen hands it over unchanged, and the hotbar slot holds the brew. Fixes #1832 Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/menu.rs | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 3b2b8fd31..38186d170 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3211,4 +3211,37 @@ pub(crate) mod tests { assert_eq!(menu.slot(0), stack("dirt", 1).as_ref()); }); } + + /// #1832: a potion taken from the creative inventory and put in the + /// hotbar keeps its `PotionContents` (the brew), as vanilla's + /// `PotionContents.createItemStack` builds it: the item tab's stack is + /// the real one, and the hotbar slot holds it as it is. + #[test] + fn a_creative_potion_keeps_its_contents_in_the_hotbar() { + let snbt = r#"{components:{"minecraft:potion_contents":{potion:"minecraft:swiftness"}},count:1,id:"minecraft:potion"}"#; + let potion = crate::item_data::parse_stack(snbt).unwrap().unwrap(); + assert_eq!(potion.potion(), Some("minecraft:swiftness")); + // The creative screen hands the stack over... + let mut carried = None; + crate::creative::click_display( + &mut carried, + Some(&potion), + |_: &ItemStack| 1, + 0, + Input::Pickup, + ); + assert_eq!( + carried.as_ref().and_then(|s| s.potion()), + Some("minecraft:swiftness") + ); + // ... and the hotbar slot keeps it: it is not the uncraftable + // potion, which is a `minecraft:potion` with no contents at all. + with_menu(Kind::ItemPicker, |env, menu| { + menu.carried = carried; + menu.click(env, 45, 0, Input::Pickup).unwrap(); + let in_hand = menu.slot(45).expect("the hotbar slot"); + assert_eq!(in_hand.potion(), Some("minecraft:swiftness")); + assert_eq!(&*in_hand.item, "minecraft:potion"); + }); + } } From 4c9075a0729f4c3f5ec47428a87ac252c5566284 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:08:31 +0500 Subject: [PATCH 27/65] Keep the thrown-item reproduction for #1762 A server's client ticks a projectile itself between the entity tracker's updates, as vanilla's Entity no-op interpolation handler does; before #2086 it only eased towards the server's position, so a thrown egg, ender pearl or wind charge hung in the air for half a second. The client tick is now a named function with unit tests for that flight, and the parity harness keeps the reproduction the issue asked for: a connected client throws each of them and samples their position twice as often as the tracker's interval. The LAN harness can also run headless now (HORIZON_E2E_HEADLESS), so the games render offscreen and never pause on the focus loss on a machine with no focused window. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- .../src/game/remote_projectiles.rs | 79 +++++++++++++++++-- tools/lan_e2e.py | 12 ++- tools/test_remote_fireball_parity.py | 50 ++++++++++-- 3 files changed, 129 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..d896d12eb 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -77,6 +77,14 @@ fn remote_arrow_tick(p: &mut Projectile, w: &impl ProjectileWorld) { } p.velocity.y -= 0.05; } +/// A server's client ticks a projectile itself: it flies on between the +/// tracker's updates (10 to 20 ticks apart) with its own gravity and drag, +/// and a block stops it there; only the server decides what it hits. +pub(super) fn remote_projectile_tick(p: &mut Projectile, w: &impl ProjectileWorld) { + if !matches!(p.tick(w).1, Hit::None) { + p.velocity = Vec3::ZERO; + } +} impl Game<'_> { /// `handleAddEntity` for these types; false when `kind` isn't one. @@ -341,11 +349,7 @@ impl Game<'_> { p.age += 1; p.position = p.position.add_vector(p.velocity); } - _ => { - if !matches!(p.tick(&world).1, Hit::None) { - p.velocity = Vec3::ZERO; - } - } + _ => remote_projectile_tick(p, &world), } } } @@ -519,3 +523,68 @@ impl Game<'_> { out } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::mobs::Who; + use horizon_core::geometry::Aabb; + + /// A world with nothing in it: the client tick of a projectile only + /// needs the blocks around it. + struct Empty; + impl ProjectileWorld for Empty { + fn clip(&self, _: Vec3, _: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> { + None + } + fn in_water(&self, _: Vec3) -> bool { + false + } + fn targets(&self) -> &[(Who, Aabb)] { + &[] + } + } + + /// A thrown item, as a server's client tracks it: the spawn position and + /// the motion the server gave it. + fn thrown(kind: ProjectileKind) -> Projectile { + let mut p = Projectile::new(kind, Vec3::new(0.0, 100.0, 0.0), None); + p.velocity = Vec3::new(1.5, 0.0, 0.0); + p + } + + #[test] + fn a_thrown_item_flies_on_between_the_server_updates() { + // A thrown egg, an ender pearl and a wind charge (#1762): the server + // sends their position every 10 ticks, and the client ticks them + // itself in between, as vanilla's no-op interpolation handler does. + for kind in [ + ProjectileKind::Egg, + ProjectileKind::EnderPearl, + ProjectileKind::WindCharge, + ] { + let mut p = thrown(kind); + remote_projectile_tick(&mut p, &Empty); + assert!(p.position.x > 1.0, "the projectile did not fly on: {p:?}"); + // A second tick moves it further: it keeps flying, not a hop. + let first = p.position.x; + remote_projectile_tick(&mut p, &Empty); + assert!(p.position.x > first, "the projectile stopped: {p:?}"); + } + } + + #[test] + fn a_thrown_item_falls_and_drags_like_a_throwable_projectile() { + // ThrowableProjectile.tick: gravity 0.03, then the air drag 0.99. + let mut p = thrown(ProjectileKind::Egg); + remote_projectile_tick(&mut p, &Empty); + assert!((p.velocity.x - 1.5 * 0.99).abs() < 1e-9, "{p:?}"); + assert!((p.velocity.y - (-0.03 * 0.99)).abs() < 1e-9, "{p:?}"); + // A wind charge keeps its speed: no gravity and no drag + // (AbstractWindCharge: acceleration 0, inertia 1). + let mut p = thrown(ProjectileKind::WindCharge); + remote_projectile_tick(&mut p, &Empty); + assert!((p.velocity.x - 1.5).abs() < 1e-9, "{p:?}"); + assert!((p.velocity.y - 0.0).abs() < 1e-9, "{p:?}"); + } +} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 012e8f021..0086cecc9 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4743,9 +4743,17 @@ def run(ctl, out, resources, checks): host, guest = Game('host', ctl, resources), Game('guest', ctl, resources) # Either way explicitly: the game's default is the server thread. host.d.env['HORIZON_SERVER_THREAD'] = '1' if SERVER_THREAD else '0' + # A headless run (HORIZON_E2E_HEADLESS) has no focused window to draw in: the games render + # offscreen and never pause on the focus loss, or the world would stand still. + headless = bool(os.environ.get('HORIZON_E2E_HEADLESS')) + launch = ['launch'] + if headless or sys.platform == 'darwin': + launch.append('--offscreen') + if headless: + launch.append('--no-pause') results = {} try: - host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] + host.pid = host.raw(*launch)['pid'] # Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative # world has them; everyone plays in survival. host.raw('open', 'Lan', 5, 'creative') @@ -4759,7 +4767,7 @@ def run(ctl, out, resources, checks): host('command', command='gamerule spawn_mobs false') port = host.raw('lan', 'open', 0, 'commands')['port'] host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name - guest.pid = guest('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] + guest.pid = guest.raw(*launch)['pid'] guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) guest.raw('wait-for', 'loaded', '--timeout', 300) guest.wait(40) diff --git a/tools/test_remote_fireball_parity.py b/tools/test_remote_fireball_parity.py index 7e60ff30a..3969322f4 100644 --- a/tools/test_remote_fireball_parity.py +++ b/tools/test_remote_fireball_parity.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -"""A connected client advances ghast fireballs between tracker packets. +"""A connected client advances ghast fireballs and thrown items between tracker packets. -AbstractHurtingProjectile.tick/applyInertia run on clients as well as servers. -Like lan_e2e's falling-entity check, sample motion more often than the tracker -interval; an interpolation-only client stalls for most of that interval. +AbstractHurtingProjectile.tick/applyInertia run on clients as well as servers, and +a thrown item ticks itself on the client too. Like lan_e2e's falling-entity check, +sample motion more often than the tracker interval; an interpolation-only client +stalls for most of that interval (#1762). """ import json import math @@ -36,6 +37,44 @@ def check_motion(host, guest, out): return {'positions': samples} +def check_thrown(host, guest, out): + """A thrown egg, an ender pearl and a wind charge fly on between tracker packets. + + The server sends a thrown item's position every 10 ticks; a client that only + eased towards it hung in the air for half a second (#1762). Vanilla's client + ticks the projectile itself, as Entity's no-op interpolation handler does. + """ + x, y, z = (math.floor(v) for v in lan.pos_of(guest)) + for game in (host, guest): + game('command', command='gamemode survival') + results = {} + for item, kind in (('minecraft:egg', 'Egg'), ('minecraft:ender_pearl', 'EnderPearl'), + ('minecraft:wind_charge', 'WindCharge')): + # A clear lane along +X at the guest's eye height, with room to fall. + host('command', command=f'fill {x + 2} {y - 7} {z - 2} {x + 60} {y - 7} {z + 2} minecraft:stone') + host('command', command=f'fill {x + 2} {y - 6} {z - 2} {x + 60} {y + 3} {z + 2} minecraft:air') + guest('command', command=f'tp @s {x + 0.5:.2f} {y:.2f} {z + 0.5:.2f}') + guest.wait(20) + guest('command', command='clear @s') + guest('command', command=f'item replace entity @s weapon.mainhand with {item}') + guest.wait(10) + # The server throws along the rotation it has: let it arrive first. + guest.raw('look-at', f'{x + 40:.2f}', f'{y + 1.62:.2f}', f'{z + 0.5:.2f}') + guest.wait(5) + guest.raw('use-item') + samples = [] + for _ in range(6): + shots = [p for p in guest('status')['projectiles'] if p['kind'] == kind] + samples.append(shots[0]['position'][0] if shots else None) + guest.wait(2) + seen = [p for p in samples if p is not None] + moves = sum(b != a for a, b in zip(seen, seen[1:])) + results[item] = {'positions': samples, 'moves': moves} + assert len(seen) >= 4, f'{item} visible in only {len(seen)} samples: {samples}' + assert moves >= len(seen) - 2, f'{item} stalled between tracker updates: {samples}' + return results + + def main(): subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bin', 'horizon-client', '--bin', 'horizon-ctl'], cwd=lab.ROOT, check=True) @@ -43,6 +82,7 @@ def main(): ['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=lab.ROOT, text=True)) ctl = lab.ROOT / metadata['target_directory'] / 'fast' / 'horizon-ctl' lan.CHECK_FNS['remote-fireball'] = check_motion + lan.CHECK_FNS['remote-thrown'] = check_thrown # Use the runner's current display (xvfb on Linux), with fresh isolated homes. lan.game_env = lambda _screen, home: lab.game_env( HORIZON_HOME=home, HORIZON_TELEMETRY_URL='off') @@ -53,7 +93,7 @@ def main(): out = lab.LOCAL / 'remote-fireball-parity' / mode out.mkdir(parents=True, exist_ok=True) # lan.Game launches each client with lab.game_env and private scratch homes. - reports[mode] = lan.run(ctl, out, lab.RESOURCES.resolve(), ['remote-fireball']) + reports[mode] = lan.run(ctl, out, lab.RESOURCES.resolve(), ['remote-fireball', 'remote-thrown']) lab.write_json(lab.LOCAL / 'remote-fireball-parity' / 'report.json', reports) assert all(r['pass'] for mode in reports.values() for r in mode.values()), reports From e184ab7a424f4b1d9155c284a44bbada9244015c Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:35:26 +0500 Subject: [PATCH 28/65] A villager that loses its job site offers its new profession's trades The reported sequence in #1639: a villager works at a bench, the bench is destroyed and it takes another bench's job, and then it does not open a trading menu. `Villager.setVillagerData` drops the offers (`offers = null`) when the profession changes, so the next `AbstractVillager.getOffers` rolls the new profession's trade set. The brain reaches that through `set_profession`, which now also marks the offers as not made (#2009); this test covers the whole reported sequence, from the lost job site to the new profession's trades, so a villager that keeps the old profession's offers marked as made cannot pass it. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/mobs/villager.rs | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index aad0ec911..20280b190 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -905,6 +905,53 @@ mod tests { assert!(t.unset); assert_eq!(m.extra.variant2, 2); } + /// The reported sequence: a villager works at a bench, the bench is + /// destroyed (its job site is gone, so `ResetProfession` makes it + /// unemployed) and it takes another bench's job. The new profession's + /// trades are offered again. + /// + /// `Villager.setVillagerData` drops the offers (`offers = null`) when the + /// profession changes, so `AbstractVillager.getOffers` rolls the new + /// profession's trade set the next time the offers are asked for. A + /// villager that keeps its old offers marked as made never trades again: + /// it shakes its head instead of opening the trading menu. + #[test] + fn a_villager_that_loses_its_job_site_offers_its_new_profession_trades() { + let mut m = villager(); + // The composter's job: the villager is a farmer. + set_profession(&mut m, 5); + assert_eq!(m.extra.variant2, 5); + // Its trades were made, so the offers are there. + let trade = m.extra.trade.get_or_insert_default(); + trade.unset = false; + trade.offers = vec![crate::merchant::MerchantOffer { + base_cost_a: crate::merchant::ItemCost { + stack: ItemStack::new("minecraft:wheat", 20), + }, + cost_b: None, + result: ItemStack::new("minecraft:emerald", 1), + uses: 0, + max_uses: 16, + reward_exp: true, + special_price_diff: 0, + demand: 0, + price_multiplier: 0.0, + xp: 1, + }]; + // The work bench is destroyed: the job site is gone, so the villager + // is unemployed and its offers are dropped (`offers = null`). + set_profession(&mut m, NONE); + let t = m.extra.trade.as_ref().unwrap(); + assert!(t.offers.is_empty()); + assert!(t.unset); + // It takes the smithing table's job. The new profession's trades are + // rolled by the next `getOffers` (ensure_offers). + set_profession(&mut m, 13); + let t = m.extra.trade.as_ref().unwrap(); + assert!(t.offers.is_empty()); + assert!(t.unset); + assert_eq!(m.extra.variant2, 13); + } fn stack(item: &str, count: u32) -> ItemStack { ItemStack::new(item, count) From b1450f1ef283e5f3902f43a775e080388ade2691 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 23:51:40 +0100 Subject: [PATCH 29/65] Mobs: foxes, rabbits, goats and horses keep their state finalizeSpawn picks a fox's type (red or snow), a rabbit's type, a goat's screaming flag and horns and a horse's max health, but the save and the load did not keep them: a snow fox came back red, every rabbit brown, a goat that had lost a horn grew it back, and a new horse was saved with the type's health (53) above the max health it rolled. - Fox, Rabbit and Goat.addAdditionalSaveData: Type, RabbitType, IsScreamingGoat, HasLeftHorn and HasRightHorn are saved from the model and read back (an unknown rabbit type is brown, horns default to present, as vanilla reads them). - The fields Horizon does not model (a fox's Trusted, Sleeping, Sitting, Crouching, a rabbit's MoreCarrotTicks, a horse's EatingHaystack and Bred) keep a loaded value or get vanilla's default. - A loaded horse or llama gets its health clamped to its max health, as LivingEntity.setHealth does. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 103 ++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 8926b3bbe..8918c4b2d 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -244,6 +244,32 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { ); } match id { + // Fox.addAdditionalSaveData; Horizon models only the type. + "minecraft:fox" => { + let kind = if m.extra.variant == 1 { "snow" } else { "red" }; + map.insert("Type".into(), string(kind)); + for (key, value) in [ + ("Trusted", Tag::List(Vec::new())), + ("Sleeping", Tag::Byte(0)), + ("Sitting", Tag::Byte(0)), + ("Crouching", Tag::Byte(0)), + ] { + map.entry(key.into()).or_insert(value); + } + } + "minecraft:rabbit" => { + map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant))); + map.entry("MoreCarrotTicks".into()).or_insert(Tag::Int(0)); + } + "minecraft:goat" => { + map.insert( + "IsScreamingGoat".into(), + Tag::Byte(i8::from(m.extra.screaming)), + ); + let [left, right] = m.extra.lost_horns; + map.insert("HasLeftHorn".into(), Tag::Byte(i8::from(!left))); + map.insert("HasRightHorn".into(), Tag::Byte(i8::from(!right))); + } "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { map.entry(key.into()).or_insert(value); @@ -298,6 +324,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { | "minecraft:trader_llama" => { map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame))); map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3))); + // AbstractHorse.addAdditionalSaveData; Horizon models neither. + for key in ["EatingHaystack", "Bred"] { + map.entry(key.into()).or_insert(Tag::Byte(0)); + } if let Some(owner) = m.extra.owner { map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); } @@ -669,6 +699,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } } m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); + // LivingEntity.setHealth clamps to the max health: a horse or llama is made + // with the type's and saved before it drops to the one it rolled. (Only + // the base is read here, so the clamp would cut a leader zombie's bonus.) + if crate::mobs::equine::is_equine(m.species()) { + m.health = m.health.min(m.attrs.max_health); + } m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. if let Some(eq) = tag.get("equipment") { @@ -818,6 +854,24 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - let sounds = crate::mobs::finalize::sound_variants(m.species()); m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8); } + match m.species() { + crate::mobs::Species::Fox => { + m.extra.variant = u8::from(text(tag.get("Type")).as_deref() == Some("snow")); + } + crate::mobs::Species::Rabbit => { + // Rabbit.Variant.byId: an unknown id is brown. + m.extra.variant = match number(tag.get("RabbitType")).unwrap_or(0) { + v @ (0..=5 | 99) => v as u8, + _ => 0, + }; + } + crate::mobs::Species::Goat => { + m.extra.screaming = flag(tag, "IsScreamingGoat"); + let horn = |key| number(tag.get(key)).is_some_and(|v| v == 0); + m.extra.lost_horns = [horn("HasLeftHorn"), horn("HasRightHorn")]; + } + _ => {} + } if m.species() == crate::mobs::Species::Cat { m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); m.extra.tame = m.extra.owner.is_some(); @@ -2502,6 +2556,55 @@ mod sheep_nbt_tests { ); } } + + #[test] + fn foxes_rabbits_and_goats_keep_their_kind() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let new = |kind: &str| Mob::new(1, types[kind].clone(), Vec3::new(0.0, 4.0, 0.0), 0.0); + let round_trip = |m: &Mob| { + let tag = mob_to_nbt(m, [1, 2, 3, 4], None); + (mob_from_nbt(&tag, &types, 2).unwrap(), tag) + }; + let mut fox = new("minecraft:fox"); + fox.extra.variant = 1; + let (back, tag) = round_trip(&fox); + assert_eq!(text(tag.get("Type")).as_deref(), Some("snow")); + assert_eq!(number(tag.get("Sleeping")), Some(0)); + assert_eq!(back.extra.variant, 1); + let mut rabbit = new("minecraft:rabbit"); + rabbit.extra.variant = 4; + let (back, tag) = round_trip(&rabbit); + assert_eq!(number(tag.get("RabbitType")), Some(4)); + assert_eq!(back.extra.variant, 4); + let mut goat = new("minecraft:goat"); + (goat.extra.screaming, goat.extra.lost_horns) = (true, [false, true]); + let (back, tag) = round_trip(&goat); + assert_eq!(number(tag.get("HasRightHorn")), Some(0)); + assert_eq!( + (back.extra.screaming, back.extra.lost_horns), + (true, [false, true]) + ); + // A goat saved without horn flags has both, as vanilla reads it. + let bare = Tag::compound([ + ("id", string("minecraft:goat")), + ("Pos", doubles(&[0.5, 64.0, 0.5])), + ]); + assert_eq!( + mob_from_nbt(&bare, &types, 3).unwrap().extra.lost_horns, + [false; 2] + ); + } } #[cfg(test)] From 731a35612addaf322fe04149c4a5d15f5498d650 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:38:01 +0500 Subject: [PATCH 30/65] Lock the benchmark's load gate: a scene waits for the chunks The benchmark's readiness rule waits for the resident chunk count to reach the view's target before "steady" means loaded, so a scene that starts with an empty view (the integrated server has not sent its first chunk yet) is measured after the world is really there. The rule had no test, so a change could silently drop it. This adds one: a fake control that keeps the counts steady and the queue empty for a second and a half, and only then lets the chunks arrive, must not end the wait before they do. Without the gate the wait ends after the quiet second and the test fails. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/benchmark.rs | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs index 12e38e78a..bd2e97be0 100644 --- a/crates/horizon-client/src/benchmark.rs +++ b/crates/horizon-client/src/benchmark.rs @@ -450,6 +450,54 @@ mod tests { assert_eq!(view_chunks(32), 2573); assert_eq!(view_chunks(0), 0); } + /// The status a fake control answers with: the player is where it should + /// be, nothing is queued, and the world holds `chunks` resident chunks. + fn status(chunks: u64) -> String { + serde_json::json!({ + "player": {"position": [0.0, 64.0, 0.0]}, + "pending_chunks": 0, + "screen": "playing", + "render_distance": 12, + "chunks": chunks, + "generated_chunks": chunks, + "meshed_sections": 0, + "streaming": {}, + }) + .to_string() + } + + #[test] + fn the_load_waits_for_the_chunks_a_teleport_starts() { + // Right after a teleport the game reports steady counts and nothing + // queued for over a second, before the integrated server has sent the + // first chunk: the quiet rule alone would call that loaded, and the + // scene would be measured over an empty view (#1749). + const LATE: usize = 30; + let (tx, rx) = mpsc::channel::(); + let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counted = std::sync::Arc::clone(&polls); + let server = thread::spawn(move || { + let mut seen = 0; + while let Ok(request) = rx.recv() { + if request.line == "status" { + let chunks = if seen < LATE { 0 } else { 400 }; + seen += 1; + counted.store(seen, std::sync::atomic::Ordering::SeqCst); + let _ = request.reply.send(status(chunks)); + } else { + let _ = request.reply.send("{}".to_owned()); + } + } + }); + let control = Control(tx); + wait_loaded(&control, |_| true).expect("the scene loads"); + assert!( + polls.load(std::sync::atomic::Ordering::SeqCst) > LATE, + "the load finished before the chunks arrived" + ); + drop(control); + let _ = server.join(); + } #[test] fn yaw_matches_vanilla() { From e11471cda092a0c26e90ac486fa22f35287aa49e Mon Sep 17 00:00:00 2001 From: "minimax-m3.1-flash" Date: Tue, 27 Oct 2026 04:38:22 +0500 Subject: [PATCH 31/65] Run the LAN harness headless HORIZON_E2E_HEADLESS launches the games with --offscreen --no-pause, so the suite runs on a machine with no focused window: without it the games pause on the focus loss and wait_ready never completes. macOS keeps its offscreen launch. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- tools/lan_e2e.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 012e8f021..80de9e955 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4743,9 +4743,18 @@ def run(ctl, out, resources, checks): host, guest = Game('host', ctl, resources), Game('guest', ctl, resources) # Either way explicitly: the game's default is the server thread. host.d.env['HORIZON_SERVER_THREAD'] = '1' if SERVER_THREAD else '0' + # The games render offscreen on macOS (a locked session gets no redraws) and, in a + # headless run (HORIZON_E2E_HEADLESS), on any machine with no focused window: they + # never pause on the focus loss there either, or the world would stand still. + headless = bool(os.environ.get('HORIZON_E2E_HEADLESS')) + launch = ['launch'] + if sys.platform == 'darwin' or headless: + launch.append('--offscreen') + if headless: + launch.append('--no-pause') results = {} try: - host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] + host.pid = host.raw(*launch)['pid'] # Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative # world has them; everyone plays in survival. host.raw('open', 'Lan', 5, 'creative') @@ -4759,7 +4768,7 @@ def run(ctl, out, resources, checks): host('command', command='gamerule spawn_mobs false') port = host.raw('lan', 'open', 0, 'commands')['port'] host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name - guest.pid = guest('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] + guest.pid = guest.raw(*launch)['pid'] guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) guest.raw('wait-for', 'loaded', '--timeout', 300) guest.wait(40) From 5be7c02d0cfbdd43a90c9c79a48d1edb3da9df05 Mon Sep 17 00:00:00 2001 From: "minimax-m3.1-flash" Date: Tue, 27 Oct 2026 04:38:22 +0500 Subject: [PATCH 32/65] Cover the mining dig stop in the LAN harness (#1340, #1908) A block the client breaks at once (a creative break, a dead bush) sends no STOP or ABORT, so the server has to forget the dig itself. Without it the server keeps mining the emptied cell: the block put back there is destroyed again (#1340) and the mining sound keeps playing at it (#1908, the cell's sound group is stone). The new dig_stop check breaks a stone block in creative and a dead bush in survival for the host and the guest, then puts the block back and waits: it must stay, and no mining sound may play. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- tools/lan_e2e.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 80de9e955..92ecb4ead 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -259,6 +259,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - instant_digging: an instant survival break leaves no repeated stone hit sounds or stale server dig (#1908). - replant: flowers and crops replanted after a short harvest click stay planted for both players; the server forgets the completed instant break (#1880). +- dig_stop: a block the client breaks at once (a creative break, a dead bush) leaves the + server no dig to keep: the block put back stays and no mining sound plays on (#1340, #1908). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -7345,5 +7347,56 @@ CHECKS += ['forced-levels'] CHECK_FNS['forced-levels'] = check_forced_levels +def check_dig_stop(host, guest, out): + """#1340 and #1908: a block the client breaks at once leaves the server no dig to keep. + + MultiPlayerGameMode sends no STOP or ABORT for a creative break or an instant + survival break (its isDestroying stays false), so the server must forget the dig on + its own, as ServerPlayerGameMode.handleBlockBreakAction's creative and insta-mine + branches do. Otherwise the server keeps mining the old spot: the block put back + there is destroyed again (#1340) and the mining sound keeps playing at it (#1908). + """ + result = {} + spots = apart(host, guest) + for label, player in (('host', host), ('guest', guest)): + x, y, z = spots[label] + cell = (x, y + 1, z + 2) + seen = result[label] = {} + for mode, block in (('creative', 'minecraft:stone'), ('survival', 'minecraft:dead_bush')): + player('command', command=f'gamemode {mode}') + player('command', command='clear @s') + host('command', command=f'fill {x - 1} {y} {z + 1} {x + 1} {y + 3} {z + 4} minecraft:air') + host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} {block}') + player.wait(10) + before = {g.name: heard(g, 'minecraft:block.stone.hit') for g in (host, guest)} + player.raw('look-at', f'{cell[0] + 0.5:.2f}', f'{cell[1] + 0.4:.2f}', f'{cell[2] + 0.5:.2f}') + # One left-click, then the attack released. + player.raw('mouse', 'left', 'click') + player.wait(40) + seen[f'{mode} broken'] = host.raw('block', *cell).get('block') + seen[f'{mode} mining'] = player('state').get('mining') + # The block put back must stay: the server has no dig left to destroy it. + host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(100) + seen[f'{mode} replacement'] = [g.raw('block', *cell).get('block') for g in (host, player)] + seen[f'{mode} hits'] = {g.name: heard(g, 'minecraft:block.stone.hit') - before[g.name] + for g in (host, guest)} + host('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:air') + assert seen['creative broken'] == 'minecraft:air', f'{label}: the creative break failed: {seen}' + assert seen['survival broken'] == 'minecraft:air', f'{label}: the instant break failed: {seen}' + assert seen['creative mining'] is None, f'{label}: the client still digs: {seen}' + assert seen['survival mining'] is None, f'{label}: the client still digs: {seen}' + for mode in ('creative', 'survival'): + assert seen[f'{mode} replacement'] == ['minecraft:stone'] * 2, \ + f'{label} {mode}: the server kept digging: {seen}' + assert all(hits == 0 for hits in seen[f'{mode} hits'].values()), \ + f'{label} {mode}: the mining sound kept playing: {seen}' + return result + + +CHECKS += ['dig_stop'] +CHECK_FNS['dig_stop'] = check_dig_stop + + if __name__ == '__main__': main() From fa4f38f824dd4f5536eb62d221ce8835c53db3cf Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 05:01:07 +0500 Subject: [PATCH 33/65] commands: an unbounded selector reaches the other loaded levels `Game::select` gathered its candidates from the level in place only, so `@e[tag=...]` never found an entity in another dimension the server still holds: vanilla's `EntitySelector` searches every loaded level unless the selector carries a spatial constraint. The selector now searches each loaded level in turn, and the commands that act on the entity it found (`/data get entity`, `/kill`, `/tp`) act on it in the level that holds it. The experience orbs and the projectiles are named by their entity id, like the other entities, so the entity a command acts on is the one the selector found. Fixes #1524 Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/command/args.rs | 8 + crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/game/commands.rs | 263 ++++++++++++------ .../horizon-client/src/game/commands/data.rs | 28 +- crates/horizon-client/src/game/creatures.rs | 15 +- crates/horizon-client/src/game/crossbow.rs | 2 +- crates/horizon-client/src/game/dispenser.rs | 2 +- crates/horizon-client/src/game/levels.rs | 4 + crates/horizon-client/src/game/persist.rs | 4 +- .../src/game/remote_projectiles.rs | 2 +- crates/horizon-client/src/game/wind.rs | 2 +- tools/command_exec_corpus.py | 12 +- 12 files changed, 248 insertions(+), 96 deletions(-) diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index ccced67a7..d9528d3f2 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -551,6 +551,14 @@ impl Selector { pub fn single(&self) -> bool { self.limit <= 1 } + /// `EntitySelectorParser.setWorldLimited`: a selector with a spatial + /// constraint (`distance` or a position) reaches the level the command + /// runs in only; an unbounded one reaches every loaded level. + pub fn world_limited(&self) -> bool { + self.distance.is_some() + || self.pos.iter().any(Option::is_some) + || self.delta.iter().any(Option::is_some) + } } #[derive(Clone, Debug, PartialEq)] pub struct BlockInput { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index db49087b2..a154c7a18 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9598,7 +9598,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); self.player_projectile_shot(); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..f79480428 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -42,9 +42,10 @@ pub(super) enum Target { Guest(u32), Mob(u32), Item(u32), - Orb(usize), - /// By index in `creatures.projectiles`. - Projectile(usize), + /// An experience orb, by its entity id. + Orb(u32), + /// A projectile, by its entity id. + Projectile(u32), Stand(u32), Frame(u32), Painting(u32), @@ -340,14 +341,16 @@ impl Game<'_> { .iter() .find(|i| i.id == id) .map(|i| [i.position.x, i.position.y, i.position.z]), - Target::Orb(i) => self + Target::Orb(id) => self .orbs - .get(i) + .iter() + .find(|o| o.id == id) .map(|o| [o.position.x, o.position.y, o.position.z]), - Target::Projectile(i) => self + Target::Projectile(id) => self .creatures .projectiles - .get(i) + .iter() + .find(|a| a.id == id) .map(|a| [a.position.x, a.position.y, a.position.z]), Target::Stand(id) => self .armor_stands @@ -399,10 +402,11 @@ impl Game<'_> { }), Target::Item(_) => "minecraft:item".into(), Target::Orb(_) => "minecraft:experience_orb".into(), - Target::Projectile(i) => self + Target::Projectile(id) => self .creatures .projectiles - .get(i) + .iter() + .find(|p| p.id == id) .map_or_else(String::new, |p| p.kind.id().into()), Target::Stand(_) => "minecraft:armor_stand".into(), Target::Frame(id) => { @@ -512,51 +516,72 @@ impl Game<'_> { s.pos[2].unwrap_or(p[2]), ] }; - let mut candidates: Vec = Vec::new(); + let mut source_candidates: Vec = Vec::new(); match (s.kind, self.command_source) { // @s: the executing entity (none for a server source). - ('s', Some(source)) => candidates.extend(source.entity), - ('s', None) => candidates.extend(self.source_entity()), + ('s', Some(source)) => source_candidates.extend(source.entity), + ('s', None) => source_candidates.extend(self.source_entity()), // A guest in place is among the players, in join order. _ if self.player.is_some() && self.lan_acting.is_none() => { - candidates.push(Target::Player); + source_candidates.push(Target::Player); } _ => {} } if s.kind != 's' { - use horizon_client::projectiles::ProjectileKind as K; - candidates.extend(self.player_candidates(s)); - candidates.extend( - self.mobs - .iter() - .filter(|m| m.death_time == 0) - .map(|m| Target::Mob(m.id)), - ); - candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id))); - candidates.extend((0..self.orbs.len()).map(Target::Orb)); - candidates.extend( - self.creatures - .projectiles - .iter() - .enumerate() - // The kinds /data can write (entity_nbt). - .filter(|(_, p)| { - p.arrow.is_some() - || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) - }) - .map(|(i, _)| Target::Projectile(i)), - ); - candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id))); - candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id))); - candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); - candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); - candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); - candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); + source_candidates.extend(self.player_candidates(s)); } + let source_dim = self.dim; + // A selector with a spatial constraint reaches the level the command + // runs in only; an unbounded one reaches every loaded level + // (EntitySelector.findEntities). + let dims = if s.world_limited() { + vec![source_dim] + } else { + self.loaded_dims() + }; + let mut out: Vec<(Target, f64)> = Vec::new(); + for dim in dims { + let back = self.enter_command_level(dim); + let mut candidates = Vec::new(); + if dim == source_dim { + candidates.append(&mut source_candidates); + } + if s.kind != 's' { + candidates.extend(self.level_candidates()); + } + out.extend(self.select_in_level(candidates, s, origin)); + if let Some(back) = back { + self.enter_command_level(back); + } + } + match s.sort { + Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)), + Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)), + Sort::Random => { + for i in (1..out.len()).rev() { + let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + out.swap(i, j); + } + } + Sort::Arbitrary => {} + } + out.into_iter() + .take(s.limit.max(1)) + .map(|(t, _)| t) + .collect() + } + /// The candidates of the level in place that pass the selector + /// (EntitySelector.getPredicate). + fn select_in_level( + &mut self, + candidates: Vec, + s: &Selector, + origin: [f64; 3], + ) -> Vec<(Target, f64)> { let level = self.experience.level; let creative = self.creative; let passing = self.selector_extra_filter(&candidates, s); - let mut out: Vec<(Target, f64)> = candidates + candidates .into_iter() .filter_map(|t| { let p = self.target_position(t)?; @@ -628,23 +653,95 @@ impl Game<'_> { } Some((t, d2)) }) - .collect(); - match s.sort { - Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)), - Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)), - Sort::Random => { - for i in (1..out.len()).rev() { - let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; - out.swap(i, j); - } - } - Sort::Arbitrary => {} - } - out.into_iter() - .take(s.limit.max(1)) - .map(|(t, _)| t) .collect() } + /// The entities of the level in place a selector can find. + fn level_candidates(&self) -> Vec { + use horizon_client::projectiles::ProjectileKind as K; + let mut candidates = Vec::new(); + candidates.extend( + self.mobs + .iter() + .filter(|m| m.death_time == 0) + .map(|m| Target::Mob(m.id)), + ); + candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id))); + candidates.extend(self.orbs.iter().map(|o| Target::Orb(o.id))); + candidates.extend( + self.creatures + .projectiles + .iter() + // The kinds /data can write (entity_nbt). + .filter(|p| { + p.arrow.is_some() + || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) + }) + .map(|p| Target::Projectile(p.id)), + ); + candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id))); + candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id))); + candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); + candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); + candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); + candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); + candidates + } + /// The loaded levels, in the order the server holds them: the + /// overworld, the nether, the end (MinecraftServer.getAllLevels). + fn loaded_dims(&self) -> Vec { + let mut dims = vec![self.dim]; + dims.extend(self.levels.parked_dims()); + dims.sort_by_key(|d| match d { + Dim::Overworld => 0, + Dim::Nether => 1, + Dim::End => 2, + }); + dims + } + /// Whether the level in place holds the entity a target names. + fn level_holds(&self, t: Target) -> bool { + match t { + // A player is in no level of its own. + Target::Player | Target::Guest(_) => true, + Target::Mob(id) => self.mobs.iter().any(|m| m.id == id), + Target::Item(id) => self.dropped.iter().any(|i| i.id == id), + Target::Orb(id) => self.orbs.iter().any(|o| o.id == id), + Target::Projectile(id) => self.creatures.projectiles.iter().any(|p| p.id == id), + Target::Stand(id) => self.armor_stands.iter().any(|a| a.id == id), + Target::Frame(id) => self.item_frames.iter().any(|f| f.id == id), + Target::Painting(id) => self.paintings.iter().any(|p| p.id == id), + Target::Boat(id) => self.boats.iter().any(|b| b.id == id), + Target::Cart(id) => self.carts.iter().any(|c| c.id == id), + Target::Other(id) => self.others.iter().any(|o| o.id == id), + } + } + /// Run `f` with the level that holds the entity a target names in place + /// (the entity ids are unique across the loaded levels) and put the + /// level back afterwards. `f` does not run when no level holds the + /// entity. + pub(in crate::game) fn in_target_level( + &mut self, + t: Target, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + if self.level_holds(t) { + return Some(f(self)); + } + for dim in self.levels.parked_dims() { + let back = self.enter_command_level(dim); + if self.level_holds(t) { + let r = f(self); + if let Some(back) = back { + self.enter_command_level(back); + } + return Some(r); + } + if let Some(back) = back { + self.enter_command_level(back); + } + } + None + } fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool { let path = self.options.resources.join(format!( "data/minecraft/tags/entity_type/{}.json", @@ -1104,6 +1201,10 @@ impl Game<'_> { Ok(targets.len() as i32) } fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { + // An entity in another level is teleported in the level that holds it. + let _ = self.in_target_level(t, |g| g.teleport_to_in_level(t, pos, rotation)); + } + fn teleport_to_in_level(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { let v = Vec3::new(pos[0], pos[1], pos[2]); match t { Target::Guest(_) => { @@ -1152,14 +1253,14 @@ impl Game<'_> { i.previous = v; } } - Target::Orb(i) => { - if let Some(o) = self.orbs.get_mut(i) { + Target::Orb(id) => { + if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) { o.position = v; o.previous = v; } } - Target::Projectile(i) => { - if let Some(a) = self.creatures.projectiles.get_mut(i) { + Target::Projectile(id) => { + if let Some(a) = self.creatures.projectiles.iter_mut().find(|a| a.id == id) { a.position = v; a.previous = v; } @@ -1558,6 +1659,10 @@ impl Game<'_> { Ok(duration.unwrap_or(-1)) } fn kill_target(&mut self, t: Target) { + // An entity in another level is killed in the level that holds it. + let _ = self.in_target_level(t, |g| g.kill_target_in_level(t)); + } + fn kill_target_in_level(&mut self, t: Target) { match t { Target::Guest(_) => { self.for_player(t, |g| g.kill_target(Target::Player)); @@ -1577,16 +1682,13 @@ impl Game<'_> { } } Target::Item(id) => self.dropped.retain(|i| i.id != id), - Target::Orb(i) => { - if i < self.orbs.len() { - self.orbs[i].age = u32::MAX / 2; + Target::Orb(id) => { + if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) { + o.age = u32::MAX / 2; } } - // cmd_kill goes from the highest index down. - Target::Projectile(i) => { - if i < self.creatures.projectiles.len() { - self.creatures.projectiles.remove(i); - } + Target::Projectile(id) => { + self.creatures.projectiles.retain(|p| p.id != id); } Target::Stand(id) => self.armor_stands.retain(|a| a.id != id), Target::Frame(id) => self.item_frames.retain(|f| f.id != id), @@ -1595,6 +1697,8 @@ impl Game<'_> { Target::Cart(id) => self.carts.retain(|c| c.id != id), Target::Other(id) => self.others.retain(|o| o.id != id), } + // The orbs marked for removal are gone (Entity.kill removes them). + self.orbs.retain(|o| o.age < u32::MAX / 2); } fn cmd_kill(&mut self, ctx: &Context) -> R { let targets = if ctx.get("targets").is_some() { @@ -1602,19 +1706,18 @@ impl Game<'_> { } else { vec![self.implied_player()] }; - let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect(); - // Remove indexed entities from the back so earlier indices stay valid. - let mut ordered = targets.clone(); - ordered.sort_by_key(|t| { - std::cmp::Reverse(match t { - Target::Orb(i) | Target::Projectile(i) => *i, - _ => 0, - }) - }); - for t in ordered { + let mut names: Vec = Vec::new(); + for &t in &targets { + // The name of an entity in another level is read there. + let name = match self.in_target_level(t, |g| g.target_name(t)) { + Some(name) => name, + None => self.target_name(t), + }; + names.push(name); + } + for &t in &targets { self.kill_target(t); } - self.orbs.retain(|o| o.age < u32::MAX / 2); let message = if targets.len() == 1 { Text::translate("commands.kill.success.single", &[names[0].clone()]) } else { diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index ac16c5e7c..6dc5b6a75 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -31,8 +31,13 @@ fn set_key(tag: &mut Tag, key: &str, value: Tag) { impl Game<'_> { // ---- entity data --------------------------------------------------- - /// `NbtPredicate.getEntityTagToCompare`: the entity as saved. + /// `NbtPredicate.getEntityTagToCompare`: the entity as saved. An entity + /// in another level is read in the level that holds it. pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option { + self.in_target_level(t, |g| g.entity_nbt_in_level(t)) + .flatten() + } + fn entity_nbt_in_level(&mut self, t: Target) -> Option { let player_uuid = self.level.player_uuid; Some(match t { Target::Guest(_) => { @@ -113,9 +118,11 @@ impl Game<'_> { let o = self.others.iter().find(|o| o.id == id)?.clone(); self.other_to_nbt(&o, uuid) } - Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()), - Target::Projectile(i) => { - let p = self.creatures.projectiles.get(i)?; + Target::Orb(id) => { + entity_nbt::orb_to_nbt(self.orbs.iter().find(|o| o.id == id)?, random_uuid()) + } + Target::Projectile(id) => { + let p = self.creatures.projectiles.iter().find(|p| p.id == id)?; let owner = if p.owner == Some(horizon_client::mobs::Who::Player) { player_uuid } else { @@ -397,6 +404,19 @@ impl Game<'_> { } pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R { let target = self.data_ref(ctx, 0)?; + // An entity in another level is read and written in the level that + // holds it. + if let DataRef::Entity(t) = &target { + let t = *t; + let target = target.clone(); + return match self.in_target_level(t, |g| g.cmd_data_in(id, ctx, target)) { + Some(r) => r, + None => Err(err("argument.entity.notfound.entity", &[])), + }; + } + self.cmd_data_in(id, ctx, target) + } + fn cmd_data_in(&mut self, id: &str, ctx: &Context, target: DataRef) -> R { match id { "data.merge" => { let Some(Arg::Str(nbt)) = ctx.get("nbt") else { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e895cb7f7..a5fb497d7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -892,6 +892,15 @@ impl Game<'_> { self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); } } + /// Adds a projectile, giving it an id from the entity counter + /// (`Entity.id`, the same counter as the rest) when it has none. + pub(super) fn add_projectile(&mut self, mut p: horizon_client::projectiles::Projectile) { + if p.id == 0 { + self.next_entity += 1; + p.id = self.next_entity; + } + self.creatures.projectiles.push(p); + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { @@ -1078,7 +1087,7 @@ impl Game<'_> { self.next_entity += 1; p.id = self.next_entity; let (owner, at) = (p.owner, [p.position.x, p.position.y, p.position.z]); - self.creatures.projectiles.push(p); + self.add_projectile(p); self.projectile_event("minecraft:projectile_shoot", owner, at); } MobEvent::Spawn(mut m) => { @@ -2160,7 +2169,7 @@ impl Game<'_> { } } if keep { - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); } } /// `TargetBlock.onProjectileHit`: a target block takes its power from @@ -3162,7 +3171,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(proj); + self.add_projectile(proj); self.player_projectile_shot(); // ItemStack.use's applyAfterUseComponentSideEffects: the pearl's // second is the `use_cooldown` component, as for any thrown item. diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index bc49c4b90..d66610183 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -222,7 +222,7 @@ impl Game<'_> { a.pierce = pierce; } arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); } self.player_projectile_shot(); let pitch = if index == 0 { diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 61725c6ab..670750f63 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1034,7 +1034,7 @@ impl Game<'_> { a.pickup = horizon_client::arrows::Pickup::Allowed; } shot.shoot(&mut own, dir, power, uncertainty); - self.creatures.projectiles.push(shot); + self.add_projectile(shot); } } } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 29bf6d511..d41485e2d 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -120,6 +120,10 @@ impl Levels { .iter_mut() .map(|(d, p)| (*d, &mut p.world.chunks)) } + /// The levels that are not in place, by dimension. + pub(super) fn parked_dims(&self) -> Vec { + self.parked.keys().copied().collect() + } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index b5e650e70..09622cf18 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -193,12 +193,12 @@ impl Game<'_> { if let Some(a) = p.arrow.as_mut() { a.last_state = in_block.and_then(|t| self.state_from_nbt(&t)); } - self.creatures.projectiles.push(p); + self.add_projectile(p); } } "minecraft:fireball" | "minecraft:small_fireball" => { if let Some(p) = entity_nbt::fireball_from_nbt(&tag, player_uuid) { - self.creatures.projectiles.push(p); + self.add_projectile(p); } } "minecraft:falling_block" => { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..52210cf3d 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -166,7 +166,7 @@ impl Game<'_> { p.velocity = velocity; p.yaw = yaw; p.pitch = pitch; - self.creatures.projectiles.push(p); + self.add_projectile(p); } } true diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index fb24102ba..63ac2641d 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -68,7 +68,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(proj); + self.add_projectile(proj); let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); self.audio .play("minecraft:entity.wind_charge.throw", Some(eye), 0.5, pitch); diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index d8f925ef0..c3f579772 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -533,13 +533,21 @@ def execute(): def levels(): """A nether portal round trip: on the way back the Overworld's entities (the - pig left by `entities`) are found and a summon names what it summoned.""" + pig left by `entities`) are found and a summon names what it summoned. An + unbounded selector also reaches the level the player is not in, while a + bounded one does not.""" return [ *setup('/fill 2 231 12 5 236 12 minecraft:obsidian', '/fill 3 232 12 4 235 12 minecraft:nether_portal[axis=x]', - '/tp @s 3.5 232 12.5 0 0'), + '/tp @s 3.5 232 12.5 0 0', + # A cow in the Overworld, in a chunk that stays loaded while the + # player is in the nether. + '/forceload add 0 0', + '/summon minecraft:cow 10.5 210 4.5 {NoAI:1b,NoGravity:1b,Tags:["remote_cow"]}'), {'op': 'portal'}, {'op': 'settle'}, cmd('/execute if dimension minecraft:the_nether run say through the portal'), + cmd('/data get entity @e[tag=remote_cow,limit=1] Pos'), + cmd('/data get entity @e[tag=remote_cow,distance=..128,limit=1] Pos'), {'op': 'portal'}, {'op': 'settle'}, cmd('/execute if dimension minecraft:overworld run say back through the portal'), From 76bebec833470750b47644a97ebdd79539778cae Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 01:01:53 +0100 Subject: [PATCH 34/65] Stop vexes suffocating inside blocks --- crates/horizon-client/src/mobs/ai.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 3406c09d7..e1951aa66 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -520,14 +520,19 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } m.first_tick = false; if m.alive() { - // LivingEntity.baseTick: suffocation inside full blocks. + // LivingEntity.baseTick: suffocation inside full blocks. Entity.isInWall + // is false under noPhysics, which Vex.tick holds while it ticks. let (ex, ey, ez) = ( m.position.x.floor() as i32, m.eye_y().floor() as i32, m.position.z.floor() as i32, ); let at_eye = w.facts.get(w.world.block(ex, ey, ez)); - if at_eye.full_collision && at_eye.solid_render && m.width() < 1.0 { + if at_eye.full_collision + && at_eye.solid_render + && m.width() < 1.0 + && m.species() != Species::Vex + { m.damage(1.0, Damage::of(DamageKind::InWall)); } // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). From 498de72da2ffa7a6726f32104540f3d4a16e6312 Mon Sep 17 00:00:00 2001 From: "minimax-m3.1-flash" Date: Tue, 27 Oct 2026 04:59:19 +0500 Subject: [PATCH 35/65] Frog: walk at vanilla's speed Vanilla's frog uses a SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true), so a walking frog covers 0.1 blocks a tick (its movement speed attribute is 1.0 and the controller's outside-water speed is 0.1). Horizon gave every generic animal the plain ground controller, which drives the mob at the attribute itself: a frog walked ten times too fast, jittered, teleported and flew (#2213). The regression test fails without the change. --- crates/horizon-client/src/mobs/ai.rs | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 3406c09d7..3abedea5f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -186,6 +186,20 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Turtle { super::turtle::register(m); } + if m.species() == Species::Frog { + // `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). + // The frog's movement speed is 1.0, so the controller's 0.1 + // outside-water speed is what keeps a walking frog at + // vanilla's pace; the plain ground controller walks ten + // times too fast (#2213). + m.ai.mov.kind = super::control::MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + }; + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -1701,3 +1715,41 @@ mod despawn_tests { } } } + +#[cfg(test)] +mod frog_tests { + use super::*; + use crate::mobs::MobTypes; + use crate::mobs::control::MoveKind; + use std::sync::Arc; + + /// `Frog()`: `new SmoothSwimmingMoveControl<>(this, 85, 10, 0.02F, 0.1F, true)`. + /// The frog's movement speed is 1.0, so the controller's 0.1 outside-water + /// speed is what keeps a walking frog at vanilla's pace. The plain ground + /// controller walks it ten times too fast, which is the jitter, the + /// teleporting and the flying of #2213. + #[test] + fn a_frog_walks_at_the_vanilla_speed() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("entity-types.json").exists() { + return; + } + let data = MobTypes::load(&root).unwrap(); + let kind = Arc::new(data.types.get("minecraft:frog").unwrap().clone()); + assert_eq!(kind.speed, 1.0, "the frog's movement speed attribute"); + let mut m = Mob::new(1, kind, Vec3::new(0.0, 4.0, 0.0), 0.0); + register(&mut m); + assert_eq!( + m.ai.mov.kind, + MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + } + ); + } +} From ee0af20e16cc4ec5e3ad3240dccdde8dec3fe8fb Mon Sep 17 00:00:00 2001 From: socksprox Date: Tue, 27 Oct 2026 01:27:41 +0100 Subject: [PATCH 36/65] Cap the view scale's render distance by the server's streaming.radius reverts to the client setting in apply_settings, so an options change on a server with a lower view distance raised every entity's render range past vanilla's. min(render_distance, remote.view_distance) is Options.getEffectiveRenderDistance. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/entity_culling.rs | 11 ++++++++--- crates/horizon-client/src/game/remote.rs | 4 +++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 4377b2f8d..971639a42 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -63,10 +63,15 @@ impl Game<'_> { impl Game<'_> { /// Entity.setViewScale (LevelExtractor.extractVisibleEntities): the entity /// distance option times the render distance's boost — 1 at 8 chunks, 2.5 - /// at 20 or more (`streaming.radius` is the effective render distance). + /// at 20 or more. The render distance is the client setting, capped by + /// the server's view distance when connected + /// (Options.getEffectiveRenderDistance). pub(super) fn view_scale(&self) -> f64 { - (f64::from(self.streaming.radius) / 8.0).clamp(1.0, 2.5) - * f64::from(self.settings.entity_distance) + let distance = match &self.remote { + Some(r) => self.settings.render_distance.min(r.view_distance), + None => self.settings.render_distance, + }; + (f64::from(distance) / 8.0).clamp(1.0, 2.5) * f64::from(self.settings.entity_distance) } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e9f30e84b..698dbb903 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -123,7 +123,9 @@ pub(super) struct Remote { pub(super) chunk_format: Arc, /// Decodes chunk packets as they arrive, off the frame. decoder: ChunkDecoder, - view_distance: i32, + /// Options.serverRenderDistance: the server's view distance from the + /// login or the last chunk-cache-radius packet. + pub(super) view_distance: i32, sequence: i32, position_sender: horizon_client::player_sync::PositionSender, last_input: u8, From e8891849a40a6a8176e78c52d6bafcc726ced7c4 Mon Sep 17 00:00:00 2001 From: socksprox Date: Tue, 27 Oct 2026 01:39:50 +0100 Subject: [PATCH 37/65] AGENTS.md: name posters by GitHub handle, never a real name The "names its own person" rule was ambiguous about which identity an agent should attribute a post to; handles are the public identity. Co-Authored-By: Devin (SWE-2 High) <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- AGENTS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 4d2a258ec..be78da022 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,8 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a contributor's agent names its own person and tool (issues: "Filed by", reviews: "Review by"). Every - comment starts with `🤖 Agent:`. Never write as Ludovic or as anyone else. + comment starts with `🤖 Agent:`. Name people by their GitHub handle (`gh api user --jq .login`), never a + real name. Never write as Ludovic or as anyone else. - **Attribution.** Commits end with a `Co-Authored-By:` line for the agent that wrote them, and PR bodies with that agent's own "Generated with" line. Ludovic's agents use `Co-Authored-By: Claude ` and From 42ef865c344b8c7553313f285fbd880915ba8d68 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:11:05 +0100 Subject: [PATCH 38/65] Give shulkers vanilla placement, push and look rules A shulker used to check only that its cell was air and the support block had a full collision box. canStayAt now mirrors vanilla: a moving piston in the shell's own cell does not force a teleport, the support's face toward the shell must be sturdy, and the fully opened shell's box must be clear of blocks and entities. teleportSomewhere likewise checks the target cell with noCollision and refuses faces tagged minecraft:shulker_does_not_teleport_to, emits level event 2016 (whose particles now render), and forces a position sync. The shell easing toward its peek now pushes collidable entities out of the swept box (onPeekAmountChange / MoverType.SHULKER) through a new MobEvent::Shift, so standing on a shulker lifts you instead of wedging you inside the lid. ShulkerLookControl is ported too: the head yaw is computed in the attach face's plane (new LookKind::Shulker and look_yaw) instead of the generic world-yaw, and hurtByTarget now ignores damage from other shulkers as toIgnoreDamage does. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 5 + crates/horizon-client/src/game/creatures.rs | 15 ++ .../src/game/level_particles.rs | 6 + crates/horizon-client/src/mobs.rs | 6 + crates/horizon-client/src/mobs/control.rs | 17 ++ crates/horizon-client/src/mobs/shulker.rs | 252 +++++++++++++++--- 6 files changed, 264 insertions(+), 37 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index db49087b2..bb24b81b1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2921,6 +2921,11 @@ impl Game<'_> { pos, data, } => self.dragon_egg_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2016, + pos, + data, + } => self.shulker_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2017, pos, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e895cb7f7..6226dbf80 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -944,6 +944,21 @@ impl Game<'_> { } } } + MobEvent::Shift { target, delta } => { + let d = Vec3::new(delta[0], delta[1], delta[2]); + match target { + Who::Player => { + if let Some(p) = self.player.as_mut() { + p.position = p.position.add_vector(d); + } + } + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.position = m.position.add_vector(d); + } + } + } + } MobEvent::Wololo { mob } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { // DyeColor.RED. diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..165faa4b6 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -12,6 +12,12 @@ impl Game<'_> { self.particles .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); } + /// Event 2016: `Shulker.teleportSomewhere`'s particles between the + /// shell's old and new cells. + pub(super) fn shulker_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .block_teleportation(pos, data, [8, 8, 8], self.settings.particles); + } /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { self.particles diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 0d7fb4b54..62a9974c0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -972,6 +972,12 @@ pub enum MobEvent { target: Who, velocity: [f64; 3], }, + /// `Entity.move(MoverType.SHULKER, delta)`: shift a target's position + /// (an opening shulker lifts what stands on its shell). + Shift { + target: Who, + delta: [f64; 3], + }, /// `EvokerWololoSpellGoal`: a blue sheep turns red. Wololo { mob: u32, diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 3df557362..a111ff5d4 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -90,6 +90,9 @@ pub enum LookKind { Fixed, /// `HappyGhast.HappyGhastLookControl`. HappyGhast, + /// `Shulker.ShulkerLookControl`: the yaw turns in the attach face's + /// plane and the head is never clamped to the body. + Shulker, } #[derive(Clone, Debug, Default)] pub struct LookControl { @@ -345,6 +348,20 @@ impl Mob { self.body_yaw += 4.0; } } + LookKind::Shulker => { + // ShulkerLookControl: resetXRotOnTick, getXRotD 0, and the + // yaw worked out in the attach face's plane (getYRotD). + self.head_pitch = 0.0; + if look.cooldown > 0 { + self.ai.look.cooldown -= 1; + if let Some(y) = super::shulker::look_yaw(self, look.wanted) { + self.head_yaw = rotate_towards(self.head_yaw, y, look.y_max_rot_speed); + } + } else { + self.head_yaw = rotate_towards(self.head_yaw, self.body_yaw, 10.0); + } + // clampHeadRotationToBody does nothing for a shulker. + } LookKind::Default | LookKind::Fixed => { if look.kind == LookKind::Default { self.head_pitch = 0.0; diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 6f0edc2d7..d5bdb6888 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -5,6 +5,7 @@ use super::{ Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, + control::LookKind, goals::{ Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, goal_clone, reduced, @@ -37,7 +38,13 @@ pub fn register(m: &mut Mob) { g.add(4, ShulkerAttack { attack_time: 0 }); g.add(7, Peek { time: 0 }); g.add(8, RandomLookAround::default()); - m.ai.targets.add(1, HurtByTarget::new().alert()); + // `ShulkerLookControl`: the head turns in the attach face's plane. + m.ai.look.kind = LookKind::Shulker; + // `HurtByTargetGoal(this, Shulker.class).setAlertOthers()`: damage from + // another shulker draws no retaliation (`toIgnoreDamage`), but a hurt + // shulker alerts every targetless shulker around. + m.ai.targets + .add(1, HurtByTarget::new().alert().ignoring(&[Species::Shulker])); // ShulkerNearestAttackGoal: the search box is only 4 deep along the // attach axis. m.ai.targets.add( @@ -57,6 +64,10 @@ pub fn register(m: &mut Mob) { fn face_step(face: u8) -> [i32; 3] { STEPS[face.min(5) as usize] } +/// `Direction.getOpposite` for a 3D data value. +fn opposite(face: u8) -> u8 { + face.min(5) ^ 1 +} fn block_pos(m: &Mob) -> [i32; 3] { [ m.position.x.floor() as i32, @@ -64,19 +75,85 @@ fn block_pos(m: &Mob) -> [i32; 3] { m.position.z.floor() as i32, ] } -/// `Shulker.canStayAt`: an empty spot against a sturdy face. -fn can_stay_at(w: &MobWorld, p: [i32; 3], face: u8) -> bool { - if !w.facts.is_air(w.world.block(p[0], p[1], p[2])) { +/// `Shulker.getProgressDeltaAabb` at scale 1: the shell's box from `pos` +/// (the bottom centre), grown `from`..`to` along `direction`. +fn progress_aabb(direction: u8, from: f64, to: f64, pos: Vec3) -> Aabb { + let s = face_step(direction).map(f64::from); + let (max, min) = (from.max(to), from.min(to)); + Aabb::new(Vec3::new(-0.5, 0.0, -0.5), Vec3::new(0.5, 1.0, 0.5)) + .expand_towards(Vec3::new(s[0] * max, s[1] * max, s[2] * max)) + .contract(Vec3::new( + -s[0] * (1.0 + min), + -s[1] * (1.0 + min), + -s[2] * (1.0 + min), + )) + .move_by(pos) +} +/// `Level.noCollision(entity, aabb)`: no block collision under the empty +/// context, and no entity `m` can be collided with overlaps (other mobs, +/// and the player when they are not a spectator). +fn no_collision(m: &Mob, w: &MobWorld, bounds: Aabb) -> bool { + let mut scene = crate::collisions::SceneCollisions { + world: w.world, + binding: w.collision, + subject: None, + }; + if !crate::collisions::no_collision_empty(&mut scene, bounds) { return false; } + let grown = bounds.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(grown) + { + return false; + } + !w.others_near(grown) + .any(|s| s.id != m.id && s.alive && s.bounds.intersects(grown)) +} +/// `Shulker.canStayAt`: an empty spot against a sturdy face, with room +/// for the fully opened shell (`canStayAt`). +fn can_stay_at(m: &Mob, w: &MobWorld, p: [i32; 3], face: u8) -> bool { + // isPositionBlocked: anything but air blocks, except a moving piston + // being driven through the shulker's own cell. + if !w.facts.is_air(w.world.block(p[0], p[1], p[2])) + && (p != block_pos(m) || w.block_name(p[0], p[1], p[2]) != "minecraft:moving_piston") + { + return false; + } + // loadedAndEntityCanStandOnFace: the supporting block's face toward + // the shell is sturdy. let s = face_step(face); - let n = w.world.block(p[0] + s[0], p[1] + s[1], p[2] + s[2]); - w.facts.get(n).full_collision + let support = w.world.block(p[0] + s[0], p[1] + s[1], p[2] + s[2]); + let open = opposite(face); + if w.facts.get(support).sturdy_full & (1 << open) == 0 { + return false; + } + // The fully opened shell's box, shrunk by the skin vanilla uses. + let opened = progress_aabb( + open, + -1.0, + 1.0, + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ), + ) + .deflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6)); + no_collision(m, w, opened) } /// `findAttachableSurface`: the first face (down, up, north, south, west, /// east) to cling to. -fn attachable(w: &MobWorld, p: [i32; 3]) -> Option { - (0..6).find(|&f| can_stay_at(w, p, f)) +fn attachable(m: &Mob, w: &MobWorld, p: [i32; 3]) -> Option { + (0..6).find(|&f| can_stay_at(m, w, p, f)) +} +/// `BlockUtil.packDifferenceInPosition` within 8 blocks of `pos`. +fn pack_diff(pos: [i32; 3], to: [i32; 3]) -> i32 { + ((to[0] - pos[0] + 8) & 0xFF) << 16 + | ((to[1] - pos[1] + 8) & 0xFF) << 8 + | (to[2] - pos[2] + 8) & 0xFF } /// `Shulker.teleportSomewhere`: up to five tries within 8 blocks. fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { @@ -87,12 +164,31 @@ fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { for _ in 0..5 { let r = |m: &mut Mob| m.random.next_int_bound(17).unwrap_or(8) - 8; let t = [old[0] + r(m), old[1] + r(m), old[2] + r(m)]; - if t[1] <= crate::chunk::MIN_Y || !w.facts.is_air(w.world.block(t[0], t[1], t[2])) { + let unit = Aabb::new( + Vec3::new(f64::from(t[0]), f64::from(t[1]), f64::from(t[2])), + Vec3::new( + f64::from(t[0]) + 1.0, + f64::from(t[1]) + 1.0, + f64::from(t[2]) + 1.0, + ), + ); + if t[1] <= crate::chunk::MIN_Y + || !w.facts.is_air(w.world.block(t[0], t[1], t[2])) + || !no_collision(m, w, unit.deflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6))) + { continue; } - let Some(face) = attachable(w, t) else { + let Some(face) = attachable(m, w, t) else { continue; }; + // `#minecraft:shulker_does_not_teleport_to` (bedrock) is never clung to. + let s = face_step(face); + if w.has_tag( + "minecraft:shulker_does_not_teleport_to", + w.block_name(t[0] + s[0], t[1] + s[1], t[2] + s[2]), + ) { + continue; + } m.extra.variant3 = face; events.push(MobEvent::Sound( "entity.shulker.teleport", @@ -106,6 +202,14 @@ fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { f64::from(t[2]) + 0.5, ); m.previous = m.position; + // Level.levelEvent(2016, oldPos, packedDiff): the teleport's + // particles at both ends, seen by the players around. + events.push(MobEvent::LevelEvent { + id: 2016, + pos: old, + data: pack_diff(old, t), + }); + m.needs_sync = true; m.extra.counter = 0; m.ai.target = None; return true; @@ -127,31 +231,102 @@ fn set_peek(m: &mut Mob, amount: i32, events: &mut Vec) { )); m.extra.counter = amount; } -/// `Shulker.tick` additions: keep a face (or teleport), ease the peek, -/// stay still and square on its block. +/// `Shulker.updatePeekAmount`/`updatePeekAmountO`: the eased peek. +fn ease_peek(m: &mut Mob) -> (f32, f32) { + let old = m.anim.v[PEEK]; + let target = m.extra.counter as f32 * 0.01; + let new = if old > target { + (old - 0.05).clamp(target, 1.0) + } else { + (old + 0.05).clamp(0.0, target) + }; + m.anim.v[PEEK] = new; + (old, new) +} +/// `Shulker.tick` additions: keep a face (or teleport), ease the peek +/// (pushing whatever it opens into), stay still and square on its block. pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.velocity = Vec3::ZERO; m.body_yaw = 0.0; m.yaw = 0.0; m.head_pitch = 0.0; let p = block_pos(m); - if !can_stay_at(w, p, m.extra.variant3) { - match attachable(w, p) { + if !can_stay_at(m, w, p, m.extra.variant3) { + match attachable(m, w, p) { Some(f) => m.extra.variant3 = f, None => { teleport(m, w, events); } } } - let a = &mut m.anim; - let target = m.extra.counter as f32 * 0.01; - let cur = a.v[PEEK]; - if cur > target { - a.v[PEEK] = (cur - 0.05).clamp(target, 1.0); - } else if cur < target { - a.v[PEEK] = (cur + 0.05).clamp(0.0, target); + let (old, new) = ease_peek(m); + if new != old { + on_peek_change(m, w, old, new, events); } } +/// `Shulker.getPhysicalPeek`: the lid's lift for a peek amount. +fn physical_peek(amount: f32) -> f64 { + f64::from(0.5 - ((0.5 + amount) * PI).msin() * 0.5) +} +/// `Shulker.onPeekAmountChange`: an opening shell pushes out of its way +/// every entity that can be collided with (except other shulkers). +fn on_peek_change(m: &Mob, w: &MobWorld, old: f32, new: f32, events: &mut Vec) { + let dir = opposite(m.extra.variant3); + let s = face_step(dir).map(f64::from); + let (old_p, new_p) = (physical_peek(old), physical_peek(new)); + let push = new_p - old_p; + if push <= 0.0 { + return; + } + let delta = [push * s[0], push * s[1], push * s[2]]; + let area = progress_aabb(dir, old_p, new_p, m.position); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(area) + { + events.push(MobEvent::Shift { + target: Who::Player, + delta, + }); + } + for seen in w.others_near(area) { + if seen.id == m.id + || !seen.alive + || seen.species == Species::Shulker + || !seen.bounds.intersects(area) + { + continue; + } + events.push(MobEvent::Shift { + target: Who::Mob(seen.id), + delta, + }); + } +} +/// `ShulkerLookControl.getYRotD`: the look yaw in the open direction's +/// plane (`None`: the target is on the head's own axis). +pub fn look_yaw(m: &Mob, at: [f64; 3]) -> Option { + let open = opposite(m.extra.variant3); + // `attachFace.getRotation().transform(FORWARD)`: the model's forward + // rotated as the renderer does (`rotations` uses the same quats). + let forward = face_quat(m.extra.variant3) * glam::Vec3::Z; + let s = face_step(open).map(|v| v as f32); + let right = glam::Vec3::from_array(s).cross(forward); + let out = glam::Vec3::new( + (at[0] - m.position.x) as f32, + (at[1] - m.eye_y()) as f32, + (at[2] - m.position.z) as f32, + ); + let (delta_right, delta_forward) = (right.dot(out), forward.dot(out)); + if delta_right.abs() <= 1.0e-5 && delta_forward.abs() <= 1.0e-5 { + return None; + } + Some(horizon_core::geometry::trig::atan2_degrees( + f64::from(-delta_right), + f64::from(delta_forward), + )) +} /// `Shulker.hurtServer` before the damage: arrows bounce off a closed shell. pub fn accepts(m: &Mob, source: &Damage) -> bool { !(m.extra.counter == 0 && source.kind == DamageKind::Arrow) @@ -319,7 +494,7 @@ impl Goal for Peek { fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { m.ai.target.is_none() && m.random.next_int_bound(reduced(40)).unwrap_or(1) == 0 - && can_stay_at(cx.w, block_pos(m), m.extra.variant3) + && can_stay_at(m, cx.w, block_pos(m), m.extra.variant3) } fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { m.ai.target.is_none() && self.time > 0 @@ -362,24 +537,27 @@ pub fn texture(m: &Mob) -> String { None => "entity/shulker/shulker".into(), } } +/// `attachFace.getOpposite().getRotation()` by attach face: the open +/// direction's rotation (`Direction.getRotation` of `face ^ 1`). +fn face_quat(face: u8) -> glam::Quat { + match face.min(5) { + // Attached below: upright. + 0 => glam::Quat::IDENTITY, + 1 => glam::Quat::from_rotation_x(PI), + 2 => glam::Quat::from_rotation_x(PI / 2.0), + 3 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI), + 4 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, -PI / 2.0), + _ => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI / 2.0), + } +} /// `ShulkerRenderer.setupRotations`: turned onto its attach face around the /// block's centre (after a half turn of the body). pub fn rotations(m: &Mob) -> glam::Mat4 { - { - let q = match m.extra.variant3 { - // Attached below: upright. - 0 => glam::Quat::IDENTITY, - 1 => glam::Quat::from_rotation_x(PI), - 2 => glam::Quat::from_rotation_x(PI / 2.0), - 3 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI), - 4 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, -PI / 2.0), - _ => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI / 2.0), - }; - glam::Mat4::from_rotation_y(PI) - * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.5, 0.0)) - * glam::Mat4::from_quat(q) - * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0)) - } + let q = face_quat(m.extra.variant3); + glam::Mat4::from_rotation_y(PI) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.5, 0.0)) + * glam::Mat4::from_quat(q) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0)) } /// `ShulkerModel.setupAnim`: the lid rises and twists with the peek, the /// head turns. From 7732ce986fb73be94434335d21e34fbb0d17e067 Mon Sep 17 00:00:00 2001 From: socksprox Date: Tue, 27 Oct 2026 02:31:11 +0100 Subject: [PATCH 39/65] Drop a client's remembered effects when it joins a world A rejoining player kept the previous session's effect list, so the HUD could show effects the server no longer had (nothing applied in combat, no icon was earned). Vanilla's new LocalPlayer starts empty and gets its effects from UpdateMobEffect; match that, and let the client-side tick drop effects whose duration ran out, as its removeIf does. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/potions.rs | 6 ++++-- crates/horizon-client/src/game/remote.rs | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 2ccfd4116..6334ff5ad 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -427,9 +427,11 @@ impl Game<'_> { /// `MobEffectInstance.tickClient`): they count down, and the server /// removes them. Their modifiers and flags move the predicted player. pub(super) fn tick_client_effects(&mut self) { - for e in &mut self.potions.effects.list { + // LivingEntity.tickEffects (client): an exhausted effect drops. + self.potions.effects.list.retain_mut(|e| { e.tick_client(); - } + e.duration != 0 + }); self.apply_effect_status(); } /// Add an active effect to the player and update attributes / absorption. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..47846735a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -394,6 +394,9 @@ impl Game<'_> { self.carried = None; self.using = None; self.clicks.miss_time = 0; + // A new LocalPlayer has no effects: the server sends what it has + // (ClientboundUpdateMobEffectPacket on placement). + self.potions = Default::default(); self.set_mode_id(0); self.experience = Experience { level: 0, From 8866e618b5ca736ea430bc8e7f012791c2bd21b6 Mon Sep 17 00:00:00 2001 From: DanielGodriNeto Date: Mon, 26 Oct 2026 22:31:59 -0300 Subject: [PATCH 40/65] perf(light): cache touched sections during relight Relight now runs over a Region that clones each touched section's Arc once, copies its light on first write and writes back only sections whose light changed. The increase loop reads state and light in one lookup. Output is identical; a randomized border test checks it against a full relight. Co-Authored-By: Claude --- crates/horizon-client/src/chunk_map.rs | 19 +- crates/horizon-client/src/light.rs | 410 +++++++++++++++++++------ 2 files changed, 334 insertions(+), 95 deletions(-) diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs index ed25491c5..fddded9e1 100644 --- a/crates/horizon-client/src/chunk_map.rs +++ b/crates/horizon-client/src/chunk_map.rs @@ -76,14 +76,11 @@ impl<'a> IntoIterator for &'a ChunkMap { } } impl crate::light::LightWorld for ChunkMap { - fn state(&self, x: i32, y: i32, z: i32) -> Option { - self.columns.state(x, y, z) + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc> { + self.columns.section(cx, s, cz) } - fn light(&self, x: i32, y: i32, z: i32) -> Option { - self.columns.light(x, y, z) - } - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { - self.columns.set_light(x, y, z, packed); + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: crate::chunk::Light) { + self.columns.set_section_light(cx, s, cz, light); } } @@ -106,7 +103,13 @@ mod tests { for column in map.values_mut() { Arc::make_mut(column).light_loaded = true; } - crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0); + crate::light::LightWorld::set_section_light( + &mut map, + 0, + 0, + 0, + crate::chunk::Light::Uniform(0), + ); assert_eq!(inserted, map.membership_revision()); map.remove(&(0, 0)); map.insert((1, 0), chunk); diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 6cb4b65b1..c8313c3d7 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -17,7 +17,7 @@ use crate::fast_hash::FxHashMap; use crate::{ blocks::BlockFacts, - chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, index}, + chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, Section, index}, }; use horizon_core::geometry::{Direction, ShapeOp, VoxelShape}; use horizon_world::registry::{BlockRegistry, BlockStateId}; @@ -565,43 +565,130 @@ pub fn update_light_layers>( /// Resident chunks the incremental relighter reads and writes. pub trait LightWorld { - fn state(&self, x: i32, y: i32, z: i32) -> Option; - /// Packed light (sky << 4 | block), None outside loaded chunks. - fn light(&self, x: i32, y: i32, z: i32) -> Option; - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8); + /// Section `s` of chunk (cx, cz), None unless the chunk is loaded and lit. + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc
>; + /// Replace the light of a section `section` returned. + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: Light); } impl LightWorld for HashMap<(i32, i32), Arc, S> { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc
> { + self.get(&(cx, cz)) + .filter(|c| c.lit) + .map(|c| &c.sections[s]) + } + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: Light) { + if let Some(chunk) = self.get_mut(&(cx, cz)) { + Arc::make_mut(&mut Arc::make_mut(chunk).sections[s]).light = light; + } + } +} +/// The sections one relight touches, held for the whole flood fill so each +/// cell access is an array index instead of a chunk lookup. Light a section +/// gets written is copied out on the first write and stored back by `finish`. +struct Region<'w> { + world: &'w mut dyn LightWorld, + slots: Vec, + /// Section key (cx, s, cz) to slot, `NONE` where the chunk isn't lit. + index: FxHashMap, + last: (Pos, u32), +} +struct Slot { + key: Pos, + /// The world's section; its light is the value before this relight. + section: Arc
, + light: Option>, +} +const NONE: u32 = u32::MAX; +impl<'w> Region<'w> { + fn new(world: &'w mut dyn LightWorld) -> Self { + Self { + world, + slots: Vec::new(), + index: FxHashMap::default(), + last: ((i32::MIN, 0, 0), NONE), + } + } + #[inline] + fn slot(&mut self, x: i32, y: i32, z: i32) -> Option { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } - self.get(&(x >> 4, z >> 4)) - .filter(|c| c.lit) - .map(|c| c.get(x & 15, y, z & 15)) - } - fn light(&self, x: i32, y: i32, z: i32) -> Option { - if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { - return None; + let key = (x >> 4, (y - MIN_Y) >> 4, z >> 4); + if self.last.0 != key { + self.last = (key, self.load(key)); } - self.get(&(x >> 4, z >> 4)) - .filter(|c| c.lit) - .map(|c| c.light(x & 15, y, z & 15)) + (self.last.1 != NONE).then_some(self.last.1 as usize) } - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { - let Some(chunk) = self.get_mut(&(x >> 4, z >> 4)) else { + fn load(&mut self, key: Pos) -> u32 { + if let Some(&slot) = self.index.get(&key) { + return slot; + } + let slot = match self.world.section(key.0, key.1 as usize, key.2) { + Some(section) => { + self.slots.push(Slot { + key, + section: section.clone(), + light: None, + }); + (self.slots.len() - 1) as u32 + } + None => NONE, + }; + self.index.insert(key, slot); + slot + } + fn state(&mut self, x: i32, y: i32, z: i32) -> Option { + let slot = self.slot(x, y, z)?; + Some(self.slots[slot].section.get(index(x, y, z))) + } + /// Packed light (sky << 4 | block), None outside loaded, lit chunks. + fn light(&mut self, x: i32, y: i32, z: i32) -> Option { + let slot = self.slot(x, y, z)?; + let slot = &self.slots[slot]; + let i = index(x, y, z); + Some(match &slot.light { + Some(light) => light[i], + None => slot.section.light(i), + }) + } + /// State and packed light of a cell, with a single section lookup. + fn cell(&mut self, x: i32, y: i32, z: i32) -> Option<(u32, u8)> { + let slot = self.slot(x, y, z)?; + let slot = &self.slots[slot]; + let i = index(x, y, z); + let light = match &slot.light { + Some(light) => light[i], + None => slot.section.light(i), + }; + Some((slot.section.get(i), light)) + } + /// Rewrite a cell's packed light; nothing outside loaded, lit chunks. + fn update_light(&mut self, x: i32, y: i32, z: i32, f: impl FnOnce(u8) -> u8) { + let Some(slot) = self.slot(x, y, z) else { return; }; - let s = ((y - MIN_Y) >> 4) as usize; + let slot = &mut self.slots[slot]; + let light = slot.light.get_or_insert_with(|| match &slot.section.light { + Light::Uniform(v) => Box::new([*v; 4096]), + Light::Full(a) => a.clone(), + }); let i = index(x, y, z); - if chunk.sections[s].light(i) == packed { - return; - } - let section = Arc::make_mut(&mut Arc::make_mut(chunk).sections[s]); - if let Light::Uniform(v) = section.light { - section.light = Light::Full(Box::new([v; 4096])); - } - if let Light::Full(a) = &mut section.light { - a[i] = packed; + light[i] = f(light[i]); + } + /// Store back the light of every section whose values changed. + fn finish(self) { + for slot in self.slots { + let Some(light) = slot.light else { + continue; + }; + if (0..4096).all(|i| slot.section.light(i) == light[i]) { + continue; + } + // Drop the clone first so the world's section isn't copied. + drop(slot.section); + let (cx, s, cz) = slot.key; + self.world + .set_section_light(cx, s as usize, cz, Light::Full(light)); } } } @@ -690,25 +777,23 @@ impl LightChanges { } } } -fn level(world: &impl LightWorld, sky: bool, p: Pos) -> Option { +fn level(world: &mut Region, sky: bool, p: Pos) -> Option { world .light(p.0, p.1, p.2) .map(|v| if sky { v >> 4 } else { v & 15 }) } -fn set_level(world: &mut impl LightWorld, sky: bool, p: Pos, value: u8) { - let Some(old) = world.light(p.0, p.1, p.2) else { - return; - }; - let packed = if sky { - (old & 0x0F) | value << 4 - } else { - (old & 0xF0) | value - }; - world.set_light(p.0, p.1, p.2, packed); +fn set_level(world: &mut Region, sky: bool, p: Pos, value: u8) { + world.update_light(p.0, p.1, p.2, |old| { + if sky { + (old & 0x0F) | value << 4 + } else { + (old & 0xF0) | value + } + }); } /// `ChunkSkyLightSources`: the Y of the upper block of the highest occluded /// edge in the column (every block at or above it is a sky source). -pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, z: i32) -> i32 { +fn lowest_sky_source(world: &mut Region, tables: &LightTables, x: i32, z: i32) -> i32 { let mut y = MIN_Y + HEIGHT - 1; let Some(mut top) = world.state(x, y, z) else { return MIN_Y; @@ -739,34 +824,52 @@ pub fn relight( force: bool, changed: &mut LightChanges, ) { - relight_layer(world, tables, false, positions.to_vec(), force, changed); + let mut region = Region::new(world); + relight_region(&mut region, tables, sky_light, positions, force, changed); + region.finish(); +} +fn relight_region( + world: &mut Region, + tables: &LightTables, + sky_light: bool, + positions: &[Pos], + force: bool, + changed: &mut LightChanges, +) { + crate::spans::time("lt_block", || { + relight_layer(world, tables, false, positions.to_vec(), force, changed) + }); if sky_light { let mut seeds = positions.to_vec(); - let mut columns: HashMap<(i32, i32), i32> = HashMap::new(); - for &(x, _, z) in positions { - if columns.contains_key(&(x, z)) { - continue; - } - let source = lowest_sky_source(world, tables, x, z); - columns.insert((x, z), source); - // Cells whose source status changed: non-15 at or above the new - // lowest source, and old 15s (sources) below it. - for y in source..MIN_Y + HEIGHT { - if level(world, true, (x, y, z)).is_some_and(|l| l != 15) { + let mut columns: FxHashMap<(i32, i32), i32> = FxHashMap::default(); + crate::spans::time("lt_columns", || { + for &(x, _, z) in positions { + if columns.contains_key(&(x, z)) { + continue; + } + let source = lowest_sky_source(world, tables, x, z); + columns.insert((x, z), source); + // Cells whose source status changed: non-15 at or above the new + // lowest source, and old 15s (sources) below it. + for y in source..MIN_Y + HEIGHT { + if level(world, true, (x, y, z)).is_some_and(|l| l != 15) { + seeds.push((x, y, z)); + } + } + let mut y = source - 1; + while y >= MIN_Y && level(world, true, (x, y, z)) == Some(15) { seeds.push((x, y, z)); + y -= 1; } } - let mut y = source - 1; - while y >= MIN_Y && level(world, true, (x, y, z)) == Some(15) { - seeds.push((x, y, z)); - y -= 1; - } - } - relight_layer(world, tables, true, seeds, force, changed); + }); + crate::spans::time("lt_sky", || { + relight_layer(world, tables, true, seeds, force, changed) + }); } } fn relight_layer( - world: &mut impl LightWorld, + world: &mut Region, tables: &LightTables, sky: bool, seeds: Vec, @@ -809,42 +912,40 @@ fn relight_layer( } } // Sources inside the cleared area light up again. - let mut sources: HashMap<(i32, i32), i32> = HashMap::new(); - for p in cleared { - let seed = if sky { - let lowest = *sources - .entry((p.0, p.2)) - .or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); - if p.1 >= lowest { 15 } else { 0 } - } else { - world - .state(p.0, p.1, p.2) - .map_or(0, |s| tables.cells[s as usize].emission) - }; - if seed > level(world, sky, p).unwrap_or(15) { - set_level(world, sky, p, seed); - changed.push(p); - increase.push_back(p); + let mut sources: FxHashMap<(i32, i32), i32> = FxHashMap::default(); + crate::spans::time("lt_sources", || { + for p in cleared { + let seed = if sky { + let lowest = *sources + .entry((p.0, p.2)) + .or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); + if p.1 >= lowest { 15 } else { 0 } + } else { + world + .state(p.0, p.1, p.2) + .map_or(0, |s| tables.cells[s as usize].emission) + }; + if seed > level(world, sky, p).unwrap_or(15) { + set_level(world, sky, p, seed); + changed.push(p); + increase.push_back(p); + } } - } + }); while let Some(p) = increase.pop_front() { - let Some(l) = level(world, sky, p) else { + let Some((from, packed)) = world.cell(p.0, p.1, p.2) else { continue; }; + let l = if sky { packed >> 4 } else { packed & 15 }; if l <= 1 { continue; } - let Some(from) = world.state(p.0, p.1, p.2) else { - continue; - }; for (d, (ox, oy, oz)) in OFFSETS.iter().enumerate() { let q = (p.0 + ox, p.1 + oy, p.2 + oz); - let Some(to) = world.state(q.0, q.1, q.2) else { - continue; - }; - let Some(ql) = level(world, sky, q) else { + let Some((to, packed)) = world.cell(q.0, q.1, q.2) else { continue; }; + let ql = if sky { packed >> 4 } else { packed & 15 }; let next = l.saturating_sub(tables.cells[to as usize].dampening.max(1)); if next > ql && !tables.blocked(from as usize, to as usize, d) { set_level(world, sky, q, next); @@ -915,10 +1016,10 @@ mod tests { lit.into_iter().collect() } fn sky(world: &HashMap<(i32, i32), Arc>, x: i32, y: i32, z: i32) -> u8 { - world.light(x, y, z).unwrap() >> 4 + world[&(x >> 4, z >> 4)].light(x & 15, y, z & 15) >> 4 } fn block(world: &HashMap<(i32, i32), Arc>, x: i32, y: i32, z: i32) -> u8 { - world.light(x, y, z).unwrap() & 15 + world[&(x >> 4, z >> 4)].light(x & 15, y, z & 15) & 15 } #[test] @@ -954,6 +1055,108 @@ mod tests { assert_eq!(sky(&w, 8, 2, 8), 0, "the full bottom face stops sky light"); } #[test] + fn relight_keeps_unchanged_and_unlit_sections() { + let mut w = world(|_| {}); + Arc::make_mut(w.get_mut(&(1, 0)).unwrap()).lit = false; + let before = w.clone(); + let same = |w: &HashMap<(i32, i32), Arc>, key| { + w[&key] + .sections + .iter() + .zip(&before[&key].sections) + .all(|(a, b)| Arc::ptr_eq(a, b)) + }; + // Cleared and lit back to the same values: nothing is stored. + relight( + &mut w, + &tables(), + true, + &[(8, 5, 8)], + false, + &mut LightChanges::default(), + ); + assert!(w.keys().all(|&key| same(&w, key))); + // Light reaching an unlit chunk isn't written into it. + Arc::make_mut(w.get_mut(&(0, 0)).unwrap()).set(15, 0, 8, TORCH); + relight( + &mut w, + &tables(), + true, + &[(15, 0, 8)], + false, + &mut LightChanges::default(), + ); + assert!(same(&w, (1, 0))); + assert_eq!(block(&w, 14, 0, 8), 13); + } + #[test] + fn random_border_relights_match_full_relight() { + // Edits around every border of chunk (0, 0), at the top and bottom of + // the world, in batches; a held clone of the chunk must not change. + let mut w = world(|_| {}); + let held = w[&(0, 0)].clone(); + let mut rng = 0x9e37_79b9_u32; + let mut next = |n: usize| { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + rng as usize % n + }; + let xz = [-2, -1, 0, 1, 7, 14, 15, 16, 17]; + let ys = [ + MIN_Y, + MIN_Y + 1, + -2, + -1, + 0, + 1, + 15, + 16, + MIN_Y + HEIGHT - 2, + MIN_Y + HEIGHT - 1, + ]; + for _ in 0..60 { + let positions: Vec = (0..1 + next(6)) + .map(|_| (xz[next(xz.len())], ys[next(ys.len())], xz[next(xz.len())])) + .collect(); + for &(x, y, z) in &positions { + let state = [TORCH, SLAB, AIR, STONE][next(4)]; + Arc::make_mut(w.get_mut(&(x >> 4, z >> 4)).unwrap()).set(x & 15, y, z & 15, state); + } + relight( + &mut w, + &tables(), + true, + &positions, + false, + &mut LightChanges::default(), + ); + } + // Every chunk, the outer ring lit as `world` lit it (no neighbours + // past the 3x3). + for (&(cx, cz), chunk) in &w { + let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| { + w.get(&(cx + dx as i32 - 1, cz + dz as i32 - 1)) + .map(|c| &**c) + }) + }); + for (si, s) in light_chunk(®ion, &tables(), true).iter().enumerate() { + for i in 0..4096 { + assert_eq!( + s.get(i), + chunk.sections[si].light(i), + "chunk {cx},{cz} section {si} index {i}" + ); + } + } + } + let fresh = world(|_| {}); + for (a, b) in held.sections.iter().zip(&fresh[&(0, 0)].sections) { + assert!((0..4096).all(|i| a.light(i) == b.light(i))); + } + } + #[test] fn incremental_relight_matches_full_relight() { let mut w = world(|c| { c.set(8, 0, 8, TORCH); @@ -1319,4 +1522,37 @@ mod tests { "fixture heap payload {payload} bytes; old worker clones it plus 24 section Arcs; old application clones current payload and 98304 returned light bytes. New worker clones zero section payload; new application clones current payload only when shared." ); } + /// Relight cost for torches placed and removed near chunk borders with + /// slabs flickering around them (fluids next to lava, in the game). + /// `cargo test --profile fast -p horizon-client relight_bench -- --ignored --nocapture` + #[test] + #[ignore] + fn relight_bench() { + let mut w: FxHashMap<_, _> = world(|_| {}).into_iter().collect(); + let t = tables(); + let mut rng = 0x2545_f491_u32; + let mut next = |n: i32| { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + (rng % n as u32) as i32 + }; + let start = std::time::Instant::now(); + let mut changed = LightChanges::default(); + for round in 0..400 { + let state = [TORCH, SLAB, AIR][round % 3]; + let positions: Vec = (0..32) + .map(|_| (next(32) - 8, next(12), next(32) - 8)) + .collect(); + for &(x, y, z) in &positions { + Arc::make_mut(w.get_mut(&(x >> 4, z >> 4)).unwrap()).set(x & 15, y, z & 15, state); + } + relight(&mut w, &t, true, &positions, false, &mut changed); + } + println!( + "relight_bench: {:?}, {} sections", + start.elapsed(), + changed.sections().count() + ); + } } From b39c4b8dd4eb0a55c8254352ab3696bba04562b1 Mon Sep 17 00:00:00 2001 From: socksprox Date: Tue, 27 Oct 2026 02:36:53 +0100 Subject: [PATCH 41/65] mobs: jumpOutOfFluid wants a dry, entity-free box Entity.isFree is noCollision(this, box) && !containsAnyLiquid(box); the check only looked at block collisions, so a mob pressed against a wall by water flow hopped out where vanilla refuses, and it ignored other collidable entities entirely. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/mobs/living.rs | 39 ++++++++++++++++++++---- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..7331eb344 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -235,6 +235,26 @@ impl MobWorld<'_> { }; scene.unobstructed(b).unwrap_or(false) } + /// `LevelReader.containsAnyLiquid`: the blocks from the box's minimum + /// corner to the block holding its maximum corner. + pub fn contains_any_liquid(&self, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + let (x0, y0, z0) = ( + lo.x.floor() as i32, + lo.y.floor() as i32, + lo.z.floor() as i32, + ); + let (x1, y1, z1) = ( + hi.x.floor() as i32, + hi.y.floor() as i32, + hi.z.floor() as i32, + ); + (x0..=x1).any(|x| { + (y0..=y1).any(|y| { + (z0..=z1).any(|z| self.facts.get(self.world.block(x, y, z)).fluid != Fluid::None) + }) + }) + } } impl Mob { /// `Entity.refreshDimensions` after growing from `old_w` by `old_h`: @@ -813,14 +833,21 @@ impl Mob { self.velocity.y -= gravity / 4.0; } } - // jumpOutOfFluid + // jumpOutOfFluid: Entity.isFree wants the box dry and clear of + // collidable entities too. let m = self.velocity; + let ahead = self.bounds().move_by(Vec3::new( + m.x, + m.y + f64::from(0.6_f32) - self.position.y + old_y, + m.z, + )); + let wide = ahead.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); if self.horizontal_collision - && w.no_collision(self.bounds().move_by(Vec3::new( - m.x, - m.y + f64::from(0.6_f32) - self.position.y + old_y, - m.z, - ))) + && w.no_collision(ahead) + && !w.contains_any_liquid(ahead) + && !w + .others_near(wide) + .any(|s| s.id != self.id && s.alive && s.bounds.intersects(wide)) { self.velocity.y = f64::from(0.3_f32); } From 9ae37fcb5062707871c1f25d7e755f857a19feb8 Mon Sep 17 00:00:00 2001 From: DanielGodriNeto Date: Mon, 26 Oct 2026 19:17:58 -0300 Subject: [PATCH 42/65] feat(threads): measure thread CPU time on Windows from cycle counts thread_cpu() returned None on Windows. Implement it from thread cycle counts, inside horizon-threads so horizon-client keeps forbid(unsafe_code). Co-Authored-By: Claude --- crates/horizon-client/src/spans.rs | 5 ++-- crates/horizon-threads/Cargo.toml | 2 +- crates/horizon-threads/src/lib.rs | 37 ++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index ce69be8ce..33c4bb933 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -52,8 +52,9 @@ pub fn thread_cpu() -> Option { Some(Duration::new(t.tv_sec as u64, t.tv_nsec as u32)) } #[cfg(not(unix))] - None + horizon_threads::thread_cpu() } + /// The frame's spans, summed by name, slowest first; clears them. pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); @@ -135,7 +136,7 @@ mod tests { /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. - #[cfg(unix)] + #[cfg(any(unix, all(windows, target_arch = "x86_64")))] #[test] fn thread_cpu_counts_work_not_sleep() { let start = super::thread_cpu().unwrap(); diff --git a/crates/horizon-threads/Cargo.toml b/crates/horizon-threads/Cargo.toml index d43b3e4fc..67b3c20da 100644 --- a/crates/horizon-threads/Cargo.toml +++ b/crates/horizon-threads/Cargo.toml @@ -10,7 +10,7 @@ description = "Scheduling hints for the game's threads: the OS calls the crates libc = "0.2" [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.61", features = ["Win32_System_Threading"] } +windows-sys = { version = "0.61", features = ["Win32_System_Threading", "Win32_System_WindowsProgramming"] } [lints] workspace = true diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index 917c3b502..85957b7e1 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -41,6 +41,43 @@ fn favour() -> bool { false } +/// The CPU time the calling thread has used, where only an OS call gives it +/// precisely. Windows counts it exactly only in cycles of the time-stamp +/// counter (`QueryThreadCycleTime`; `GetThreadTimes` moves in scheduler ticks +/// of ~15.6 ms), so the counter's rate is measured once against the wall +/// clock and cycles convert to time. `None` elsewhere: unix callers read +/// `CLOCK_THREAD_CPUTIME_ID` themselves. +#[cfg(all(windows, target_arch = "x86_64"))] +pub fn thread_cpu() -> Option { + use std::{ + sync::OnceLock, + time::{Duration, Instant}, + }; + use windows_sys::Win32::System::{ + Threading::GetCurrentThread, WindowsProgramming::QueryThreadCycleTime, + }; + // Time-stamp counter cycles per nanosecond. + static RATE: OnceLock = OnceLock::new(); + let rate = *RATE.get_or_init(|| { + // SAFETY: RDTSC has no preconditions on x86_64. + let tsc = || unsafe { core::arch::x86_64::_rdtsc() }; + let (wall, start) = (Instant::now(), tsc()); + std::thread::sleep(Duration::from_millis(20)); + (tsc() - start) as f64 / wall.elapsed().as_nanos() as f64 + }); + let mut cycles = 0; + // SAFETY: GetCurrentThread's pseudo handle needs no closing; a valid out pointer. + if unsafe { QueryThreadCycleTime(GetCurrentThread(), &mut cycles) } == 0 { + return None; + } + Some(Duration::from_nanos((cycles as f64 / rate) as u64)) +} + +#[cfg(not(all(windows, target_arch = "x86_64")))] +pub fn thread_cpu() -> Option { + None +} + /// Set once as the game starts, before its helper threads do: they then go /// behind the server thread and the render thread (`behind_server`). static HELPERS_BEHIND: AtomicBool = AtomicBool::new(false); From e70ead5bfe57eac08d45065d62859b5e326aebc1 Mon Sep 17 00:00:00 2001 From: socksprox Date: Tue, 27 Oct 2026 02:51:55 +0100 Subject: [PATCH 43/65] Multiplayer parity: four client/server movement and use divergences - A remote client no longer tramples farmland or turtle eggs locally: BlockLandingWorld.is_server_level/is_client_side now reflect the player's client_side flag, as vanilla's fallOn gates trampling and entity events on `level instanceof ServerLevel`. The server's block change and teleport drive the change, so a player no longer ends up inside the grown block (phasing through when farmland turns to dirt). - key.swapOffhand, key.drop and a mount's inventory key on a server now wait for the tick's input phase instead of sending a packet straight from the window event, like the click queue: no action packet leaks between CLIENT_TICK_END and a later pong. - remote_use_item treats a refused consume like vanilla's InteractionResult.FAIL: a full player who right-clicks food no longer starts a use the server will refuse (the eat/noslow desync), the off hand gets its turn, and no use cooldown starts. - The host's "moved too quickly" check subtracts the guest's server-simulated velocity like vanilla's expectedDist term, so a fast legitimate arrival (e.g. landing with elytra) isn't flagged. Co-Authored-By: Devin --- crates/horizon-client/src/game.rs | 6 +- crates/horizon-client/src/game/remote.rs | 83 +++++++++++++++++------- crates/horizon-client/src/lan/hub.rs | 11 +++- crates/horizon-client/src/landing.rs | 7 +- 4 files changed, 75 insertions(+), 32 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2bfdc1d49..fa0d09a31 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11256,8 +11256,10 @@ impl Game<'_> { // key.swapOffhand: on a server, ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND // (the server swaps the hands and sends both slots back; spectators can't). KeyCode::KeyF if self.screen == Screen::Playing && self.remote.is_some() => { - if !self.spectator() { - self.remote_swap_hands(); + if !self.spectator() + && let Some(r) = self.remote.as_mut() + { + r.pending_keys.push(key); } } KeyCode::KeyF if self.screen == Screen::Playing => { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..946e55488 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -189,6 +189,10 @@ pub(super) struct Remote { destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, + /// Keys whose presses send a packet (swap hands, drop, a mount's + /// inventory): like the click queue, they wait for the tick's + /// `handleKeybinds` phase rather than going out between window events. + pub(super) pending_keys: Vec, stop_mining: bool, placing: Option<([i32; 3], u64)>, death_message: Option, @@ -473,6 +477,7 @@ impl Game<'_> { destroying: None, destroy_delay: 0, input: Default::default(), + pending_keys: Vec::new(), stop_mining: false, placing: None, death_message: None, @@ -4295,13 +4300,18 @@ impl Game<'_> { let Some(info) = self.res.items().get(&held.item).cloned() else { return false; }; + // Food starts being eaten (Consumable.startConsuming). A food that + // can't be eaten (full and not always-edible) fails the use + // (InteractionResult.FAIL): startUseItem tries the other hand, and + // no cooldown or use animation starts. + let eating = self.with_hand(hand, |g| g.start_eating(&info)); + if info.food.is_some() && !eating { + return false; + } // MultiPlayerGameMode.useItem runs the use here too (inside // startPrediction): the `use_cooldown` component starts its entry, and // the server's ClientboundCooldownPacket confirms it. self.apply_use_cooldown(&held); - // Food starts being eaten (Consumable.startConsuming), a book and - // quill opens. - self.with_hand(hand, |g| g.start_eating(&info)); if self.with_hand(hand, |g| g.remote_use_book(&held)) { return true; } @@ -4483,6 +4493,31 @@ impl Game<'_> { } let (attack, use_item) = (self.left, self.right); input.tick(&mut RemoteInputWorld(self), attack, use_item); + // handleKeybinds' keybind polls: the queued presses act now, in tick + // order, so no packet goes out between CLIENT_TICK_END and a pong. + let pending = self + .remote + .as_mut() + .map(|r| std::mem::take(&mut r.pending_keys)) + .unwrap_or_default(); + for key in pending { + match key { + KeyCode::KeyF if !self.spectator() => self.remote_swap_hands(), + KeyCode::KeyQ if !self.spectator() => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.remote_drop(all); + } + KeyCode::KeyE if self.riding_mount_with_menu() => { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 5, + data: 0, + })); + } + _ => {} + } + } if self.clicks.miss_time > 0 { self.clicks.miss_time -= 1; } @@ -4594,22 +4629,8 @@ impl Game<'_> { if self.spectator() { return Ok(true); } - let all = self.keys.contains(&KeyCode::ControlLeft); - // MultiPlayerGameMode.dropItem: predict removal before sending - // the action, then swing only if a nonempty stack was removed. - let dropped = horizon_client::items::take_held_drop( - &mut self.inventory[self.selected], - all, - false, - ); - self.send(S::PlayerAction(play::PlayerAction { - action: if all { 4 } else { 5 }, - pos: [0; 3], - direction: 0, - sequence: 0, - })); - if dropped.is_some() { - self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + if let Some(r) = self.remote.as_mut() { + r.pending_keys.push(key); } Ok(true) } @@ -4617,12 +4638,9 @@ impl Game<'_> { // horse or llama, the server opens its inventory // (ServerboundPlayerCommandPacket OPEN_INVENTORY). KeyCode::KeyE if self.riding_mount_with_menu() => { - let id = self.remote.as_ref().map_or(0, |r| r.entity_id); - self.send(S::PlayerCommand(play::PlayerCommand { - id, - action: 5, - data: 0, - })); + if let Some(r) = self.remote.as_mut() { + r.pending_keys.push(key); + } Ok(true) } KeyCode::KeyE => { @@ -4669,6 +4687,21 @@ impl Game<'_> { })); } } + /// MultiPlayerGameMode.dropItem (key.drop): predict the removal, then send + /// the action; swing only if a nonempty stack was removed. + fn remote_drop(&mut self, all: bool) { + let dropped = + horizon_client::items::take_held_drop(&mut self.inventory[self.selected], all, false); + self.send(S::PlayerAction(play::PlayerAction { + action: if all { 4 } else { 5 }, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + if dropped.is_some() { + self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + } + } /// Minecraft.handleKeybinds, key.swapOffhand: the server swaps the hands /// (ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND at BlockPos.ZERO, facing down) and /// sends both slots back; nothing is predicted. diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..4e7ad2e79 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2134,11 +2134,16 @@ impl Hub { packets = 1; } // shouldCheckPlayerMovement (never the single-player owner). - // The server holds no velocity for a guest (getDeltaMovement), - // so nothing is expected. if !owner && check && (!g.fall_flying || elytra_check) { let limit = if g.fall_flying { 300.0 } else { 100.0 }; - if moved > limit * f64::from(packets) { + // `movedDist - expectedDist` (getDeltaMovement): the velocity + // the server last simulated for the guest is expected + // movement, not a violation — a landing glide keeps its speed. + let expected = g.motion.as_ref().map_or(0.0, |m| { + let v = m.velocity; + v.x * v.x + v.y * v.y + v.z * v.z + }); + if moved - expected > limit * f64::from(packets) { events.push(HostEvent::Warn(format!( "{} moved too quickly! {},{},{}", g.name, diff --git a/crates/horizon-client/src/landing.rs b/crates/horizon-client/src/landing.rs index 6fb1f7580..629d8c042 100644 --- a/crates/horizon-client/src/landing.rs +++ b/crates/horizon-client/src/landing.rs @@ -324,10 +324,13 @@ impl BlockLandingWorld for MotionWorld<'_, '_, '_> { type DamageSource = LandingDamage; type Sound = SceneSound; fn is_server_level(&self) -> bool { - true + // A remote client's world is a client level: it never tramples, + // the server's block change and teleport do it (FarmlandBlock.fallOn + // and TurtleEggBlock.fallOn check `level instanceof ServerLevel`). + !self.player.client_side } fn is_client_side(&mut self) -> Result { - Ok(false) + Ok(self.player.client_side) } fn random_float(&mut self) -> Result { Ok(self.scene.random.next_float()) From d6017151266c7c9890a6d5d5604b0949daecd7c1 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Tue, 27 Oct 2026 03:08:53 +0100 Subject: [PATCH 44/65] Streaming: the last finished ring is lit against decorated neighbours A chunk was lit only once all eight neighbours were finished, so the outermost finished ring of a loaded area (a /forceload square, a /pregen band's edge, a player's last ring) stayed unlit: saved as FULL with no light at all, and with no generation animals, which wait for light. Vanilla's LIGHT step needs its neighbours only at INITIALIZE_LIGHT (ChunkPyramid), so its last FULL ring is lit against decorated chunks. A light job now reads a neighbour that will not finish (past the area) from its decorated proto chunk (ChunkGenerator::light_view). A chunk saved unlit is saved again once lit, and one whose light changes when a neighbour finishes later is saved again. `execute if loaded` needs the chunk lit, as vanilla's needs it ENTITY_TICKING. Co-Authored-By: Claude Opus 5.5 --- .../src/game/commands/execute.rs | 10 +++-- crates/horizon-client/src/save.rs | 3 ++ crates/horizon-client/src/streaming.rs | 40 ++++++++++++++++++- crates/horizon-client/src/vanillagen.rs | 6 +++ 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..b2b410337 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -807,10 +807,12 @@ impl Game<'_> { .coords(c, "pos") .map(|co| co.block(self.source_position(), self.source_rotation())); let dimension = self.command_source.map_or(self.dim, |s| s.dimension); - return Ok(flag( - dimension == self.dim - && p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))), - )); + // ExecuteCommand.isChunkLoaded: ENTITY_TICKING, which is past lit. + let loaded = |p: [i32; 3]| { + let key = (p[0] >> 4, p[2] >> 4); + self.world.chunks.contains_key(&key) && self.streaming.is_lit(key.0, key.1) + }; + return Ok(flag(dimension == self.dim && p.is_some_and(loaded))); } if c.has("dimension") { let dimension = self.command_source.map_or(self.dim, |s| s.dimension); diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5431adcd6..033392224 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -3841,6 +3841,9 @@ impl ChunkGenerator for Persistent { fn is_decorated(&self, proto: &crate::streaming::Proto) -> bool { self.inner.is_decorated(proto) } + fn light_view(&self, proto: &crate::streaming::Proto) -> Option { + self.inner.light_view(proto) + } fn save_protos(&self, protos: &[&crate::streaming::Proto]) { self.save .tables diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 643a604bc..7d25cf64c 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -70,6 +70,11 @@ pub trait ChunkGenerator: Send + Sync + 'static { false } /// What to save of a proto chunk dropped before it became final. + /// A decorated proto chunk's blocks as a column, to light a finished + /// neighbour against (vanilla lights with neighbours at FEATURES). + fn light_view(&self, _proto: &Proto) -> Option { + None + } fn saved_proto(&self, _proto: &Proto) -> Option { None } @@ -207,6 +212,7 @@ struct Shared { } pub struct Streaming { shared: Arc, + light_view: Arc Option + Send + Sync>, results: mpsc::Receiver, threads: Vec>, order: u64, @@ -531,8 +537,13 @@ impl Streaming { .expect("spawn worker") }) .collect(); + let light_view = { + let generator = generator.clone(); + Arc::new(move |p: &Proto| generator.light_view(p)) + }; Self { shared, + light_view, results, threads, order: 0, @@ -746,6 +757,26 @@ impl Streaming { fn distance(&self, x: i32, z: i32) -> i64 { self.ranges().priority(x, z, self.loading) } + /// The 3x3 a light job reads: the finished columns, and for a neighbour + /// that will not finish (past the area), its decorated proto chunk, as + /// vanilla lights its last FULL ring against neighbours at FEATURES. + fn light_region(&self, world: &World, x: i32, z: i32) -> Option> { + let mut region: Region = Default::default(); + for dz in 0..3 { + for dx in 0..3 { + let n = (x + dx as i32 - 1, z + dz as i32 - 1); + region[dz][dx] = Some(match world.chunks.get(&n) { + Some(chunk) => chunk.clone(), + None if !self.in_range(n.0, n.1, 1) && self.decorated.contains(&n) => { + let proto = self.protos.get(&n)?.as_ref()?; + Arc::new((self.light_view)(proto)?) + } + None => return None, + }); + } + } + Some(Box::new(region)) + } fn region(world: &World, x: i32, z: i32) -> Option> { let mut region: Region = Default::default(); for dz in 0..3 { @@ -866,6 +897,11 @@ impl Streaming { } else { apply_relighting(chunk, sections, &mut changed); } + // Saved unlit (at the edge of what was loaded), or its light + // changed: saved again. + if (first && !chunk.light_loaded) || !changed.is_empty() { + world.modified.insert((x, z)); + } chunk.lit = true; if first { for dz in -1..=1 { @@ -1102,7 +1138,7 @@ impl Streaming { world.dirty_light.remove(&(x, z)); continue; } - let Some(region) = Self::region(world, x, z) else { + let Some(region) = self.light_region(world, x, z) else { continue; }; world.dirty_light.remove(&(x, z)); @@ -1424,7 +1460,7 @@ impl Streaming { counts[1] += 1; } else { counts[2] += 1; - if Self::region(world, key.0, key.1).is_some() { + if self.light_region(world, key.0, key.1).is_some() { world.dirty_light.insert(key); } } diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 923818a08..c07082426 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -433,6 +433,12 @@ impl ChunkGenerator for VanillaTerrain { fn is_decorated(&self, proto: &Proto) -> bool { matches!(proto.downcast_ref::(), Some(VanillaProto::Ready(c)) if c.is_decorated()) } + fn light_view(&self, proto: &Proto) -> Option { + match proto.downcast_ref::() { + Some(VanillaProto::Ready(chunk)) => Some(self.column(chunk)), + _ => None, + } + } fn saved_proto(&self, proto: &Proto) -> Option { let Some(VanillaProto::Ready(chunk)) = proto.downcast_ref::() else { return None; From c3a12bf7924e141518b82431452377a5b73856ac Mon Sep 17 00:00:00 2001 From: Silas Lunsford Date: Mon, 26 Oct 2026 21:11:35 -0500 Subject: [PATCH 45/65] client: retune the entity-shadow depth bias to kill its rim flicker The shadow quads lie exactly on block tops like vanilla's, but terrain and shadows are separate draws: their fp32 depth interpolations disagree by a few dozen ulps of the fragment depth, and at a constant bias of 16 ulps the rim re-rolled the fight with the block top as the camera drifted a subpixel - the visible speckle. Subpixel yaw glides at three camera pitches (70, 45, 20 down) measured ~88/~60/~26 strong flip pixels a frame with the shadow, all on the rim, none without it. A constant bias of 128 ulps covers the spread at any resolution while staying far below what the 0.001 a model's feet sit higher amounts to, so shadows never bleed onto the feet. Co-Authored-By: GLM 5.3-Flash --- crates/horizon-client/src/gfx.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 70d882a98..22a96ffba 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1818,19 +1818,21 @@ impl Renderer { false, ); // RenderPipelines.ENTITY_SHADOW: translucent, depth test without - // writes. The quads lie on the block tops like vanilla's, but the - // terrain under them snaps to the subpixel grid at other vertices, so - // at a slant their depths differ by up to 1/256 of a pixel's depth - // slope and whole shadows failed the test. The bias covers that and - // the rounding, and stays below the 0.001 a model's feet sit higher - // (1/27 of a pixel's slope at the 16-block shadow range in 720p). + // writes. The quads lie exactly on the block tops like vanilla's, but + // terrain and shadows are separate draw paths, so their fp32 depth + // interpolations disagree by a few dozen ulps of the fragment depth + // and the shadow's rim z-fights with the block top (speckle that + // re-rolls as the camera drifts a subpixel). A constant bias of 128 + // ulps covers that spread at any resolution while staying far below + // the 0.001 a model's feet sit higher, so shadows never bleed onto + // the feet. let shadow_blob_pipeline = entity_pipeline( "Entity shadows", None, false, wgpu::CompareFunction::GreaterEqual, wgpu::DepthBiasState { - constant: 16, + constant: 128, slope_scale: 0.015, clamp: 0.0, }, From 82c8398c6b3ba361e5f57342e927fb7c94956af3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:02:20 +0100 Subject: [PATCH 46/65] launcher: desktop shortcut that plays an instance Home's Instance row gets Shortcut / Remove shortcut, and the CLI and MCP instance shortcut [instance] [--remove]. The shortcut runs horizon-launcher play --instance : a .desktop file on Linux (and in the applications menu), a script app with Horizon's icon on macOS, and a Shell Link written from Microsoft's published MS-SHLLINK layout on Windows. HORIZON_LAUNCHER_DESKTOP points it at a scratch folder. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/launcher-commands.md | 11 + launcher/README.md | 7 + launcher/src/cli.rs | 30 +++ launcher/src/desktop.rs | 4 +- launcher/src/desktop_seams.rs | 6 +- launcher/src/instances_page.rs | 19 +- launcher/src/lib.rs | 1 + launcher/src/main.rs | 4 + launcher/src/shortcut.rs | 427 +++++++++++++++++++++++++++++++++ launcher/src/shortcut/tests.rs | 197 +++++++++++++++ launcher/src/shortcut_page.rs | 69 ++++++ 12 files changed, 766 insertions(+), 11 deletions(-) create mode 100644 launcher/src/shortcut.rs create mode 100644 launcher/src/shortcut/tests.rs create mode 100644 launcher/src/shortcut_page.rs diff --git a/AGENTS.md b/AGENTS.md index 932eb1067..9c702e8ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the - launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to + launcher, `HORIZON_LAUNCHER_TRASH`, `HORIZON_LAUNCHER_CLIPBOARD` and `HORIZON_LAUNCHER_DESKTOP` pointing into the scratch home. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 432b76e72..03a631cf0 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -364,6 +364,17 @@ Export an instance (or a port) to share: its settings, packs, Horizon mods and t MCP: `instance_export`. +## `horizon-launcher instance shortcut` + +Put a shortcut on the desktop that plays an instance (`play --instance`): a .desktop file (also in the applications menu) on Linux, an app on macOS, a .lnk on Windows. + + horizon-launcher instance shortcut [INSTANCE] + +- `INSTANCE`: The instance (default: the selected one) +- `--remove`: Move the instance's shortcuts to the trash instead + +MCP: `instance_shortcut`. + ## `horizon-launcher instance import` Import what a file is, as dropping it on the window does: a shared instance (a .mrpack without mod loaders, such as `instance export` writes, or a game folder zip) becomes a new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into the instance (default: the selected one). diff --git a/launcher/README.md b/launcher/README.md index ad96eece1..963ddd187 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -100,6 +100,13 @@ The opening, then Play ([clip](docs/opening.webm)): pack into the selected instance. A data pack is pointed at the world rows, and the Packs section and the world rows keep taking their own drops. A note in the corner says what happened. `horizon-launcher instance import `. +- **Desktop shortcut**: Home's Instance row has **Shortcut**: a shortcut on the desktop that plays + the selected instance without opening the launcher (`horizon-launcher play --instance `). + A `.desktop` file on Linux (also put in the applications menu, and marked trusted with `gio` + where it exists), a small app with Horizon's icon on macOS, a `.lnk` on Windows + (`horizon_launcher::shortcut`). **Remove shortcut** moves it to the trash; it is found by the + instance id inside it, so a rename doesn't lose it. `horizon-launcher instance shortcut + [instance] [--remove]`; `HORIZON_LAUNCHER_DESKTOP` points it at another folder. - **Console**: Home's Console shows the game's output of this run as it comes: a search (every word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 246538b08..00c21ec66 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -198,6 +198,15 @@ enum InstanceCmd { #[arg(long)] out: Option, }, + /// Put a shortcut on the desktop that plays an instance (`play --instance`): a .desktop + /// file (also in the applications menu) on Linux, an app on macOS, a .lnk on Windows + Shortcut { + /// The instance (default: the selected one) + instance: Option, + /// Move the instance's shortcuts to the trash instead + #[arg(long)] + remove: bool, + }, /// Import what a file is, as dropping it on the window does: a shared instance (a .mrpack /// without mod loaders, such as `instance export` writes, or a game folder zip) becomes a /// new instance; a Java modpack goes to the Modpacks import; a resource or shader pack into @@ -1827,6 +1836,27 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { }; changed(instances::edit(&instance, |m| m.version = pin)?) } + InstanceCmd::Shortcut { instance, remove } => { + use horizon_launcher::shortcut; + let i = match instance { + Some(name) => instances::find(&name)?, + None => instances::selected(), + }; + let paths = match remove { + false => shortcut::make(backend::exe_path(), &i.id, &i.name)?, + true => shortcut::remove(&i.id)?, + }; + if as_json { + json(serde_json::json!({ "instance": i.id, "paths": paths })); + } else if remove && paths.is_empty() { + println!("{} has no shortcut.", i.name); + } else { + let did = if remove { "Moved to the trash" } else { "Made" }; + for path in paths { + println!("{did}: {}", path.display()); + } + } + } InstanceCmd::Import { file, instance } => { use horizon_launcher::import::{self, Dropped}; use horizon_launcher::modpacks; diff --git a/launcher/src/desktop.rs b/launcher/src/desktop.rs index 281850cb6..863923acb 100644 --- a/launcher/src/desktop.rs +++ b/launcher/src/desktop.rs @@ -65,7 +65,7 @@ pub fn data_home() -> Option { } /// Quotes a path for an `Exec` key: inside double quotes, `"`, `` ` ``, `$` and `\` are escaped. -fn quote(path: &Path) -> String { +pub(crate) fn quote(path: &Path) -> String { let mut out = String::from("\""); for c in path.to_string_lossy().chars() { if matches!(c, '"' | '`' | '$' | '\\') { @@ -215,7 +215,7 @@ pub fn needs_repair_in(data: &Path, path: Option<&OsStr>) -> bool { /// What the entry starts: a distributor's wrapper (`HORIZON_LAUNCHER_DESKTOP_EXEC`) when one is /// configured, else the binary at `exe`. -fn target(exe: &Path) -> PathBuf { +pub(crate) fn target(exe: &Path) -> PathBuf { std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") .filter(|path| !path.is_empty()) .map_or_else(|| exe.to_path_buf(), PathBuf::from) diff --git a/launcher/src/desktop_seams.rs b/launcher/src/desktop_seams.rs index edec7ab8d..2815748ea 100644 --- a/launcher/src/desktop_seams.rs +++ b/launcher/src/desktop_seams.rs @@ -7,7 +7,8 @@ //! (text as UTF-8, a picture as its PNG or JPEG bytes). //! //! Test runs point both into their scratch folders, beside `HORIZON_HOME` and -//! `HORIZON_LAUNCHER_HOME`. +//! `HORIZON_LAUNCHER_HOME`, and `HORIZON_LAUNCHER_DESKTOP` too (`shortcut`: where desktop +//! shortcuts go). use std::path::{Path, PathBuf}; pub const TRASH_ENV: &str = "HORIZON_LAUNCHER_TRASH"; @@ -22,7 +23,8 @@ pub fn to_trash(path: &Path) -> Result<(), String> { } } -fn to_folder(path: &Path, dir: &Path) -> Result<(), String> { +/// Moves `path` into `dir` under a free name: the trash of a test run. +pub fn to_folder(path: &Path, dir: &Path) -> Result<(), String> { std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let name = path.file_name().ok_or("Nothing to move")?.to_string_lossy(); let target = (1..) diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs index 273f967df..9af5051fe 100644 --- a/launcher/src/instances_page.rs +++ b/launcher/src/instances_page.rs @@ -590,6 +590,7 @@ impl Launcher { cx.notify(); })), ) + .child(self.shortcut_button(&instance, cx)) .child( button("instance-folder", "Open folder", Kind::Ghost, &t).on_click( move |_, _, cx| { @@ -604,14 +605,20 @@ impl Launcher { Some( div() .flex() - .items_baseline() - .gap(px(10.)) - .child(instance.name.clone()) + .flex_col() .child( - text(theme::CAPTION) - .text_color(t.muted) - .child(played_line(&instance)), + div() + .flex() + .items_baseline() + .gap(px(10.)) + .child(instance.name.clone()) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .child(played_line(&instance)), + ), ) + .children(self.shortcut_note(&instance.id)) .into_any_element(), ), Some(actions.into_any_element()), diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 28c6d21bd..ea896aa21 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -21,6 +21,7 @@ pub mod proxy; pub mod screenshots; pub mod server_list; pub mod servers; +pub mod shortcut; pub mod signed; pub mod sources; pub mod tailscale; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 352ae7e98..257b83226 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -30,6 +30,7 @@ mod perf; mod screenshots_page; mod scrollbar; mod servers_page; +mod shortcut_page; mod theme; mod titlebar; mod while_playing; @@ -250,6 +251,8 @@ struct Launcher { console: console_page::Console, /// What the window did when the game started (`while_playing.rs`). aside: while_playing::Aside, + /// The selected instance's desktop shortcut (`shortcut_page.rs`). + shortcuts: shortcut_page::Shortcuts, /// The name the game made up for an offline player (`horizon-player.txt`), for the top bar. offline_name: Option, /// The player's servers, for the sidebar until the Servers page has read them. @@ -418,6 +421,7 @@ impl Launcher { importing: Default::default(), console: Default::default(), aside: while_playing::Aside::new(window.window_handle()), + shortcuts: Default::default(), offline_name: offline_name(), side_servers: horizon_launcher::servers::list(), art: art::Art::default(), diff --git a/launcher/src/shortcut.rs b/launcher/src/shortcut.rs new file mode 100644 index 000000000..b4e97abd4 --- /dev/null +++ b/launcher/src/shortcut.rs @@ -0,0 +1,427 @@ +//! A shortcut on the desktop that plays one instance: it runs +//! `horizon-launcher play --instance `, so the game starts without the launcher's window. +//! +//! - Linux: ` (Horizon).desktop` on the desktop (executable, and marked trusted with `gio` +//! where it exists, so GNOME starts it), and the same entry in the applications menu +//! (`applications/horizon-instance-.desktop`, `desktop::data_home`). +//! - macOS: ` (Horizon).app`, a small app whose program is a shell script, with Horizon's +//! icon. It has no Dock icon of its own (`LSUIElement`): the game's window is the one to see. +//! - Windows: ` (Horizon).lnk`, a Shell Link as Microsoft's published [MS-SHLLINK] format +//! lays it out, to the launcher's `.exe` with Horizon's icon. +//! +//! Each shortcut names its instance's id inside it, so removing finds it after a rename. +//! `HORIZON_LAUNCHER_DESKTOP` points the desktop folder elsewhere, for tests. +//! +//! [MS-SHLLINK]: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-shllink/ +use crate::desktop; +use crate::desktop_seams; +use std::fs; +use std::path::{Path, PathBuf}; + +pub const DESKTOP_ENV: &str = "HORIZON_LAUNCHER_DESKTOP"; +const MAC_ICON: &[u8] = include_bytes!("../../packaging/icons/horizon.icns"); +/// The key a Linux shortcut names its instance with. +const INSTANCE_KEY: &str = "X-Horizon-Instance"; +/// And a macOS one, in its Info.plist. +const MAC_KEY: &str = "HorizonInstance"; + +/// The kinds of shortcut, one per system: all of them can be written and tested anywhere. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum System { + Linux, + Mac, + Windows, +} + +impl System { + pub fn here() -> Self { + if cfg!(target_os = "macos") { + Self::Mac + } else if cfg!(windows) { + Self::Windows + } else { + Self::Linux + } + } + + fn extension(self) -> &'static str { + match self { + Self::Linux => "desktop", + Self::Mac => "app", + Self::Windows => "lnk", + } + } +} + +/// The desktop folder: `HORIZON_LAUNCHER_DESKTOP`, else the system's. +pub fn desktop_dir() -> Option { + std::env::var_os(DESKTOP_ENV) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .or_else(dirs::desktop_dir) +} + +/// The shortcut's file name: the instance's name without the characters a file name can't +/// hold on any of the three systems. +pub fn file_name(name: &str, system: System) -> String { + let clean: String = name + .chars() + .map(|c| match c { + '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '-', + c if c.is_control() => '-', + c => c, + }) + .collect(); + let clean = clean.trim().trim_matches('.'); + let clean = if clean.is_empty() { "Instance" } else { clean }; + format!("{clean} (Horizon).{}", system.extension()) +} + +/// The id as a file name or bundle id part: letters, digits and `-`. +fn slug(id: &str) -> String { + id.chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect() +} + +/// A Linux `.desktop` entry that plays the instance. +pub fn desktop_entry(exe: &Path, id: &str, name: &str) -> String { + let field = |s: &str| s.replace(['\n', '\r'], " "); + format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name={name}\n\ + Comment=Play {name} in Horizon\n\ + Exec={} play --instance {}\n\ + TryExec={}\n\ + Icon=horizon\n\ + Terminal=false\n\ + Categories=Game;\n\ + StartupWMClass=horizon\n\ + {INSTANCE_KEY}={id}\n", + desktop::quote(exe), + desktop::quote(Path::new(id)), + exe.display(), + name = field(name), + id = field(id), + ) +} + +/// `'text'` for a POSIX shell. +fn sh_quote(text: &str) -> String { + format!("'{}'", text.replace('\'', r"'\''")) +} + +fn xml(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// A macOS app's files, by path inside the `.app`, and whether each is a program. +pub fn mac_app(exe: &Path, id: &str, name: &str) -> Vec<(&'static str, Vec, bool)> { + let plist = format!( + r#" + + + + CFBundleExecutable + play + CFBundleIdentifier + dev.horizon.instance.{} + CFBundleName + {} + CFBundleIconFile + horizon + CFBundlePackageType + APPL + LSUIElement + + {MAC_KEY} + {} + + +"#, + slug(id), + xml(name), + xml(id), + ); + let script = format!( + "#!/bin/sh\n# Plays the Horizon instance {}.\nexec {} play --instance {}\n", + name.replace('\n', " "), + sh_quote(&exe.to_string_lossy()), + sh_quote(id), + ); + vec![ + ("Contents/Info.plist", plist.into_bytes(), false), + ("Contents/MacOS/play", script.into_bytes(), true), + ("Contents/Resources/horizon.icns", MAC_ICON.to_vec(), false), + ] +} + +/// The arguments of a Windows shortcut: the id in quotes, with its own quotes escaped. +fn windows_args(id: &str) -> String { + format!("play --instance \"{}\"", id.replace('"', "\\\"")) +} + +fn utf16(text: &str) -> Vec { + text.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +/// A Windows Shell Link ([MS-SHLLINK]) to `exe` (a Windows path) with `args`: the header, a +/// LinkInfo with the local path (ANSI and Unicode), then the name, working folder, arguments and +/// icon as Unicode strings. +pub fn lnk(exe: &str, args: &str, comment: &str) -> Vec { + const HAS_LINK_INFO: u32 = 0x02; + const HAS_NAME: u32 = 0x04; + const HAS_WORKING_DIR: u32 = 0x10; + const HAS_ARGUMENTS: u32 = 0x20; + const HAS_ICON_LOCATION: u32 = 0x40; + const IS_UNICODE: u32 = 0x80; + const FILE_ATTRIBUTE_NORMAL: u32 = 0x80; + const SW_SHOWNORMAL: u32 = 1; + let flags = + HAS_LINK_INFO | HAS_NAME | HAS_WORKING_DIR | HAS_ARGUMENTS | HAS_ICON_LOCATION | IS_UNICODE; + let mut out = Vec::new(); + out.extend(0x4Cu32.to_le_bytes()); + // CLSID 00021401-0000-0000-C000-000000000046. + out.extend([ + 0x01, 0x14, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x46, + ]); + out.extend(flags.to_le_bytes()); + out.extend(FILE_ATTRIBUTE_NORMAL.to_le_bytes()); + out.extend([0; 24]); // creation, access and write times: unknown + out.extend(0u32.to_le_bytes()); // file size + out.extend(0i32.to_le_bytes()); // icon index + out.extend(SW_SHOWNORMAL.to_le_bytes()); + out.extend([0; 2 + 2 + 4 + 4]); // hot key, reserved + + // LinkInfo: a header with the Unicode offsets (0x24 bytes), a VolumeID for a fixed drive + // with no label, the path in ANSI (anything else as '?') and in UTF-16, and empty suffixes. + let header = 0x24u32; + let volume: Vec = [0x11u32, 3, 0, 0x10] + .iter() + .flat_map(|v| v.to_le_bytes()) + .chain([0]) + .collect(); + let ansi: Vec = exe + .chars() + .map(|c| if c.is_ascii() { c as u8 } else { b'?' }) + .chain([0]) + .collect(); + let wide: Vec = utf16(exe).into_iter().chain([0, 0]).collect(); + let volume_at = header; + let path_at = volume_at + volume.len() as u32; + let suffix_at = path_at + ansi.len() as u32; + let wide_at = suffix_at + 1; + let wide_suffix_at = wide_at + wide.len() as u32; + let size = wide_suffix_at + 2; + for v in [ + size, + header, + 1, // VolumeIDAndLocalBasePath + volume_at, + path_at, + 0, // no network path + suffix_at, + wide_at, + wide_suffix_at, + ] { + out.extend(v.to_le_bytes()); + } + out.extend(volume); + out.extend(ansi); + out.push(0); + out.extend(wide); + out.extend([0, 0]); + + let folder = exe.rsplit_once('\\').map_or("", |(dir, _)| dir); + for text in [comment, folder, args, exe] { + out.extend((text.encode_utf16().count() as u16).to_le_bytes()); + out.extend(utf16(text)); + } + out.extend(0u32.to_le_bytes()); // no extra data + out +} + +/// Whether the shortcut at `path` plays the instance `id`. +fn plays(path: &Path, id: &str) -> bool { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or(""); + match ext { + "desktop" => fs::read_to_string(path) + .is_ok_and(|t| t.lines().any(|l| l == format!("{INSTANCE_KEY}={id}"))), + "app" => fs::read_to_string(path.join("Contents/Info.plist")) + .is_ok_and(|t| t.contains(&format!("{MAC_KEY}\n\t{}", xml(id)))), + "lnk" => fs::read(path).is_ok_and(|b| { + let want = utf16(&windows_args(id)); + b.windows(want.len()).any(|w| w == want) + }), + _ => false, + } +} + +/// Writes `bytes` beside `path` and renames it in, so nothing reads half a file. +fn write(path: &Path, bytes: &[u8], program: bool) -> Result<(), String> { + let fail = |e: std::io::Error| format!("{}: {e}", path.display()); + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(fail)?; + } + let temp = path.with_extension("horizon-tmp"); + fs::write(&temp, bytes).map_err(fail)?; + #[cfg(unix)] + if program { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&temp, fs::Permissions::from_mode(0o755)).map_err(fail)?; + } + #[cfg(not(unix))] + let _ = program; + fs::rename(&temp, path).map_err(fail) +} + +/// Moves a file or folder out of the way, where the player can get it back. +pub type Trash<'a> = &'a dyn Fn(&Path) -> Result<(), String>; + +/// Makes the shortcut for `system` in `desktop` (and, for Linux, the menu entry under +/// `menu`, an `applications` folder). The instance's shortcut of the same name is rewritten; +/// one under an older name goes to `trash`. Returns what it wrote. +pub fn make_in( + system: System, + desktop: &Path, + menu: Option<&Path>, + exe: &Path, + id: &str, + name: &str, + trash: Trash, +) -> Result, String> { + let path = desktop.join(file_name(name, system)); + let item = menu.map(|m| m.join(format!("horizon-instance-{}.desktop", slug(id)))); + for old in find_in(desktop, menu, id) { + if old != path && Some(&old) != item.as_ref() { + trash(&old)?; + } + } + if path.exists() && !plays(&path, id) { + return Err(format!( + "{} is already on the desktop, and isn't this instance's shortcut.", + path.file_name().unwrap().to_string_lossy() + )); + } + let mut made = vec![path.clone()]; + match system { + System::Linux => { + let entry = desktop_entry(exe, id, name); + write(&path, entry.as_bytes(), true)?; + if let Some(item) = item { + write(&item, entry.as_bytes(), false)?; + made.push(item); + } + } + System::Mac => { + for (inside, bytes, program) in mac_app(exe, id, name) { + write(&path.join(inside), &bytes, program)?; + } + } + System::Windows => write( + &path, + &lnk( + &exe.to_string_lossy(), + &windows_args(id), + &format!("Play {name} in Horizon"), + ), + false, + )?, + } + Ok(made) +} + +/// The instance's shortcuts in `desktop` and the menu. +pub fn find_in(desktop: &Path, menu: Option<&Path>, id: &str) -> Vec { + let mut found: Vec = fs::read_dir(desktop) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| plays(p, id)) + .collect(); + if let Some(item) = menu + .map(|m| m.join(format!("horizon-instance-{}.desktop", slug(id)))) + .filter(|p| plays(p, id)) + { + found.push(item); + } + found.sort(); + found +} + +/// Moves the instance's shortcuts to `trash`. Returns what it moved. +pub fn remove_in( + desktop: &Path, + menu: Option<&Path>, + id: &str, + trash: Trash, +) -> Result, String> { + let found = find_in(desktop, menu, id); + for path in &found { + trash(path)?; + } + Ok(found) +} + +fn menu() -> Option { + (System::here() == System::Linux) + .then(desktop::data_home) + .flatten() + .map(|d| d.join("applications")) +} + +fn desktop_or_err() -> Result { + desktop_dir().ok_or_else(|| "This computer has no desktop folder.".into()) +} + +/// Makes the shortcut on this computer's desktop that plays `id`, starting `exe`. +pub fn make(exe: &Path, id: &str, name: &str) -> Result, String> { + let desktop = desktop_or_err()?; + let made = make_in( + System::here(), + &desktop, + menu().as_deref(), + &desktop::target(exe), + id, + name, + &desktop_seams::to_trash, + )?; + if System::here() == System::Linux { + // GNOME starts a desktop file only once it is trusted; elsewhere this does nothing. + let _ = std::process::Command::new("gio") + .args(["set", "-t", "string"]) + .arg(&made[0]) + .args(["metadata::trusted", "true"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); + } + Ok(made) +} + +/// The instance's shortcuts on this computer. +pub fn find(id: &str) -> Vec { + desktop_dir() + .map(|d| find_in(&d, menu().as_deref(), id)) + .unwrap_or_default() +} + +/// Moves the instance's shortcuts on this computer to the trash. +pub fn remove(id: &str) -> Result, String> { + remove_in( + &desktop_or_err()?, + menu().as_deref(), + id, + &desktop_seams::to_trash, + ) +} + +#[cfg(test)] +#[path = "shortcut/tests.rs"] +mod tests; diff --git a/launcher/src/shortcut/tests.rs b/launcher/src/shortcut/tests.rs new file mode 100644 index 000000000..ce49d5b20 --- /dev/null +++ b/launcher/src/shortcut/tests.rs @@ -0,0 +1,197 @@ +use super::*; + +fn scratch(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-shortcut-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + root +} + +#[test] +fn names_fit_every_system() { + assert_eq!( + file_name("Hardcore", System::Linux), + "Hardcore (Horizon).desktop" + ); + assert_eq!( + file_name("A/B: C?", System::Windows), + "A-B- C- (Horizon).lnk" + ); + assert_eq!(file_name(" .. ", System::Mac), "Instance (Horizon).app"); + assert_eq!(slug("port:all the mods"), "port-all-the-mods"); +} + +#[test] +fn a_linux_entry_plays_its_instance() { + let entry = desktop_entry( + Path::new("/opt/My Horizon/horizon-launcher"), + "port:atm", + "ATM", + ); + assert!(entry.starts_with("[Desktop Entry]\nType=Application\nName=ATM\n")); + assert!(entry + .contains("\nExec=\"/opt/My Horizon/horizon-launcher\" play --instance \"port:atm\"\n")); + assert!(entry.contains("\nTryExec=/opt/My Horizon/horizon-launcher\n")); + assert!(entry.ends_with("\nX-Horizon-Instance=port:atm\n")); + let odd = desktop_entry(Path::new("/x"), "a", "Two\nlines"); + assert!(odd.contains("Name=Two lines\n")); +} + +#[test] +fn a_mac_app_runs_a_script_that_plays_its_instance() { + let files = mac_app( + Path::new("/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher"), + "it's", + "Tom & Jerry", + ); + let (_, plist, _) = &files[0]; + let plist = String::from_utf8(plist.clone()).unwrap(); + assert!(plist.contains("Tom & Jerry")); + assert!(plist.contains("dev.horizon.instance.it-s")); + assert!(plist.contains("LSUIElement\n\t")); + let (path, script, program) = &files[1]; + assert_eq!((*path, *program), ("Contents/MacOS/play", true)); + assert!(String::from_utf8(script.clone()).unwrap().ends_with( + "exec '/Applications/Horizon Launcher.app/Contents/MacOS/horizon-launcher' play \ + --instance 'it'\\''s'\n" + )); + assert_eq!(files[2].1, MAC_ICON); +} + +/// Reads a Shell Link back by its spec: the header, the LinkInfo's paths, and the strings. +fn read_lnk(b: &[u8]) -> (u32, String, String, Vec) { + let u32_at = |at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + assert_eq!(u32_at(0), 0x4C); + assert_eq!( + &b[4..20], + &[1, 0x14, 2, 0, 0, 0, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46] + ); + let flags = u32_at(20); + assert_eq!(u32_at(60), 1, "show normal"); + let info = 76; + let size = u32_at(info) as usize; + assert_eq!(u32_at(info + 4), 0x24); + assert_eq!(u32_at(info + 8), 1); + let volume = info + u32_at(info + 12) as usize; + assert_eq!((u32_at(volume), u32_at(volume + 4)), (0x11, 3)); + let cstr = |at: usize| { + let end = b[at..].iter().position(|&c| c == 0).unwrap(); + String::from_utf8(b[at..at + end].to_vec()).unwrap() + }; + let ansi = cstr(info + u32_at(info + 16) as usize); + assert_eq!(cstr(info + u32_at(info + 24) as usize), ""); + let wide_at = info + u32_at(info + 28) as usize; + let wide: Vec = b[wide_at..] + .chunks(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .take_while(|&c| c != 0) + .collect(); + let wide = String::from_utf16(&wide).unwrap(); + assert_eq!( + ansi.replace('?', ""), + wide.replace(|c: char| !c.is_ascii(), "") + ); + let mut at = info + size; + let mut strings = Vec::new(); + for _ in 0..4 { + let n = u16::from_le_bytes([b[at], b[at + 1]]) as usize; + let units: Vec = b[at + 2..at + 2 + 2 * n] + .chunks(2) + .map(|c| u16::from_le_bytes([c[0], c[1]])) + .collect(); + strings.push(String::from_utf16(&units).unwrap()); + at += 2 + 2 * n; + } + assert_eq!(&b[at..], &[0, 0, 0, 0], "the terminal block ends it"); + (flags, ansi, wide, strings) +} + +#[test] +fn a_windows_shortcut_is_a_shell_link_to_the_launcher() { + let exe = r"C:\Users\Zoé\AppData\Local\Horizon\horizon-launcher.exe"; + let b = lnk(exe, &windows_args("port:atm"), "Play ATM in Horizon"); + let (flags, ansi, wide, strings) = read_lnk(&b); + assert_eq!(flags, 0x02 | 0x04 | 0x10 | 0x20 | 0x40 | 0x80); + assert_eq!( + ansi, + r"C:\Users\Zo?\AppData\Local\Horizon\horizon-launcher.exe" + ); + assert_eq!(wide, exe); + assert_eq!( + strings, + [ + "Play ATM in Horizon", + r"C:\Users\Zoé\AppData\Local\Horizon", + "play --instance \"port:atm\"", + exe, + ] + ); +} + +#[test] +fn shortcuts_are_made_found_renamed_and_removed() { + let root = scratch("make"); + let (desktop, menu, trash) = ( + root.join("Desktop"), + root.join("applications"), + root.join("trash"), + ); + let bin = trash.clone(); + let trash_fn = move |p: &Path| desktop_seams::to_folder(p, &bin); + let t: Trash = &trash_fn; + let exe = Path::new("/opt/horizon-launcher"); + for system in [System::Linux, System::Mac, System::Windows] { + let made = make_in( + system, + &desktop, + Some(&menu), + exe, + "hardcore", + "Hardcore", + t, + ) + .unwrap(); + assert_eq!(made[0], desktop.join(file_name("Hardcore", system))); + assert_eq!(find_in(&desktop, Some(&menu), "hardcore"), { + let mut m = made.clone(); + m.sort(); + m + }); + // Again: rewritten in place, nothing in the trash. + make_in( + system, + &desktop, + Some(&menu), + exe, + "hardcore", + "Hardcore", + t, + ) + .unwrap(); + assert!(!trash.exists()); + // Renamed: the old one goes, the new one is there. + let made = make_in(system, &desktop, Some(&menu), exe, "hardcore", "Hard", t).unwrap(); + assert!(made[0].ends_with(file_name("Hard", system))); + assert!(!desktop.join(file_name("Hardcore", system)).exists()); + assert!(find_in(&desktop, Some(&menu), "skyblock").is_empty()); + let gone = remove_in(&desktop, Some(&menu), "hardcore", t).unwrap(); + assert_eq!(gone.len(), made.len()); + assert!(find_in(&desktop, Some(&menu), "hardcore").is_empty()); + fs::remove_dir_all(&trash).unwrap(); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let made = make_in(System::Mac, &desktop, None, exe, "a", "A", t).unwrap(); + let mode = fs::metadata(made[0].join("Contents/MacOS/play")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o111, 0o111); + } + // Someone else's file of that name stays. + fs::write(desktop.join("Mine (Horizon).desktop"), "not ours").unwrap(); + let err = make_in(System::Linux, &desktop, None, exe, "mine", "Mine", t).unwrap_err(); + assert!(err.contains("isn't this instance's shortcut"), "{err}"); + fs::remove_dir_all(&root).unwrap(); +} diff --git a/launcher/src/shortcut_page.rs b/launcher/src/shortcut_page.rs new file mode 100644 index 000000000..68eb9ca2d --- /dev/null +++ b/launcher/src/shortcut_page.rs @@ -0,0 +1,69 @@ +//! The Instance row's desktop shortcut (`horizon_launcher::shortcut`): make one that plays the +//! selected instance, or take it away. +use super::*; +use horizon_launcher::shortcut; + +#[derive(Default)] +pub(super) struct Shortcuts { + /// The instance last looked at, and whether it has a shortcut: read again only when the + /// selection changes or a button is pressed, not on every frame. + seen: Option<(String, bool)>, + /// What the last press did, for that instance. + note: Option<(String, Result)>, +} + +impl Launcher { + fn has_shortcut(&mut self, id: &str) -> bool { + match &self.shortcuts.seen { + Some((seen, has)) if seen == id => *has, + _ => { + let has = !shortcut::find(id).is_empty(); + self.shortcuts.seen = Some((id.to_string(), has)); + has + } + } + } + + fn toggle_shortcut(&mut self, id: String, name: String) { + let has = self.has_shortcut(&id); + let done = match has { + false => shortcut::make(backend::exe_path(), &id, &name).map(|made| { + let file = made[0].file_name().unwrap_or_default().to_string_lossy(); + format!("{file} is on your desktop: it plays {name}.") + }), + true => shortcut::remove(&id).map(|_| format!("{name}'s shortcut is in the trash.")), + }; + self.shortcuts.seen = None; + self.shortcuts.note = Some((id, done)); + } + + /// The row's button. + pub(super) fn shortcut_button( + &mut self, + instance: &instances::Instance, + cx: &mut Context, + ) -> Stateful
{ + let t = self.theme; + let label = match self.has_shortcut(&instance.id) { + true => "Remove shortcut", + false => "Shortcut", + }; + let (id, name) = (instance.id.clone(), instance.name.clone()); + button("instance-shortcut", label, Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.toggle_shortcut(id.clone(), name.clone()); + cx.notify(); + }, + )) + } + + /// What the last press did, under the row, while that instance is selected. + pub(super) fn shortcut_note(&self, id: &str) -> Option
{ + let t = self.theme; + let (_, said) = self.shortcuts.note.as_ref().filter(|(n, _)| n == id)?; + Some(match said { + Ok(said) => text(theme::CAPTION).text_color(t.muted).child(said.clone()), + Err(e) => text(theme::CAPTION).text_color(t.danger).child(e.clone()), + }) + } +} From 7115c708e110e7077f8c4ca037295ad52e3db267 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:22:34 +0100 Subject: [PATCH 47/65] launcher: pre-launch command, wrapper and environment per instance Home's Instance row gets Launch...: a shell command run in the instance's folder before the game (which starts only if it succeeds), a wrapper the game runs through, and environment variables, kept in instances.json. The game stays one process: /bin/sh runs the command and execs the wrapper and game through "$@" on Unix, cmd /C on Windows. The window's Play and `play` both use them. CLI and MCP: instance launch (confirm needed over MCP). The Instance row's actions move under its name, and editing an instance that shares its name with an import works again. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 13 ++ launcher/README.md | 8 ++ launcher/src/cli.rs | 53 +++++++- launcher/src/cli_tools.rs | 2 + launcher/src/import/tests.rs | 1 + launcher/src/instances.rs | 17 ++- launcher/src/instances/tests.rs | 12 ++ launcher/src/instances_page.rs | 23 +++- launcher/src/launch.rs | 220 ++++++++++++++++++++++++++++++++ launcher/src/launch/tests.rs | 143 +++++++++++++++++++++ launcher/src/launch_page.rs | 137 ++++++++++++++++++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 12 ++ launcher/src/servers_page.rs | 10 +- 14 files changed, 646 insertions(+), 6 deletions(-) create mode 100644 launcher/src/launch.rs create mode 100644 launcher/src/launch/tests.rs create mode 100644 launcher/src/launch_page.rs diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 03a631cf0..41108a86e 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -364,6 +364,19 @@ Export an instance (or a port) to share: its settings, packs, Horizon mods and t MCP: `instance_export`. +## `horizon-launcher instance launch` + +Show or set what runs around an instance's game: a shell command before it (the game starts only if it succeeds), a wrapper it runs through (`nice -n 5`), and environment variables ("NAME=value NAME2=value"). An empty value clears one. + + horizon-launcher instance launch + +- `INSTANCE` +- `--pre-launch` +- `--wrapper` +- `--env` + +MCP: `instance_launch`, needs `confirm: true`. + ## `horizon-launcher instance shortcut` Put a shortcut on the desktop that plays an instance (`play --instance`): a .desktop file (also in the applications menu) on Linux, an app on macOS, a .lnk on Windows. diff --git a/launcher/README.md b/launcher/README.md index 963ddd187..41ff3c915 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -100,6 +100,14 @@ The opening, then Play ([clip](docs/opening.webm)): pack into the selected instance. A data pack is pointed at the world rows, and the Packs section and the world rows keep taking their own drops. A note in the corner says what happened. `horizon-launcher instance import `. +- **Launch options**: Home's Instance row has **Launch…**: per instance, a shell command run in its + folder before the game (the game starts only if it succeeds), a wrapper the game runs through + (`nice -n 5`), and environment variables (`NAME=value OTHER="two words"`), kept in + `instances.json` (`horizon_launcher::launch`). The game stays one process the launcher follows: + on Unix `/bin/sh` runs the command and then `exec`s the wrapper and the game, whose words pass + through `"$@"` untouched; on Windows `cmd /C` runs ` && `. Both the window's Play + and `play` use them. `horizon-launcher instance launch [--pre-launch …] + [--wrapper …] [--env …]` (an MCP agent needs `confirm: true`: it sets commands Play runs). - **Desktop shortcut**: Home's Instance row has **Shortcut**: a shortcut on the desktop that plays the selected instance without opening the launcher (`horizon-launcher play --instance `). A `.desktop` file on Linux (also put in the applications menu, and marked trusted with `gio` diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 00c21ec66..38150917f 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -198,6 +198,18 @@ enum InstanceCmd { #[arg(long)] out: Option, }, + /// Show or set what runs around an instance's game: a shell command before it (the game + /// starts only if it succeeds), a wrapper it runs through (`nice -n 5`), and environment + /// variables ("NAME=value NAME2=value"). An empty value clears one + Launch { + instance: String, + #[arg(long)] + pre_launch: Option, + #[arg(long)] + wrapper: Option, + #[arg(long)] + env: Option, + }, /// Put a shortcut on the desktop that plays an instance (`play --instance`): a .desktop /// file (also in the applications menu) on Linux, an app on macOS, a .lnk on Windows Shortcut { @@ -938,7 +950,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } cmd.args(arg); let started = std::time::Instant::now(); - let played = attached(cmd); + let played = attached(horizon_launcher::launch::wrap(cmd, &instance.launch)); if let Err(e) = instances::record_play(&instance.id, started.elapsed()) { eprintln!("Play time not saved: {e}"); } @@ -1836,6 +1848,45 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> { }; changed(instances::edit(&instance, |m| m.version = pin)?) } + InstanceCmd::Launch { + instance, + pre_launch, + wrapper, + env, + } => { + use horizon_launcher::launch; + let env = env.as_deref().map(launch::parse_env).transpose()?; + let changing = pre_launch.is_some() || wrapper.is_some() || env.is_some(); + let i = match changing { + false => instances::find(&instance)?, + true => instances::edit(&instance, |m| { + if let Some(p) = pre_launch { + m.launch.pre_launch = p.trim().to_string(); + } + if let Some(w) = wrapper { + m.launch.wrapper = w.trim().to_string(); + } + if let Some(e) = env { + m.launch.env = e; + } + })?, + }; + let l = &i.launch; + if as_json { + json(serde_json::json!({ + "instance": i.id, "pre_launch": l.pre_launch, "wrapper": l.wrapper, "env": l.env, + })); + } else { + println!( + "{}: {}", + i.name, + l.summary().unwrap_or("nothing around the game".into()) + ); + println!(" pre-launch: {}", l.pre_launch); + println!(" wrapper: {}", l.wrapper); + println!(" env: {}", launch::env_line(&l.env)); + } + } InstanceCmd::Shortcut { instance, remove } => { use horizon_launcher::shortcut; let i = match instance { diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index fad614d0f..a6ddbfa34 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -32,6 +32,8 @@ pub const DESTRUCTIVE: &[&str] = &[ "packs remove", "worlds datapack-remove", "unshare-log", + // It sets shell commands the next Play runs: the player says yes first. + "instance launch", ]; /// Commands that send something or reach other people: only when the player asks. diff --git a/launcher/src/import/tests.rs b/launcher/src/import/tests.rs index dcbe0e548..1287b475e 100644 --- a/launcher/src/import/tests.rs +++ b/launcher/src/import/tests.rs @@ -48,6 +48,7 @@ fn maker(root: &Path) -> impl Fn(&str) -> Result + '_ { version: None, played: Duration::ZERO, last_played: None, + launch: Default::default(), }) } } diff --git a/launcher/src/instances.rs b/launcher/src/instances.rs index 34d9bb408..38951bf02 100644 --- a/launcher/src/instances.rs +++ b/launcher/src/instances.rs @@ -8,6 +8,7 @@ //! launcher's data folder, so renaming one never moves a folder. use crate::backend; use crate::browser::horizon::pack as registry_pack; +use crate::launch::Launch; use crate::modpacks; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -97,6 +98,9 @@ pub struct Meta { /// When its last run ended, in seconds since 1970. #[serde(default, skip_serializing_if = "Option::is_none")] pub last_played: Option, + /// What runs around the game: a pre-launch command, a wrapper, variables (`launch`). + #[serde(default, skip_serializing_if = "Launch::is_empty")] + pub launch: Launch, } fn is_zero(n: &u64) -> bool { @@ -140,6 +144,8 @@ pub struct Instance { pub version: Option, pub played: Duration, pub last_played: Option, + /// What runs around the game (`launch::wrap`). + pub launch: Launch, } impl Instance { @@ -213,6 +219,7 @@ fn list_in(game_home: &Path, data: &Path) -> Vec { last_played: meta .last_played .map(|s| UNIX_EPOCH + Duration::from_secs(s)), + launch: meta.launch, id, kind, work, @@ -403,9 +410,13 @@ fn edit_in( if name.is_empty() { return Err("An instance needs a name.".into()); } - if all - .iter() - .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) + // Only a new name is checked: an import can share a name, and changing anything + // else about it must still work. + let renamed = !name.eq_ignore_ascii_case(&instance.name); + if renamed + && all + .iter() + .any(|i| i.id != instance.id && i.name.eq_ignore_ascii_case(name)) { return Err(format!("There is already an instance called {name}.")); } diff --git a/launcher/src/instances/tests.rs b/launcher/src/instances/tests.rs index 22f8f2b00..b2e2fe6fe 100644 --- a/launcher/src/instances/tests.rs +++ b/launcher/src/instances/tests.rs @@ -149,6 +149,18 @@ fn names_stay_unique_and_packs_are_not_copied() { // An empty group is no group. let grouped = edit_in(&home, &data, "Survival", |m| m.group = Some(" ".into())).unwrap(); assert_eq!(grouped.group, None); + // An import named like an instance: both can still change everything but their names. + let mut store = Store::load(&data); + store.instances.entry(port.id.clone()).or_default().name = Some("Survival".into()); + store.save(&data).unwrap(); + let launched = edit_in(&home, &data, "survival", |m| { + m.launch.wrapper = "nice".into() + }) + .unwrap(); + assert_eq!(launched.launch.wrapper, "nice"); + assert!(edit_in(&home, &data, "survival-2", |m| m.name = + Some("survival".into())) + .is_err()); fs::remove_dir_all(&root).unwrap(); } diff --git a/launcher/src/instances_page.rs b/launcher/src/instances_page.rs index 9af5051fe..b0777e9ba 100644 --- a/launcher/src/instances_page.rs +++ b/launcher/src/instances_page.rs @@ -551,9 +551,13 @@ impl Launcher { instance.clone(), instance.name.clone(), ); + // Under the name, wrapping: six actions don't fit beside it at the window's narrowest. let actions = div() .flex() + .flex_wrap() .gap(px(8.)) + .mt(px(6.)) + .ml(px(-14.)) .child( button("instance-edit", "Edit…", Kind::Ghost, &t).on_click(cx.listener( move |this, _: &ClickEvent, _, cx| { @@ -590,6 +594,22 @@ impl Launcher { cx.notify(); })), ) + .child( + button( + "instance-launch", + if self.launch.is_some() { + "Close launch" + } else { + "Launch…" + }, + Kind::Ghost, + &t, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.toggle_launch(); + cx.notify(); + })), + ) .child(self.shortcut_button(&instance, cx)) .child( button("instance-folder", "Open folder", Kind::Ghost, &t).on_click( @@ -619,9 +639,10 @@ impl Launcher { ), ) .children(self.shortcut_note(&instance.id)) + .child(actions) .into_any_element(), ), - Some(actions.into_any_element()), + None, &t, )) } diff --git a/launcher/src/launch.rs b/launcher/src/launch.rs new file mode 100644 index 000000000..486f5f469 --- /dev/null +++ b/launcher/src/launch.rs @@ -0,0 +1,220 @@ +//! What runs around the game for one instance (`instances::Meta::launch`): a command run before +//! it, a wrapper it runs through, and environment variables. All empty by default. +//! +//! [`wrap`] turns the game's command into one process that does all three, so the launcher still +//! follows one program (its output, its exit, Stop): +//! +//! - Unix: `/bin/sh -c '() || exit; exec "$@"' horizon `. +//! The pre-launch command is the player's own shell line, run in the instance's folder; the +//! game's words go through `"$@"`, so they are never parsed by the shell. `exec` makes the +//! shell become the wrapper (or the game). +//! - Windows: `cmd /D /S /C " && "`, each word quoted. +//! +//! Without a pre-launch command the wrapper is the program itself, and no shell runs. +use crate::backend::split_args; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::ffi::{OsStr, OsString}; +use std::process::Command; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Launch { + /// A shell command run in the instance's folder before the game; the game starts only if it + /// succeeds. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub pre_launch: String, + /// A command line the game runs through, such as `nice -n 5` (quotes group a word). + #[serde(default, skip_serializing_if = "String::is_empty")] + pub wrapper: String, + /// Environment variables for the game (and the two commands above). + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub env: BTreeMap, +} + +impl Launch { + pub fn is_empty(&self) -> bool { + self == &Launch::default() + } + + /// What it does, in one line, or None when nothing. + pub fn summary(&self) -> Option { + let mut parts = Vec::new(); + if !self.pre_launch.trim().is_empty() { + parts.push(format!("runs {} first", self.pre_launch.trim())); + } + if !self.wrapper.trim().is_empty() { + parts.push(format!("through {}", self.wrapper.trim())); + } + match self.env.len() { + 0 => {} + 1 => parts.push("with 1 variable".into()), + n => parts.push(format!("with {n} variables")), + } + (!parts.is_empty()).then(|| parts.join(", ")) + } +} + +fn valid_key(key: &str) -> bool { + let mut chars = key.chars(); + chars + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// `KEY=value KEY2="two words"` (one line, or one per line) as variables. +pub fn parse_env(text: &str) -> Result, String> { + let mut env = BTreeMap::new(); + for word in split_args(text) { + let (key, value) = word + .split_once('=') + .ok_or_else(|| format!("{word}: write it as NAME=value"))?; + if !valid_key(key) { + return Err(format!( + "{key}: a variable's name is letters, digits and _, not starting with a digit" + )); + } + env.insert(key.to_string(), value.to_string()); + } + Ok(env) +} + +/// The variables as [`parse_env`] reads them back. +pub fn env_line(env: &BTreeMap) -> String { + env.iter() + .map( + |(k, v)| match v.is_empty() || v.contains([' ', '"', '\'', '\\']) { + true => format!("{k}=\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\"")), + false => format!("{k}={v}"), + }, + ) + .collect::>() + .join(" ") +} + +/// The Unix script: the pre-launch command (in a subshell, so its `exit` doesn't end the script +/// before the message), then the rest of the arguments as the program. +fn script(pre_launch: &str) -> String { + format!( + "(\n{pre_launch}\n) || {{ s=$?; echo \"The pre-launch command failed (exit $s), so the \ + game did not start.\" >&2; exit $s; }}\nexec \"$@\"" + ) +} + +/// A word quoted for a Windows command line, as programs built with the C runtime read it back. +fn windows_quote(word: &OsStr) -> String { + let word = word.to_string_lossy(); + if !word.is_empty() && !word.contains([' ', '\t', '"']) { + return word.into_owned(); + } + let mut out = String::from("\""); + let mut slashes = 0; + for c in word.chars() { + match c { + '\\' => slashes += 1, + '"' => { + out.extend(std::iter::repeat_n('\\', slashes * 2 + 1)); + out.push('"'); + slashes = 0; + } + c => { + out.extend(std::iter::repeat_n('\\', slashes)); + out.push(c); + slashes = 0; + } + } + } + out.extend(std::iter::repeat_n('\\', slashes * 2)); + out.push('"'); + out +} + +/// How [`wrap`] runs a command on each system, apart from the variables and the folder: the +/// program and its arguments. +#[derive(Debug, PartialEq, Eq)] +pub enum Plan { + /// Run as given (`words[0]` is the program). + Direct(Vec), + /// `/bin/sh -c